Skip to content

The agent that grows with you

refactor(tools): pack/hug bracket spans (AST-verified)

Teknium71f3fb1f0f06
diff --git a/tools/plugin_guard.py b/tools/plugin_guard.py
index 38ce05fce2c..7d583ba0a39 100644
--- a/tools/plugin_guard.py
+++ b/tools/plugin_guard.py
@@ -18,16 +18,14 @@ from typing import Iterator, List, Optional, Tuple
from tools.skills_guard import (
Finding, ScanResult, SUSPICIOUS_BINARY_EXTENSIONS, _determine_verdict, format_scan_report,
- scan_file,
-)
+ scan_file)
PLUGIN_SCANNER_VERSION = "plugin-guard-v1"
# Never scanned: VCS internals, caches, vendored envs.
EXCLUDED_DIRS = {
".git", "__pycache__", "node_modules", ".venv", "venv",
- ".mypy_cache", ".pytest_cache", ".ruff_cache", ".tox",
-}
+ ".mypy_cache", ".pytest_cache", ".ruff_cache", ".tox"}
# Code files, where "reads an env secret" / "HTTP call with a key" is the normal
# documented plugin pattern (requires_env).
@@ -55,16 +53,14 @@ CODE_EXEMPT_PATTERN_IDS = {
# and base64-encode credentials (HTTP Basic auth).
"agent_config_mod",
"agent_config_contract",
- "encoded_exfil",
-}
+ "encoded_exfil"}
# Plugin severity remaps: a bundled binary is warn-tier (repos occasionally vendor
# one legitimately); a mere ``~/.hermes/.env`` mention is how READMEs tell users where
# keys go (READING it still trips ``read_secrets_file``, critical); ``curl | sh``
# install instructions are common in READMEs — caution, not an unoverridable block.
SEVERITY_REMAP = {
- "binary_file": "high", "hermes_env_access": "medium", "curl_pipe_shell": "high"
-}
+ "binary_file": "high", "hermes_env_access": "medium", "curl_pipe_shell": "high"}
# Structural limits — plugins are real codebases, far larger than skills.
MAX_PLUGIN_FILE_COUNT = 400
@@ -169,17 +165,14 @@ def scan_plugin(plugin_dir: Path, source: str = "") -> ScanResult:
result = ScanResult(
skill_name=plugin_dir.name, source=source or plugin_dir.name, trust_level="community",
verdict=verdict, findings=all_findings, scanned_at=datetime.now(timezone.utc).isoformat(),
- summary=summary,
- )
+ summary=summary)
result.scan_provenance = {
- "scanner_version": PLUGIN_SCANNER_VERSION, "verdict": verdict, "source": result.source
- }
+ "scanner_version": PLUGIN_SCANNER_VERSION, "verdict": verdict, "source": result.source}
return result
def should_allow_plugin_install(
- result: ScanResult, force: bool = False,
-) -> Tuple[Optional[bool], str]:
+ result: ScanResult, force: bool = False) -> Tuple[Optional[bool], str]:
"""Map a verdict to ``(allowed, reason)``: True installs, None asks to confirm, False blocks."""
n = len(result.findings)
if result.verdict == "safe":
@@ -190,10 +183,8 @@ def should_allow_plugin_install(
return None, f"Requires confirmation (caution verdict, {n} findings)"
return False, (
f"Blocked (dangerous verdict, {n} findings). "
- f"--force does not override a dangerous verdict."
- )
+ f"--force does not override a dangerous verdict.")
__all__ = [
- "scan_plugin", "should_allow_plugin_install", "format_scan_report", "PLUGIN_SCANNER_VERSION"
-]
+ "scan_plugin", "should_allow_plugin_install", "format_scan_report", "PLUGIN_SCANNER_VERSION"]
diff --git a/tools/registry.py b/tools/registry.py
index 5c694bf6fa3..dadd0deb4a7 100644
--- a/tools/registry.py
+++ b/tools/registry.py
@@ -36,8 +36,7 @@ def _bound_error_text(text: str) -> str:
return text
logger.debug(
"tool error body truncated for context (%d chars): %s",
- len(text), text[:_MAX_LOGGED_ERROR_CHARS],
- )
+ len(text), text[:_MAX_LOGGED_ERROR_CHARS])
return text[:_MAX_TOOL_ERROR_CHARS] + _TOOL_ERROR_TRUNCATION_MARKER
@@ -228,8 +227,7 @@ _NO_CACHE_CHECK_FNS: Set[Callable] = set()
_BROWSER_IDENTITY_KEYS = (
"HERMES_SESSION_ID",
"HERMES_BROWSER_CONTROL_PRINCIPAL",
- "HERMES_BROWSER_CONTROL_TRANSPORT_FAMILY",
-)
+ "HERMES_BROWSER_CONTROL_TRANSPORT_FAMILY")
def no_cache_check_fn(fn: Callable) -> Callable:
@@ -438,8 +436,7 @@ class ToolRegistry:
return [entry for entry in self._merged_tools(scope).values() if entry.toolset == toolset]
def _snapshot_state(
- self, scope: Optional[str] = None,
- ) -> tuple[List[ToolEntry], Dict[str, Callable]]:
+ self, scope: Optional[str] = None) -> tuple[List[ToolEntry], Dict[str, Callable]]:
"""Return a coherent snapshot of registry entries and toolset checks."""
with self._lock:
entries = list(self._merged_tools(scope).values())
@@ -469,8 +466,7 @@ class ToolRegistry:
return self._merged_tools(scope).get(name)
def snapshot_registration(
- self, name: str, *, scope: Optional[str] = None,
- ) -> Optional[ToolEntry]:
+ self, name: str, *, scope: Optional[str] = None) -> Optional[ToolEntry]:
"""Return the local slot state without following global fallback."""
with self._lock:
return self._slot(scope).get(name)
@@ -493,8 +489,7 @@ class ToolRegistry:
existing = self._toolset_aliases.get(alias)
if existing and existing != toolset:
logger.warning(
- "Toolset alias collision: '%s' (%s) overwritten by %s",
- alias, existing, toolset,
+ "Toolset alias collision: '%s' (%s) overwritten by %s", alias, existing, toolset
)
self._toolset_aliases[alias] = toolset
self._generation += 1
@@ -650,12 +645,10 @@ class ToolRegistry:
target = self._slot(scope, create=True)
existing = (self._tools if scope is None else self._merged_tools(scope)).get(name)
plugin_override_denied = (
- owner is not None and not self._plugin_override_allowed(scope, owner)
- )
+ owner is not None and not self._plugin_override_allowed(scope, owner))
shadows_global = (
owner is not None and scope is not None
- and name not in target and name in self._tools
- )
+ and name not in target and name in self._tools)
if shadows_global:
if not override:
logger.error(
@@ -763,8 +756,7 @@ class ToolRegistry:
def restore_registration(
self, name: str, current: ToolEntry, previous: Optional[ToolEntry], *,
- scope: Optional[str] = None,
- ) -> bool:
+ scope: Optional[str] = None) -> bool:
"""Restore a host-owned registration if it is still current (plugin ownership ledger).
The identity check is deliberate: another plugin (or ``PluginManager`` in a
multi-profile process) may have registered a newer entry under the same name, and
@@ -832,8 +824,7 @@ class ToolRegistry:
except Exception as exc:
logger.warning(
"dynamic_schema_overrides for tool %s raised %s; using static schema",
- name, exc,
- )
+ name, exc)
result.append({"type": "function", "function": schema_with_name})
return result
@@ -861,8 +852,7 @@ class ToolRegistry:
result_type=result_type)
def dispatch(
- self, name: str, args: dict, *, scope: Optional[str] = None, **kwargs,
- ) -> str | dict:
+ self, name: str, args: dict, *, scope: Optional[str] = None, **kwargs) -> str | dict:
"""Execute a tool handler by name: async handlers bridged via ``_run_async()``,
results normalized, every exception returned as ``{"error": ...}``."""
entry = self.get_entry(name, scope=scope)
diff --git a/tools/schema_sanitizer.py b/tools/schema_sanitizer.py
index 2cc9208f851..f263e1638e4 100644
--- a/tools/schema_sanitizer.py
+++ b/tools/schema_sanitizer.py
@@ -182,15 +182,13 @@ def strip_nullable_unions(schema: Any, *, keep_nullable_hint: bool = True) -> An
"""
if isinstance(schema, list):
return [
- strip_nullable_unions(item, keep_nullable_hint=keep_nullable_hint) for item in schema
- ]
+ strip_nullable_unions(item, keep_nullable_hint=keep_nullable_hint) for item in schema]
if not isinstance(schema, dict):
return schema
stripped = {
k: strip_nullable_unions(v, keep_nullable_hint=keep_nullable_hint)
- for k, v in schema.items()
- }
+ for k, v in schema.items()}
for key in _UNION_KEYS:
variants = stripped.get(key)
if not isinstance(variants, list):
@@ -206,8 +204,7 @@ def strip_nullable_unions(schema: Any, *, keep_nullable_hint: bool = True) -> An
_CONST_PRIMITIVE_TYPES: dict[type, str] = {
- bool: "boolean", int: "integer", float: "number", str: "string",
-}
+ bool: "boolean", int: "integer", float: "number", str: "string"}
def _const_branch_type(branch: Any) -> str | None:
@@ -257,9 +254,7 @@ def collapse_const_unions(schema: Any) -> Any:
if len(branch_types) != 1 or None in branch_types:
continue
replacement: dict = {
- "type": branch_types.pop(),
- "enum": [item["const"] for item in const_branches],
- }
+ "type": branch_types.pop(), "enum": [item["const"] for item in const_branches]}
if null_branches:
replacement["nullable"] = True
_carry_union_meta(out, replacement, skip_default_on_ref=False)
@@ -379,8 +374,7 @@ def _dict_nodes(node: Any):
def _reactive_strip(
- tools: list[dict], strip_node: Callable[[dict], int], log_msg: str,
-) -> tuple[list[dict], int]:
+ tools: list[dict], strip_node: Callable[[dict], int], log_msg: str) -> tuple[list[dict], int]:
"""Apply *strip_node* (returns keywords removed) to every dict node of each tool's
parameters, in place. Handles OpenAI (``{"function": {"parameters": ..}}``) and Responses
(``{"name": .., "parameters": ..}``) formats. Returns ``(tools, stripped_count)``."""
diff --git a/tools/self_repo_guard.py b/tools/self_repo_guard.py
index 5150e4312e0..3f2883b175b 100644
--- a/tools/self_repo_guard.py
+++ b/tools/self_repo_guard.py
@@ -52,8 +52,7 @@ _WRAPPER_OPTIONS_WITH_ARG: dict[str, frozenset[str]] = {
_MAX_RECURSION = 4
# git global options that consume the next argument (-C/--work-tree/-c are acted on).
_GIT_GLOBAL_OPTIONS_WITH_ARG = frozenset({
- "-C", "-c", "--work-tree", "--git-dir", "--namespace", "--exec-path",
-})
+ "-C", "-c", "--work-tree", "--git-dir", "--namespace", "--exec-path"})
@dataclass
@@ -114,8 +113,7 @@ def _shell_words_at(command: str, start: int) -> list[str]:
def _consume_options(
- words: list[str], start: int, options_with_arg: frozenset[str] = _NO_OPTIONS,
-) -> int:
+ words: list[str], start: int, options_with_arg: frozenset[str] = _NO_OPTIONS) -> int:
"""Index of the first positional at/after ``start`` (``--`` ends options)."""
index = start
while index < len(words):
@@ -383,8 +381,7 @@ def _stash_mutates(args: list[str]) -> bool:
def _clean_mutates(args: list[str]) -> bool:
return not any(
arg == "--dry-run" or (not arg.startswith("--") and _has_short_flag(arg, "n"))
- for arg in args
- )
+ for arg in args)
def _restore_mutates(args: list[str]) -> bool:
@@ -430,12 +427,10 @@ def _read_git_alias(executable: str, target: Path, alias: str) -> str | None:
def _inspect_git(
- executable: str, args: list[str], current_dir: Path, env: dict[str, str], root: Path,
- depth: int,
+ executable: str, args: list[str], current_dir: Path, env: dict[str, str], root: Path, depth: int
) -> str | None:
target, subcommand, sub_args, inline_aliases = _git_target_and_subcommand(
- args, current_dir, env,
- )
+ args, current_dir, env)
if subcommand is None:
return None
# `worktree` names its victim as an argument, so the cwd check does not apply.
@@ -463,8 +458,7 @@ def _inspect_git(
def _inspect_github_cli(
- executable: str, args: list[str], current_dir: Path, env: dict[str, str], root: Path,
- depth: int,
+ executable: str, args: list[str], current_dir: Path, env: dict[str, str], root: Path, depth: int
) -> str | None:
if not _is_within(current_dir, root):
return None
@@ -475,8 +469,7 @@ def _inspect_github_cli(
def _inspect_shell(
- executable: str, args: list[str], current_dir: Path, env: dict[str, str], root: Path,
- depth: int,
+ executable: str, args: list[str], current_dir: Path, env: dict[str, str], root: Path, depth: int
) -> str | None:
script = _shell_script_arg(args)
return _find_mutation(script, current_dir, root, depth + 1) if script else None