Skip to content

The agent that grows with you

fix(acp): give every tool call a terminal status before the turn ends

HTeo12d7b4ab9c77
diff --git a/acp_adapter/events.py b/acp_adapter/events.py
index 216145237ea..b06a798c657 100644
--- a/acp_adapter/events.py
+++ b/acp_adapter/events.py
@@ -15,7 +15,10 @@ from typing import Any, Callable, Deque, Dict
import acp
from acp.schema import AgentPlanUpdate, PlanEntry
-from .tools import _json_loads_maybe, build_tool_complete, build_tool_start, coerce_tool_args, make_tool_call_id
+from .tools import (
+ _json_loads_maybe, build_tool_abandoned, build_tool_complete, build_tool_start, coerce_tool_args,
+ make_tool_call_id,
+)
logger = logging.getLogger(__name__)
@@ -72,19 +75,67 @@ def _upgrade_queue(tool_call_ids: Dict[str, Deque[str]], name: str) -> Deque[str
return queue
+def close_tool_call(
+ conn: acp.Client, session_id: str, loop: asyncio.AbstractEventLoop, tool_call_ids: Dict[str, Deque[str]],
+ tool_call_meta: Dict[str, Dict[str, Any]], name: str, result: Any = None,
+) -> str | None:
+ """Close the oldest open ACP tool call for ``name``; returns its id, or None when none is open."""
+ queue = _upgrade_queue(tool_call_ids, name)
+ if not queue:
+ return None
+ tc_id = queue.popleft()
+ meta = tool_call_meta.pop(tc_id, {})
+ _send_update(conn, session_id, loop, build_tool_complete(
+ tc_id, name, result=str(result) if result is not None else None,
+ function_args=meta.get("args"), snapshot=meta.get("snapshot"),
+ ))
+ if not queue:
+ tool_call_ids.pop(name, None)
+ return tc_id
+
+
+def flush_open_tool_calls(
+ conn: acp.Client, session_id: str, loop: asyncio.AbstractEventLoop, tool_call_ids: Dict[str, Deque[str]],
+ tool_call_meta: Dict[str, Dict[str, Any]],
+) -> int:
+ """Close every tool call still open at the end of a turn, and report how many there were.
+
+ A tool blocked by scope, guardrail or an editor permission prompt never
+ projects ``tool.completed``, so without this its bubble stays ``in_progress``
+ forever and clients read the turn as one that never ran a tool."""
+ open_calls = [(name, list(queue)) for name, queue in list(tool_call_ids.items()) if queue]
+ flushed = 0
+ for name, ids in open_calls:
+ for tc_id in ids:
+ tool_call_meta.pop(tc_id, None)
+ _send_update(conn, session_id, loop, build_tool_abandoned(tc_id, name))
+ flushed += 1
+ tool_call_ids.pop(name, None)
+ if flushed:
+ logger.debug("Flushed %d ACP tool call(s) left open at turn end", flushed)
+ return flushed
+
+
def make_tool_progress_cb(
conn: acp.Client, session_id: str, loop: asyncio.AbstractEventLoop, tool_call_ids: Dict[str, Deque[str]],
tool_call_meta: Dict[str, Dict[str, Any]],
edit_approval_policy_getter: Callable[[], tuple[str, str | None]] | None = None,
+ turn_state: Dict[str, Any] | None = None,
) -> Callable:
"""Create a ``tool_progress_callback`` for AIAgent.
Signature: ``tool_progress_callback(event_type, name, preview, args, **kwargs)``.
Emits ``ToolCallStart`` for ``tool.started`` and tracks IDs in a FIFO per tool
name so parallel same-name calls complete against the right ACP tool call.
- Other event types (``tool.completed``, ``reasoning.available``) are ignored."""
+ ``tool.completed`` closes that call with its own result — the step callback
+ only fires on the *next* step, which leaves a turn's last tools open."""
def _tool_progress(event_type: str, name: str = None, preview: str = None, args: Any = None, **kwargs) -> None:
+ if event_type == "tool.completed" and name:
+ if turn_state is not None:
+ turn_state["saw_completion"] = True
+ close_tool_call(conn, session_id, loop, tool_call_ids, tool_call_meta, name, kwargs.get("result"))
+ return
if event_type != "tool.started":
return
args = coerce_tool_args(args)
@@ -199,7 +250,7 @@ def make_message_cb(
def make_step_cb(
conn: acp.Client, session_id: str, loop: asyncio.AbstractEventLoop, tool_call_ids: Dict[str, Deque[str]],
- tool_call_meta: Dict[str, Dict[str, Any]],
+ tool_call_meta: Dict[str, Dict[str, Any]], turn_state: Dict[str, Any] | None = None,
) -> Callable:
"""Create a ``step_callback(api_call_count: int, prev_tools: list)`` for AIAgent."""
@@ -218,19 +269,22 @@ def make_step_cb(
if not tool_name:
continue
- queue = _upgrade_queue(tool_call_ids, tool_name)
- if not queue:
- continue
- tc_id = queue.popleft()
- meta = tool_call_meta.pop(tc_id, {})
- _send_update(conn, session_id, loop, build_tool_complete(
- tc_id, tool_name, result=str(result) if result is not None else None,
- function_args=function_args or meta.get("args"), snapshot=meta.get("snapshot"),
- ))
+ # ``tool.completed`` already closed this call with its own result;
+ # this callback is the fallback for runtimes that never project one.
+ if not (turn_state or {}).get("saw_completion"):
+ queue = _upgrade_queue(tool_call_ids, tool_name)
+ if not queue:
+ continue
+ tc_id = queue.popleft()
+ meta = tool_call_meta.pop(tc_id, {})
+ _send_update(conn, session_id, loop, build_tool_complete(
+ tc_id, tool_name, result=str(result) if result is not None else None,
+ function_args=function_args or meta.get("args"), snapshot=meta.get("snapshot"),
+ ))
+ if not queue:
+ tool_call_ids.pop(tool_name, None)
if tool_name == "todo" and (plan_update := _build_plan_update_from_todo_result(result)) is not None:
_send_update(conn, session_id, loop, plan_update)
- if not queue:
- tool_call_ids.pop(tool_name, None)
return _step
diff --git a/acp_adapter/server.py b/acp_adapter/server.py
index b8dc358b73b..b7cecd53e15 100644
--- a/acp_adapter/server.py
+++ b/acp_adapter/server.py
@@ -28,8 +28,8 @@ from acp_adapter.auth import TERMINAL_SETUP_AUTH_METHOD_ID, build_auth_methods,
from acp_adapter.commands import HERMES_VERSION, SlashCommandsMixin, _estimate_tokens
from acp_adapter.content import PromptBlock, _content_blocks_to_openai_user_content, _extract_text
from acp_adapter.events import (
- AssistantMessageIdAllocator, _build_plan_update_from_todo_result, make_message_cb, make_step_cb,
- make_thinking_cb, make_tool_progress_cb,
+ AssistantMessageIdAllocator, _build_plan_update_from_todo_result, flush_open_tool_calls, make_message_cb,
+ make_step_cb, make_thinking_cb, make_tool_progress_cb,
)
from acp_adapter.model_catalog import build_model_state, encode_model_choice
from acp_adapter.permissions import make_approval_callback
@@ -222,6 +222,8 @@ class _TurnCallbacks:
approval_cb: Any = None
edit_approval_requester: Any = None
streamed: bool = False
+ tool_call_ids: Any = None
+ tool_call_meta: Any = None
class HermesACPAgent(SlashCommandsMixin, acp.Agent):
@@ -840,13 +842,26 @@ class HermesACPAgent(SlashCommandsMixin, acp.Agent):
result = await loop.run_in_executor(_executor, ctx.run, _run_agent)
except Exception:
logger.exception("Executor error for session %s", session_id)
+ self._flush_turn_tool_calls(cbs, session_id, conn, loop)
with state.runtime_lock:
state.is_running = False
state.current_prompt_text = ""
return PromptResponse(stop_reason="end_turn")
+ self._flush_turn_tool_calls(cbs, session_id, conn, loop)
return await self._finish_turn(state, session_id, conn, result, pre_turn_hermes_id, cbs.streamed)
+ def _flush_turn_tool_calls(
+ self, cbs: _TurnCallbacks, session_id: str, conn: Any, loop: asyncio.AbstractEventLoop
+ ) -> None:
+ """Close any tool call the turn left open, so no bubble spins after the turn ends."""
+ if not conn or cbs.tool_call_ids is None:
+ return
+ try:
+ flush_open_tool_calls(conn, session_id, loop, cbs.tool_call_ids, cbs.tool_call_meta or {})
+ except Exception:
+ logger.debug("Could not flush open ACP tool calls for %s", session_id, exc_info=True)
+
def _wire_turn_callbacks(
self, state: SessionState, session_id: str, conn: Any, loop: asyncio.AbstractEventLoop
) -> _TurnCallbacks:
@@ -855,9 +870,14 @@ class HermesACPAgent(SlashCommandsMixin, acp.Agent):
if conn:
tool_call_ids: dict[str, Deque[str]] = defaultdict(deque)
tool_call_meta: dict[str, dict[str, Any]] = {}
+ cbs.tool_call_ids, cbs.tool_call_meta = tool_call_ids, tool_call_meta
+ # Shared with the step callback so a runtime that projects
+ # ``tool.completed`` closes each call once, not twice.
+ turn_state: dict[str, Any] = {}
policy_getter = lambda: self._edit_approval_policy_for_state(state) # noqa: E731
cbs.tool_progress_cb = make_tool_progress_cb(
- conn, session_id, loop, tool_call_ids, tool_call_meta, edit_approval_policy_getter=policy_getter
+ conn, session_id, loop, tool_call_ids, tool_call_meta, edit_approval_policy_getter=policy_getter,
+ turn_state=turn_state,
)
# Per-session allocator: a new turn must never reuse a previous turn's
# assistant messageId (ACP clients replace the bubble with that id).
@@ -865,7 +885,7 @@ class HermesACPAgent(SlashCommandsMixin, acp.Agent):
state.message_ids = AssistantMessageIdAllocator()
state.message_ids.close() # new turn -> next chunk opens a fresh id
cbs.reasoning_cb = make_thinking_cb(conn, session_id, loop, state.message_ids)
- cbs.step_cb = make_step_cb(conn, session_id, loop, tool_call_ids, tool_call_meta)
+ cbs.step_cb = make_step_cb(conn, session_id, loop, tool_call_ids, tool_call_meta, turn_state)
message_cb = make_message_cb(conn, session_id, loop, state.message_ids)
def stream_delta_cb(text: str) -> None:
diff --git a/acp_adapter/tools.py b/acp_adapter/tools.py
index b57a5638675..1e29caa6470 100644
--- a/acp_adapter/tools.py
+++ b/acp_adapter/tools.py
@@ -833,6 +833,18 @@ def build_tool_complete(
)
+def build_tool_abandoned(tool_call_id: str, tool_name: str) -> ToolCallProgress:
+ """Create a ToolCallUpdate for a call that ended without ever reporting a result.
+
+ A blocked or permission-denied call projects no ``tool.completed``, so the
+ turn ends with its bubble still spinning; ``failed`` is the honest terminal
+ state — the tool did not produce a result."""
+ return acp.update_tool_call(
+ tool_call_id, kind=get_tool_kind(tool_name), status="failed",
+ content=[_text("This tool call ended without a result (blocked, denied, or interrupted).")],
+ )
+
+
def extract_locations(arguments: Args) -> List[ToolCallLocation]:
"""Extract file-system locations from tool arguments."""
if not (path := arguments.get("path")):
diff --git a/tests/acp_adapter/test_events.py b/tests/acp_adapter/test_events.py
index 7e6d9a898b2..406b45668d0 100644
--- a/tests/acp_adapter/test_events.py
+++ b/tests/acp_adapter/test_events.py
@@ -310,3 +310,84 @@ class TestAssistantMessageIds:
side_effect=lambda c, s, l, u: sent.append(u)):
cb("text")
assert sent[0].message_id is None
+
+
+class TestToolCallsAlwaysReachATerminalStatus:
+ """A tool call left ``in_progress`` makes a finished turn look like it ran nothing.
+
+ Paseo read four Hermes tool calls as never-run on 2026-09-17: the step
+ callback only fires on the *next* step, so a turn's last tools stayed open,
+ and a denied edit projects no ``tool.completed`` at all."""
+
+ def _patch(self):
+ return patch("acp_adapter.events.asyncio.run_coroutine_threadsafe")
+
+ def test_tool_completed_closes_the_call_without_waiting_for_another_step(self, mock_conn, event_loop_fixture):
+ from collections import deque
+
+ ids = {"read": deque(["tc-1"])}
+ cb = make_tool_progress_cb(mock_conn, "s", event_loop_fixture, ids, {"tc-1": {"args": {"path": "a"}}})
+ with self._patch() as rcts, patch("acp_adapter.events.build_tool_complete") as btc:
+ rcts.return_value = MagicMock(spec=Future)
+ cb("tool.completed", "read", None, None, result="file body")
+ btc.assert_called_once_with("tc-1", "read", result="file body", function_args={"path": "a"}, snapshot=None)
+ assert "read" not in ids
+
+ def test_step_callback_does_not_close_a_second_call_after_tool_completed(self, mock_conn, event_loop_fixture):
+ """Both closers pop the same FIFO, so the fallback must stand down once completions arrive."""
+ from collections import deque
+
+ ids, turn_state = {"read": deque(["tc-1", "tc-2"])}, {}
+ progress = make_tool_progress_cb(mock_conn, "s", event_loop_fixture, ids, {}, turn_state=turn_state)
+ step = make_step_cb(mock_conn, "s", event_loop_fixture, ids, {}, turn_state)
+ with self._patch() as rcts, patch("acp_adapter.events.build_tool_complete") as btc:
+ rcts.return_value = MagicMock(spec=Future)
+ progress("tool.completed", "read", None, None, result="first")
+ step(1, [{"name": "read", "result": "first"}])
+ assert [c.args[0] for c in btc.call_args_list] == ["tc-1"]
+ assert list(ids["read"]) == ["tc-2"]
+
+ def test_step_callback_still_closes_when_no_completion_is_ever_projected(self, mock_conn, event_loop_fixture):
+ from collections import deque
+
+ ids = {"read": deque(["tc-1"])}
+ step = make_step_cb(mock_conn, "s", event_loop_fixture, ids, {}, {})
+ with self._patch() as rcts, patch("acp_adapter.events.build_tool_complete") as btc:
+ rcts.return_value = MagicMock(spec=Future)
+ step(1, [{"name": "read", "result": "body"}])
+ btc.assert_called_once_with("tc-1", "read", result="body", function_args=None, snapshot=None)
+
+ def test_a_todo_plan_update_survives_the_completion_path(self, mock_conn, event_loop_fixture):
+ """The plan panel is fed by the step callback, not by the close it now skips."""
+ from collections import deque
+
+ ids, turn_state = {"todo": deque(["tc-1"])}, {}
+ progress = make_tool_progress_cb(mock_conn, "s", event_loop_fixture, ids, {}, turn_state=turn_state)
+ step = make_step_cb(mock_conn, "s", event_loop_fixture, ids, {}, turn_state)
+ todos = '{"todos": [{"content": "ship it", "status": "in_progress"}]}'
+ with self._patch() as rcts, patch("acp_adapter.events.build_tool_complete"):
+ rcts.return_value = MagicMock(spec=Future)
+ progress("tool.completed", "todo", None, None, result=todos)
+ step(1, [{"name": "todo", "result": todos}])
+ sent = [c.args[1] for c in mock_conn.session_update.call_args_list]
+ assert any(isinstance(u, AgentPlanUpdate) for u in sent)
+
+ def test_flush_fails_a_call_the_turn_never_reported(self, mock_conn, event_loop_fixture):
+ """A denied edit projects no completion; ``failed`` is the honest end state, not ``completed``."""
+ from collections import deque
+
+ from acp_adapter.events import flush_open_tool_calls
+
+ ids, meta = {"edit": deque(["tc-denied"])}, {"tc-denied": {"args": {}}}
+ with self._patch() as rcts:
+ rcts.return_value = MagicMock(spec=Future)
+ assert flush_open_tool_calls(mock_conn, "s", event_loop_fixture, ids, meta) == 1
+ update = mock_conn.session_update.call_args_list[0].args[1]
+ assert update.status == "failed"
+ assert ids == {} and meta == {}
+
+ def test_flush_is_a_no_op_when_every_call_is_closed(self, mock_conn, event_loop_fixture):
+ from acp_adapter.events import flush_open_tool_calls
+
+ assert flush_open_tool_calls(mock_conn, "s", event_loop_fixture, {}, {}) == 0
+ mock_conn.session_update.assert_not_called()