Files
hermes-agent/tests/tools/test_code_execution_hook_identity.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

106 lines
4.3 KiB
Python

"""Tool calls made from inside an execute_code cell fire pre_tool_call hooks under the calling
conversation's identity (#145870): without it a hook sees ``session_id=""`` and, in a
multiplexed gateway, can only fall back to the process-wide HERMES_SESSION_ID of whichever
conversation bound a turn last."""
import json
from unittest.mock import patch
import pytest
from tools.calls import handle_function_call
from tools.code_execution_rpc import _default_dispatch
from tools.code_kernel import shutdown_all_kernels
@pytest.fixture(autouse=True)
def _local_kernel(monkeypatch):
monkeypatch.setenv("TERMINAL_ENV", "local")
shutdown_all_kernels()
with patch("tools.code_execution_tool._load_config", return_value={"mode": "strict", "timeout": 30}):
yield
shutdown_all_kernels()
@pytest.fixture
def hook_calls():
calls = []
def _record(tool_name, args, **hook_kwargs):
calls.append((tool_name, hook_kwargs))
return None, None
with patch("hermes_cli.plugins._dispatch_pre_tool_call_hooks", side_effect=_record):
yield calls
def _nested(calls, tool):
return [kw for name, kw in calls if name == tool]
def test_nested_call_in_a_local_cell_carries_the_outer_session_and_turn(tmp_path, hook_calls):
target = tmp_path / "note.txt"
target.write_text("hello\n", encoding="utf-8")
code = f"from hermes_tools import read_file\nprint(read_file({str(target)!r})['content'])"
result = json.loads(handle_function_call(
"execute_code", {"code": code}, task_id="task-A", session_id="sess-A", turn_id="turn-A",
conversation_id="conv-A", enabled_tools=["execute_code", "read_file"]))
assert result["status"] == "success", result
nested = _nested(hook_calls, "read_file")
assert len(nested) == 1
assert nested[0]["session_id"] == "sess-A"
assert nested[0]["turn_id"] == "turn-A"
assert nested[0]["conversation_id"] == "conv-A"
def test_nested_call_over_the_remote_rpc_dispatch_carries_the_outer_session_and_turn(tmp_path, hook_calls):
target = tmp_path / "note.txt"
target.write_text("hello\n", encoding="utf-8")
dispatch = _default_dispatch("task-A", "sess-A", "turn-A", "conv-A")
assert "hello" in json.loads(dispatch("read_file", {"path": str(target)}))["content"]
nested = _nested(hook_calls, "read_file")
assert len(nested) == 1
assert nested[0]["session_id"] == "sess-A"
assert nested[0]["turn_id"] == "turn-A"
assert nested[0]["conversation_id"] == "conv-A"
@pytest.mark.parametrize("route", ["kernel", "per_call"])
def test_both_remote_routes_hand_the_outer_identity_to_the_rpc_dispatch(route, monkeypatch):
import inspect
from contextlib import ExitStack
from tests.tools.test_code_kernel_remote import ScriptedEnv, _cell, _spawn_ok_handlers
from tools import code_execution_rpc
from tools.code_kernel_remote import shutdown_all_remote_kernels
real, seen = code_execution_rpc._default_dispatch, []
def _recording(*args, **kwargs):
seen.append(inspect.signature(real).bind(*args, **kwargs).arguments)
return real(*args, **kwargs)
handlers = [("command -v python3", lambda c: {"output": "OK\n", "returncode": 0})]
if route == "kernel":
handlers += _spawn_ok_handlers([_cell(stdout="ran\n")])
monkeypatch.setenv("TERMINAL_ENV", "ssh")
with ExitStack() as stack:
stack.callback(shutdown_all_remote_kernels)
stack.enter_context(patch("tools.code_execution_tool._get_or_create_env",
return_value=(ScriptedEnv(handlers), "ssh")))
stack.enter_context(patch("tools.code_execution_tool._remote_write"))
stack.enter_context(patch("tools.code_kernel_remote._remote_write"))
stack.enter_context(patch.object(code_execution_rpc, "_default_dispatch", side_effect=_recording))
if route == "per_call":
stack.enter_context(patch("tools.code_kernel_remote.execute_in_remote_kernel", return_value=None))
result = json.loads(handle_function_call(
"execute_code", {"code": "print(1)"}, task_id="task-A", session_id="sess-A", turn_id="turn-A",
conversation_id="conv-A", enabled_tools=["execute_code", "read_file"]))
assert result["status"] == "success", result
assert [(a["session_id"], a["turn_id"], a["conversation_id"]) for a in seen] == [("sess-A", "turn-A", "conv-A")]