The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tools): tool_search_validation/output_limits/spill_safety — flatten required probe and section guard, pack signatures, compact docstrings
Teknium78203e36f81e
diff --git a/tools/spill_safety.py b/tools/spill_safety.pyindex 0f2d12ff85e..34eeb2ed510 100644--- a/tools/spill_safety.py+++ b/tools/spill_safety.py@@ -16,15 +16,14 @@ from typing import IO__all__ = ["ensure_spill_dir", "open_exclusive", "write_text_exclusive"]-# O_NOFOLLOW is POSIX-only; on Windows O_EXCL alone already refuses every-# pre-existing path.+# O_NOFOLLOW is POSIX-only; on Windows O_EXCL alone already refuses every pre-existing path._O_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)def ensure_spill_dir(path: Path, *, private: bool = True) -> Path:- """Create ``path`` (and parents) as a directory, refusing symlinks.- ``private=True`` creates the leaf ``0o700`` and tightens an existing leaf.- Raises ``OSError`` if the leaf is not a real directory."""+ """Create ``path`` (and parents) as a directory, refusing symlinks. ``private=True``+ creates the leaf ``0o700`` and tightens an existing leaf. Raises ``OSError`` if the leaf+ is not a real directory."""path = Path(path)path.mkdir(mode=0o700 if private else 0o777, parents=True, exist_ok=True)st = os.lstat(path)@@ -35,17 +34,12 @@ def ensure_spill_dir(path: Path, *, private: bool = True) -> Path:return path-def open_exclusive(- path: Path,- *,- private: bool = True,- overwrite: bool = False,- encoding: str = "utf-8",- errors: str = "strict") -> IO[str]:- """Open ``path`` for writing via exclusive create; never follows a link.- ``overwrite=True`` first unlinks an existing path (``lstat``-checked, so only- the link itself is removed and directories are refused), then creates- exclusively — the overwrite path cannot be redirected through a symlink either."""+def open_exclusive(path: Path, *, private: bool = True, overwrite: bool = False,+ encoding: str = "utf-8", errors: str = "strict") -> IO[str]:+ """Open ``path`` for writing via exclusive create; never follows a link. ``overwrite=True``+ first unlinks an existing path (``lstat``-checked, so only the link itself is removed and+ directories are refused), then creates exclusively — the overwrite path cannot be+ redirected through a symlink either."""path = Path(path)if overwrite:try:@@ -65,16 +59,9 @@ def open_exclusive(raise-def write_text_exclusive(- path: Path,- text: str,- *,- private: bool = True,- overwrite: bool = False,- encoding: str = "utf-8",- errors: str = "strict") -> None:+def write_text_exclusive(path: Path, text: str, *, private: bool = True, overwrite: bool = False,+ encoding: str = "utf-8", errors: str = "strict") -> None:"""``Path.write_text`` equivalent that refuses to follow symlinks."""- with open_exclusive(- path, private=private, overwrite=overwrite, encoding=encoding, errors=errors- ) as fh:+ with open_exclusive(path, private=private, overwrite=overwrite, encoding=encoding,+ errors=errors) as fh:fh.write(text)diff --git a/tools/tool_output_limits.py b/tools/tool_output_limits.pyindex c13bc78831b..f6e2d558069 100644--- a/tools/tool_output_limits.py+++ b/tools/tool_output_limits.py@@ -11,9 +11,7 @@ from typing import Any, DictDEFAULT_MAX_BYTES = 50_000 # terminal_tool.MAX_OUTPUT_CHARSDEFAULT_MAX_LINES = 2000 # file_operations.MAX_LINESDEFAULT_MAX_LINE_LENGTH = 2000 # file_operations.MAX_LINE_LENGTH--# Process-lifetime cache: avoids re-reading config.yaml on every tool call.-_cached_limits: dict | None = None+_cached_limits: dict | None = None # process-lifetime: no config.yaml re-read per tool calldef _coerce_int(value: Any, default: int, minimum: int) -> int:@@ -31,8 +29,8 @@ def _coerce_positive_int(value: Any, default: int) -> int:def get_tool_output_limits() -> Dict[str, int]:- """Resolved ``{max_bytes, max_lines, max_line_length}``; never raises. Cached- for the process — ``_reset_tool_output_limits_cache()`` forces a fresh read."""+ """Resolved ``{max_bytes, max_lines, max_line_length}``; never raises. Cached for the+ process — ``_reset_tool_output_limits_cache()`` forces a fresh read."""global _cached_limitsif _cached_limits is not None:return _cached_limits@@ -40,9 +38,9 @@ def get_tool_output_limits() -> Dict[str, int]:from hermes_cli.config import load_configcfg = load_config() or {}section = cfg.get("tool_output") if isinstance(cfg, dict) else None- if not isinstance(section, dict):- section = {}except Exception:+ section = None+ if not isinstance(section, dict):section = {}_cached_limits = {"max_bytes": _coerce_positive_int(section.get("max_bytes"), DEFAULT_MAX_BYTES),diff --git a/tools/tool_search_validation.py b/tools/tool_search_validation.pyindex 1379895eb9d..4ed31b0e10f 100644--- a/tools/tool_search_validation.py+++ b/tools/tool_search_validation.py@@ -16,8 +16,8 @@ _SCHEMA_LITERAL_KEYS = frozenset({"const", "default", "enum", "example", "exampldef _schema_for_local_validation(node: Any) -> Any:- """JSON-Schema-compatible copy honoring OpenAPI ``nullable: true`` — the- normal coercion path accepts that shape, so local validation must too."""+ """JSON-Schema-compatible copy honoring OpenAPI ``nullable: true`` (the normal coercion+ path accepts that shape, so local validation must too)."""if isinstance(node, list):return [_schema_for_local_validation(item) for item in node]if not isinstance(node, dict):@@ -38,14 +38,14 @@ def _schema_for_local_validation(node: Any) -> Any:if "null" not in schema_type:normalized["type"] = [*schema_type, "null"]return normalized- # No ``type`` to extend ($ref/combinator): wrap so local refs still resolve- # from the root while null stays an explicit alternative.+ # No ``type`` to extend ($ref/combinator): wrap so local refs still resolve from the+ # root while null stays an explicit alternative.return {"anyOf": [normalized, {"type": "null"}]}def _schema_has_external_ref(node: Any) -> bool:- """True when *node* contains a non-local ``$ref`` — local validation must- never turn a tool call into an implicit network/file fetch (fail open)."""+ """True when *node* contains a non-local ``$ref`` — local validation must never turn a+ tool call into an implicit network/file fetch (fail open)."""if isinstance(node, list):return any(_schema_has_external_ref(item) for item in node)if not isinstance(node, dict):@@ -53,10 +53,8 @@ def _schema_has_external_ref(node: Any) -> bool:ref = node.get("$ref")if isinstance(ref, str) and not ref.startswith("#"):return True- return any(- _schema_has_external_ref(value)- for key, value in node.items()- if key not in _SCHEMA_LITERAL_KEYS)+ return any(_schema_has_external_ref(value) for key, value in node.items()+ if key not in _SCHEMA_LITERAL_KEYS)def _validation_path(error: Any) -> str:@@ -79,15 +77,12 @@ def _validation_error(message: str, *, path: str, constraint: str, parameters: Adef validate_deferred_call_args(name: str, args: Dict[str, Any]) -> Optional[str]:- """Validate ``tool_call`` arguments against the deferred tool's schema.-- Models invoke deferred tools "blind" (schema unseen) and omit required- args; without this, the opaque downstream failure makes cheap models loop.- Required-field probe first, then the same schema-guided coercion normal- dispatch applies, then jsonschema on the repaired copy. Missing/malformed- schemas, no validator, and external refs all fail OPEN. Returns a JSON- error string when invalid, ``None`` when the call should dispatch.- """+ """Validate ``tool_call`` arguments against the deferred tool's schema. Models invoke+ deferred tools "blind" (schema unseen) and omit required args; without this, the opaque+ downstream failure makes cheap models loop. Required-field probe first, then the same+ schema-guided coercion normal dispatch applies, then jsonschema on the repaired copy.+ Missing/malformed schemas, no validator, and external refs all fail OPEN. Returns a JSON+ error string when invalid, ``None`` when the call should dispatch."""try:from tools.registry import registry as _registryschema = _registry.get_schema(name)@@ -98,35 +93,31 @@ def validate_deferred_call_args(name: str, args: Dict[str, Any]) -> Optional[strif not isinstance(params, dict):return Nonerequired = params.get("required")- if isinstance(required, list):- missing = [r for r in required if isinstance(r, str) and r not in args]- if missing:- return _validation_error(- f"tool_call to '{name}' is missing required argument(s): "- f"{', '.join(missing)}. The tool was NOT invoked.",- path="arguments", constraint="required", parameters=params)-+ missing = ([r for r in required if isinstance(r, str) and r not in args]+ if isinstance(required, list) else [])+ if missing:+ return _validation_error(+ f"tool_call to '{name}' is missing required argument(s): "+ f"{', '.join(missing)}. The tool was NOT invoked.",+ path="arguments", constraint="required", parameters=params)validation_schema = _schema_for_local_validation(params)if _schema_has_external_ref(validation_schema):logger.debug("Skipping local deferred-argument validation for %s: external $ref", name)return None-- # Validate the repaired shape dispatch will see; copy because- # coerce_tool_args may normalize in place (dispatch re-coerces canonically).+ # Validate the repaired shape dispatch will see; copy because coerce_tool_args may+ # normalize in place (dispatch re-coerces canonically).try:from model_tools import coerce_tool_argscandidate_args = coerce_tool_args(name, dict(args))except Exception:logger.debug("Deferred-argument coercion failed for %s", name, exc_info=True)candidate_args = dict(args)-try:from jsonschema.exceptions import best_matchfrom jsonschema.validators import validator_forexcept ImportError:logger.debug("jsonschema unavailable; keeping required-only validation for %s", name)return None-validator_cls = validator_for(validation_schema)validator_cls.check_schema(validation_schema)validation_error = best_match(validator_cls(validation_schema).iter_errors(candidate_args))