Files
hermes-agent/tests/tools/test_code_execution_file_rpc.py
alt-glitch c81362cc59 refactor(tools): the tool list and one tool call become tools/schemas.py and tools/calls.py
model_tools.py held two jobs. tools/schemas.py now builds the tool list sent
to the model: importing it loads the built-in and plugin tools (the moment
`import model_tools` did), and get_tool_definitions selects, rewrites per
session, cleans and defers. tools/calls.py runs one model tool call through
argument repair, hooks, middleware and the registry. Argument repair stays in
tools/arg_coercion.py: the inline executors import it at module top, and in
tools/calls.py that import would load every tool. The error cleaner joins tools/results.py.
Definitions move unchanged. Imports of tools.context and the schema cleaner
that were inside the moved functions go to module top as module objects;
both are loaded by then already, and a patch on, say,
tools.context.hosted_tool_refusal still reaches the code. The imports of
tools.deferral stay inside their functions: Tool Search loads the connectors
on the first tool list, and at module top `import model_tools` would load
them too. calls.py reads get_tool_definitions and _last_resolved_tool_names
through the schemas module, so a patch on either still reaches the call path.

tools/schema_sanitizer.py stays a file. Provider adapters and a provider
plugin import it at module top; inside tools/schemas.py, loading a provider
would load every tool.

Old names, until v0.27.0. model_tools.py is a file of re-exports: the names
releases up to v0.23.5 import from it inside functions, and the public names
pinned catalog plugins import (get_tool_definitions, handle_function_call).
Importing it still loads the tools. No product code imports model_tools now; its own
compatibility tests do, as do ten tests and four eval workers that import it
only to load the tools (the evals also run against older checkouts).

The call path's log lines move from the model_tools logger to tools.calls and
tools.schemas: `hermes logs --component` shows them under tools, not agent.
Argument repair logs as "model_tools", as before.
2026-12-02 04:05:32 +05:30

100 lines
4.6 KiB
Python

"""Generated stubs and the production file poller over real shell/filesystem I/O."""
import concurrent.futures
import json
import os
from pathlib import Path
import subprocess
import threading
import time
import pytest
from tools.code_execution_tool import generate_hermes_tools_module
from tools.code_execution_rpc import _rpc_poll_loop
CALLS = {
"web_search": {"query": "fixture", "limit": 3},
"web_extract": {"urls": ["https://example.test"], "char_limit": 3000},
"read_file": {"path": "reference", "offset": 2, "limit": 4},
"write_file": {"path": "output", "content": "café", "cross_profile": False},
"search_files": {"pattern": "x", "target": "files", "path": ".", "file_glob": "*.py",
"limit": 4, "offset": 2, "output_mode": "count", "context": 3, "order": "modified"},
"patch": {"path": "output", "old_string": "old", "new_string": "new", "replace_all": True,
"mode": "replace", "patch": None, "cross_profile": False},
"terminal": {"command": "echo fixture", "timeout": 3, "workdir": "/tmp"},
}
@pytest.mark.platforms("posix")
def test_generated_file_rpc_kwargs_correlation_and_authority(tmp_path, monkeypatch):
from pm.shell import bash
from tools.registry import registry
import tools.file_tools
import tools.web_tools
import tools.terminal_tool
shell = bash()
assert shell
rpc = tmp_path / "rpc with spaces"
rpc.mkdir()
monkeypatch.delenv("HERMES_RPC_DIR", raising=False)
monkeypatch.setattr("tempfile.gettempdir", lambda: str(tmp_path))
namespace = {}
exec(generate_hermes_tools_module([], transport="file"), namespace)
assert namespace["_RPC_DIR"] == str(tmp_path / "hermes_rpc")
assert "terminal" not in namespace
monkeypatch.setenv("HERMES_RPC_DIR", str(rpc))
monkeypatch.setenv("HERMES_RPC_TOKEN", "right-token")
exec(generate_hermes_tools_module(list(CALLS), transport="file"), namespace)
seen, log, counter = [], [], [0]
def dispatch(name, args, **kwargs):
seen.append((name, args.copy()))
return json.dumps({"name": name, "args": args})
monkeypatch.setattr("tools.calls.handle_function_call", dispatch)
class Shell:
def execute(self, command, cwd=None, timeout=None, stdin_data=None):
result = subprocess.run([shell, "-c", command], cwd=cwd, timeout=timeout,
env=dict(os.environ), input=stdin_data or "", capture_output=True, text=True, check=False)
assert result.returncode == 0, result.stderr
return {"output": result.stdout}
stop = threading.Event()
budget = len(CALLS) + 8
poller = threading.Thread(target=_rpc_poll_loop, args=(Shell(), str(rpc), "owner", log, counter,
budget, frozenset(CALLS), stop, "right-token"), daemon=True)
poller.start()
try:
# Raw clients bypass stub visibility; neither missing nor wrong token may dispatch.
for seq, token in [(9001, None), (9002, "wrong-token")]:
request = {"seq": seq, "tool": "terminal", "args": {"command": "forbidden"}}
if token is not None:
request["token"] = token
path = rpc / f"req_{seq}"
path.write_text(json.dumps(request), encoding="utf-8")
deadline = time.monotonic() + 5
while path.exists() and time.monotonic() < deadline:
stop.wait(.01)
assert not path.exists()
assert not (rpc / f"res_{seq:06d}").exists()
assert seen == [] and counter == [0]
for name, args in CALLS.items():
blocked = {"background", "heartbeat", "pty", "notify", "notify_on_complete", "watch_patterns", "persist_on_release"} if name == "terminal" else set()
schema_keys = set(registry.get_entry(name).schema["parameters"]["properties"]) - blocked
assert schema_keys <= set(args), (name, schema_keys - set(args))
assert namespace[name](**args) == {"name": name, "args": args}
assert seen == list(CALLS.items())
with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:
results = list(pool.map(lambda i: namespace["terminal"](f"tag-{i}", 3, "/tmp"), range(8)))
assert [r["args"]["command"] for r in results] == [f"tag-{i}" for i in range(8)]
assert "not available" in namespace["_call"]("unauthorized-tool", {})["error"]
assert "limit reached" in namespace["terminal"]("over-budget")["error"]
assert counter == [budget] and len(seen) == len(log) == budget
finally:
stop.set()
poller.join(timeout=10)
assert not poller.is_alive()