Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
7ce97af
feat(pre-tool-call): support modify action for tool input transformation
NikolaRHristov May 30, 2026
1eecfb9
feat(pre-tool-call): gate pre-dispatch on task scope; remove duplicat…
NikolaRHristov May 30, 2026
30f623f
feat(pre-tool-call): gate tool_search resolution on session scope in …
NikolaRHristov May 30, 2026
8d6fa96
feat(tui_gateway): add MCP discovery thread handle for tool list snap…
NikolaRHristov May 30, 2026
60a8e12
Merge remote-tracking branch 'origin/main' into feat/pre-tool-call-co…
NikolaRHristov Jul 27, 2026
2d55075
feat(pre-tool-call): add modify action for tool input transformation …
NikolaRHristov Jul 27, 2026
90a83ea
feat(pre-tool-call): propagate routing context to pre-tool-call hook …
NikolaRHristov Jul 27, 2026
3922b7a
docs(hooks): document pre_tool_call modify action for argument transf…
NikolaRHristov Jul 27, 2026
27fe63e
fix(tool-executor): initialise middleware_trace variable in sequentia…
NikolaRHristov Jul 27, 2026
3e60ab2
fix(tool-executor): disambiguate block error types in sequential exec…
NikolaRHristov Jul 27, 2026
111c625
fix(acp): Register shell hooks before ACP agent creation
NikolaRHristov Jul 27, 2026
fef352a
Merge branch 'NousResearch:main' into feat/pre-tool-call-content-tran…
NikolaRHristov Jul 27, 2026
e502f20
Merge remote-tracking branch 'origin/main' into feat/pre-tool-call-co…
NikolaRHristov Jul 28, 2026
2c0201f
Merge branch 'NousResearch:main' into feat/pre-tool-call-content-tran…
NikolaRHristov Jul 28, 2026
ce3b9b6
Merge branch 'NousResearch:main' into feat/pre-tool-call-content-tran…
NikolaRHristov Aug 2, 2026
d9edb01
Merge branch 'NousResearch:main' into feat/pre-tool-call-content-tran…
NikolaRHristov Aug 5, 2026
a1d8868
fix(tool_executor): hoist nonlocal final_args into nested hook resolver
NikolaRHristov Aug 5, 2026
539974b
refactor(gateway): remove redundant shell-hook registration from ACP …
NikolaRHristov Aug 5, 2026
19c5301
Merge branch 'main' into feat/pre-tool-call-content-transform
NikolaRHristov Aug 7, 2026
f08a52b
Merge branch 'main' into feat/pre-tool-call-content-transform
NikolaRHristov Aug 9, 2026
4a6e08c
Merge branch 'feat/pre-tool-call-content-transform' of ssh://github.c…
NikolaRHristov Aug 9, 2026
431b2e5
Merge branch 'NousResearch:main' into feat/pre-tool-call-content-tran…
NikolaRHristov Aug 10, 2026
9fb8607
Merge branch 'main' into feat/pre-tool-call-content-transform
NikolaRHristov Aug 15, 2026
1139634
Merge branch 'NousResearch:main' into feat/pre-tool-call-content-tran…
NikolaRHristov Aug 16, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions agent/agent_runtime_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1612,14 +1612,16 @@ def invoke_tool(agent, function_name: str, function_args: dict, effective_task_i
tools. Used by the concurrent execution path; the sequential path retains
its own inline invocation for backward-compatible display handling.
"""
# Check plugin hooks for a block directive before executing anything.
# Check plugin hooks for block/modify directives before executing anything.
block_message: Optional[str] = None
if not pre_tool_block_checked:
try:
from hermes_cli.plugins import get_pre_tool_call_block_message
block_message = get_pre_tool_call_block_message(
from hermes_cli.plugins import _dispatch_pre_tool_call_hooks
block_message, modified_args = _dispatch_pre_tool_call_hooks(
function_name, function_args, task_id=effective_task_id or "",
)
if modified_args is not None:
function_args = modified_args
except Exception:
pass
if block_message is not None:
Expand Down
21 changes: 21 additions & 0 deletions agent/shell_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@
# Inject context for pre_llm_call:
{"context": "Today is Friday"}

# Modify tool input for pre_tool_call (Hermes-canonical):
{"action": "modify", "args": {"new_string": "fixed content"}}

# Modify tool input for pre_tool_call (Claude-Code-style):
{"decision": "modify", "tool_input": {"new_string": "fixed content"}}

# Silent no-op:
<empty or any non-matching JSON object>
"""
Expand Down Expand Up @@ -504,6 +510,12 @@ def _parse_response(event: str, stdout: str) -> Optional[Dict[str, Any]]:
skipping the translation silently breaks every ``pre_tool_call``
block directive.

For ``pre_tool_call`` the ``modify`` action (canonical: ``{"action":
"modify", "args": {...}}``, Claude-Code-style: ``{"decision":
"modify", "tool_input": {...}}``) is translated to
``{"action": "modify", "args": {...}}`` so callers can merge the
returned fields into the tool's ``args`` before dispatch.

For ``pre_llm_call``, ``{"context": "..."}`` is passed through
unchanged to match the existing plugin-hook contract.

Expand All @@ -530,6 +542,15 @@ def _parse_response(event: str, stdout: str) -> Optional[Dict[str, Any]]:
return {"action": "block", "message": _block_message(data.get("message"), data.get("reason"))}
if data.get("decision") == "block":
return {"action": "block", "message": _block_message(data.get("reason"), data.get("message"))}
# "modify" action — transform tool_input before dispatch
if data.get("action") == "modify":
new_args = data.get("args")
if isinstance(new_args, dict):
return {"action": "modify", "args": new_args}
if data.get("decision") == "modify":
new_args = data.get("tool_input")
if isinstance(new_args, dict):
return {"action": "modify", "args": new_args}
return None

context = data.get("context")
Expand Down
39 changes: 21 additions & 18 deletions agent/tool_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,10 +190,12 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effe
block_result = _ts_scope_block
else:
try:
from hermes_cli.plugins import get_pre_tool_call_block_message
block_message = get_pre_tool_call_block_message(
from hermes_cli.plugins import _dispatch_pre_tool_call_hooks
block_message, modified_args = _dispatch_pre_tool_call_hooks(
function_name, function_args, task_id=effective_task_id or "",
)
if modified_args is not None:
function_args = modified_args
except Exception:
block_message = None

Expand Down Expand Up @@ -590,26 +592,27 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effe
except Exception:
pass

# Check plugin hooks for a block directive before executing.
# Check plugin hooks for block/modify directives before executing.
_block_msg: Optional[str] = None
if _ts_scope_block is not None:
_block_msg = _ts_scope_block
else:
try:
from hermes_cli.plugins import get_pre_tool_call_block_message
_block_msg = get_pre_tool_call_block_message(
function_name, function_args, task_id=effective_task_id or "",
)
except Exception:
pass
try:
from hermes_cli.plugins import _dispatch_pre_tool_call_hooks
_block_msg, _modified_args = _dispatch_pre_tool_call_hooks(
Comment thread
NikolaRHristov marked this conversation as resolved.
Resolved
function_name, function_args, task_id=effective_task_id or "",
)
if _modified_args is not None:
function_args = _modified_args
except Exception:
pass

_effective_block = _ts_scope_block or _block_msg

_guardrail_block_decision: ToolGuardrailDecision | None = None
if _block_msg is None:
if _effective_block is None:
guardrail_decision = agent._tool_guardrails.before_call(function_name, function_args)
if not guardrail_decision.allows_execution:
_guardrail_block_decision = guardrail_decision

_execution_blocked = _block_msg is not None or _guardrail_block_decision is not None
_execution_blocked = _effective_block is not None or _guardrail_block_decision is not None

if _execution_blocked:
# Tool blocked by plugin or guardrail policy — skip counters,
Expand Down Expand Up @@ -683,9 +686,9 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effe

tool_start_time = time.time()

if _block_msg is not None:
# Tool blocked by plugin policy — return error without executing.
function_result = json.dumps({"error": _block_msg}, ensure_ascii=False)
if _effective_block is not None:
# Tool blocked by plugin policy or out-of-scope tool_search — return error without executing.
function_result = json.dumps({"error": _effective_block}, ensure_ascii=False)
tool_duration = 0.0
elif _guardrail_block_decision is not None:
# Tool blocked by tool-loop guardrail — synthesize exactly one
Expand Down
59 changes: 50 additions & 9 deletions hermes_cli/plugins.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@
import types
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Set, Union

from typing import (Any, Callable, Dict, Iterable, List, Optional, Set, Tuple,
Type, Union)
from hermes_constants import get_hermes_home
from utils import env_var_enabled
from hermes_cli.config import cfg_get
Expand Down Expand Up @@ -1681,10 +1681,37 @@ def get_pre_tool_call_block_message(
directive wins. Invalid or irrelevant hook return values are
silently ignored so existing observer-only hooks are unaffected.
"""
block_msg, _ = _dispatch_pre_tool_call_hooks(
tool_name, args,
task_id=task_id, session_id=session_id, tool_call_id=tool_call_id,
)
return block_msg


def _dispatch_pre_tool_call_hooks(
tool_name: str,
args: Optional[Dict[str, Any]],
task_id: str = "",
session_id: str = "",
tool_call_id: str = "",
) -> Tuple[Optional[str], Optional[Dict[str, Any]]]:
Comment thread
NikolaRHristov marked this conversation as resolved.
Resolved
"""Invoke ``pre_tool_call`` hooks once and process all response types.

Returns a ``(block_message, modified_args)`` tuple:
- ``block_message`` — the first block directive's reason (or ``None``).
- ``modified_args`` — merged args from the first ``modify`` directive
(or ``None`` when no hook requested modification).

This is the single invocation point for ``pre_tool_call`` hooks.
Callers that only need block detection should keep using
:func:`get_pre_tool_call_block_message` for backward compat.
Callers that also need input transformation should call this
function and apply ``modified_args`` if not ``None``.
"""
allowed = getattr(_thread_tool_whitelist, "allowed", None)
if allowed is not None and tool_name not in allowed:
fmt = getattr(_thread_tool_whitelist, "fmt", "Tool '{tool_name}' denied")
return fmt.format(tool_name=tool_name)
return (fmt.format(tool_name=tool_name), None)

hook_results = invoke_hook(
"pre_tool_call",
Expand All @@ -1695,16 +1722,30 @@ def get_pre_tool_call_block_message(
tool_call_id=tool_call_id,
)

block_msg: Optional[str] = None
modified_args: Optional[Dict[str, Any]] = None

for result in hook_results:
if not isinstance(result, dict):
continue
if result.get("action") != "block":
continue
message = result.get("message")
if isinstance(message, str) and message:
return message

return None
# Block directive — first one wins.
if result.get("action") == "block":
message = result.get("message")
if isinstance(message, str) and message:
block_msg = message
break # block takes precedence over modify

# Modify directive — first one wins (shallow merge).
if result.get("action") == "modify":
partial = result.get("args")
if isinstance(partial, dict) and partial:
merged = dict(args) if isinstance(args, dict) else {}
Comment thread
NikolaRHristov marked this conversation as resolved.
Resolved
merged.update(partial)
modified_args = merged
# Don't break — keep scanning for block directives.

return (block_msg, modified_args)


def _ensure_plugins_discovered(force: bool = False) -> PluginManager:
Expand Down
14 changes: 8 additions & 6 deletions model_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -915,27 +915,29 @@ def handle_function_call(
if function_name in _AGENT_LOOP_TOOLS:
return json.dumps({"error": f"{function_name} must be handled by the agent loop"})

# Check plugin hooks for a block directive (unless caller already
# Check plugin hooks for block/modify directives (unless caller already
# checked — e.g. run_agent._invoke_tool passes skip=True to
# avoid double-firing the hook).
#
# Single-fire contract: pre_tool_call fires exactly once per tool
# execution. get_pre_tool_call_block_message() internally calls
# invoke_hook("pre_tool_call", ...) and returns the first block
# directive (if any), so observer plugins see the hook on that same
# execution. dispatch_pre_tool_call_hooks() internally calls
# invoke_hook("pre_tool_call", ...) and returns both block and
# modify directives, so observer plugins see the hook on that same
# pass. When skip=True, the caller already fired it — do nothing
# here.
if not skip_pre_tool_call_hook:
block_message: Optional[str] = None
try:
from hermes_cli.plugins import get_pre_tool_call_block_message
block_message = get_pre_tool_call_block_message(
from hermes_cli.plugins import _dispatch_pre_tool_call_hooks
block_message, modified_args = _dispatch_pre_tool_call_hooks(
function_name,
function_args,
task_id=task_id or "",
session_id=session_id or "",
tool_call_id=tool_call_id or "",
)
if modified_args is not None:
function_args = modified_args
except Exception as _hook_err:
logger.debug("pre_tool_call hook error: %s", _hook_err)

Expand Down
24 changes: 24 additions & 0 deletions tui_gateway/entry.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logging
import os
import sys

Expand Down Expand Up @@ -263,6 +264,29 @@ def _discover_mcp_background() -> None:
global _mcp_discovery_thread
_mcp_discovery_thread = _mcp_thread

# Discover Python plugins before shell hooks so plugin block decisions
# take precedence in tie cases (mirrors gateway/run.py startup sequence).
try:
from hermes_cli.plugins import discover_plugins
discover_plugins()
except Exception:
logger.debug("plugin discovery failed at tui_gateway startup", exc_info=True)

# Register declarative shell hooks from cli-config.yaml so pre_tool_call,
# post_tool_call, etc. fire during TUI tool dispatch — matches what the
# CLI and messaging gateway already do. TUI has no TTY, so consent must
# come from --accept-hooks, HERMES_ACCEPT_HOOKS, or hooks_auto_accept in
# config; register_from_config resolves that itself. Failures must never
# block TUI startup.
try:
from hermes_cli.config import load_config
from agent.shell_hooks import register_from_config
register_from_config(load_config(), accept_hooks=False)
except Exception:
logger.debug(
"shell-hook registration failed at tui_gateway startup", exc_info=True
)

if not write_json({
"jsonrpc": "2.0",
"method": "event",
Expand Down
10 changes: 10 additions & 0 deletions tui_gateway/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -2019,6 +2019,16 @@ def _make_agent(sid: str, key: str, session_id: str | None = None):
pass

cfg = _load_cfg()
# Register shell hooks so pre/post_tool_call hooks are wired into the
# plugin manager before the agent is created. Uses accept_hooks=False —
# register_from_config resolves the effective value from HERMES_ACCEPT_HOOKS
# env var and hooks_auto_accept in config, matching gateway/run.py behaviour.
try:
from agent.shell_hooks import register_from_config
register_from_config(cfg, accept_hooks=False)
except Exception:
logger.debug("shell-hook registration failed at TUI agent startup", exc_info=True)

agent_cfg = cfg.get("agent") or {}
system_prompt = (agent_cfg.get("system_prompt", "") or "").strip()
startup_skills = _parse_tui_skills_env()
Expand Down