The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: attribute gateway lifecycle stops to their system issuer, not the user
teknium19d0ab880bc5c
diff --git a/agent/interrupt_scope.py b/agent/interrupt_scope.pyindex e08a66a823e..26f664c81aa 100644--- a/agent/interrupt_scope.py+++ b/agent/interrupt_scope.py@@ -21,27 +21,35 @@ from agent.interrupt_compat import request_hard_interrupt_ACTIVE_SCOPE: ContextVar[Optional["InterruptScope"]] = ContextVar("hermes_interrupt_scope", default=None)+_TOOL_REASON_HOST_CANCELLED = "host cancelled the command"++class InterruptScope:def __init__(self) -> None:self._lock = threading.Lock()self._agents: list[Any] = []self.reason: Optional[str] = None+ self._tool_reason: Optional[str] = _TOOL_REASON_HOST_CANCELLED++ def cancel(self, reason: str, *, tool_reason: Optional[str] = _TOOL_REASON_HOST_CANCELLED) -> None:+ """Latch ``reason`` and hard-interrupt every agent running under this scope.- def cancel(self, reason: str) -> None:- """Latch ``reason`` and hard-interrupt every agent running under this scope."""+ ``tool_reason`` names the system issuer; pass ``None`` for a human stop so the turn is+ attributed to the user rather than to the host (#112647)."""with self._lock:self.reason = reason+ self._tool_reason = tool_reasonagents = list(self._agents)for agent in agents:- request_hard_interrupt(agent, reason, tool_reason="host cancelled the command")+ request_hard_interrupt(agent, reason, tool_reason=tool_reason)@contextmanagerdef track(self, agent: Any) -> Iterator[None]:with self._lock:self._agents.append(agent)- reason = self.reason+ reason, tool_reason = self.reason, self._tool_reasonif reason is not None:- request_hard_interrupt(agent, reason, tool_reason="host cancelled the command")+ request_hard_interrupt(agent, reason, tool_reason=tool_reason)try:yieldfinally:diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex 1d59ea2e85f..bdb78436275 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -664,7 +664,8 @@ async def _abandon_agent_task(agent = agent_ref[0] if agent_ref else Noneif agent is not None:with suppress(Exception):- request_hard_interrupt(agent, reason)+ # The abandoning client/server is the issuer, not the user (#112647).+ request_hard_interrupt(agent, reason, tool_reason=reason.lower())_reap_disconnected_agent_processes(agent, source=reap_source)if not agent_task.done():agent_task.cancel()@@ -1208,7 +1209,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):interrupted = 0for agent in agents.values():try:- if request_hard_interrupt(agent, reason):+ if request_hard_interrupt(agent, reason, tool_reason="gateway shutdown"):interrupted += 1except Exception as exc:logger.debug("[api_server] failed interrupting active agent: %s", exc)diff --git a/gateway/run.py b/gateway/run.pyindex cf474612d5d..0eac13a0e5f 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -2581,6 +2581,9 @@ _INTERRUPT_REASON_TIMEOUT = "Execution timed out (inactivity)"# ``tool_reason`` for the inactivity timeout: attributes the stop to the gateway watchdog (#112647)._INTERRUPT_TOOL_REASON_TIMEOUT = "gateway inactivity watchdog"_INTERRUPT_REASON_EVICTED = "Session ended while the turn was running"+# ``tool_reason`` for eviction / shutdown: these stops are system-issued, not user stops (#112647).+_INTERRUPT_TOOL_REASON_EVICTED = "session evicted"+_INTERRUPT_TOOL_REASON_GATEWAY_SHUTDOWN = "gateway shutdown"_INTERRUPT_REASON_SSE_DISCONNECT = "SSE client disconnected"_INTERRUPT_REASON_GATEWAY_SHUTDOWN = "Gateway shutting down"_INTERRUPT_REASON_GATEWAY_RESTART = "Gateway restarting"diff --git a/gateway/run_agent_cache.py b/gateway/run_agent_cache.pyindex 1197ab4a330..04ee5b6b024 100644--- a/gateway/run_agent_cache.py+++ b/gateway/run_agent_cache.py@@ -424,9 +424,12 @@ class GatewayAgentCacheMixin:if interrupt_event is not None:interrupt_event._hermes_run_generation = int(generation)- def _interrupt_running_turn(self, session_key: str, *, interrupt_reason: str, invalidation_reason: str) -> int:+ def _interrupt_running_turn(+ self, session_key: str, *, interrupt_reason: str, invalidation_reason: str, tool_reason: str | None = None,+ ) -> int:"""Sync core shared by /stop, /new and eviction: request a hard interrupt on the in-flightagent, invalidate its run generation, and reap the tool processes that turn spawned.+ ``tool_reason`` names a system issuer (eviction); ``None`` keeps the user attribution of /stop and /new.Returns the post-bump generation."""from contextvars import copy_contextfrom gateway.run import _AGENT_PENDING_SENTINEL, _reap_gateway_turn_processes, request_hard_interrupt@@ -438,7 +441,7 @@ class GatewayAgentCacheMixin:# bump and release below are the cleanup that matters.with _log_suppressed(logging.WARNING, "Failed to interrupt running agent for %s; continuing",session_key, exc_info=True):- request_hard_interrupt(running_agent, interrupt_reason)+ request_hard_interrupt(running_agent, interrupt_reason, tool_reason=tool_reason)_process_task_id = getattr(running_agent, "_gateway_turn_process_task_id", "")_process_baseline = getattr(running_agent, "_gateway_turn_process_baseline", None)# Bump the generation BEFORE scheduling the reap thread and capture the post-bump value:diff --git a/gateway/run_inbound.py b/gateway/run_inbound.pyindex 5ac3c75dca8..a43dcaa8c4e 100644--- a/gateway/run_inbound.py+++ b/gateway/run_inbound.py@@ -544,9 +544,10 @@ class GatewayInboundMixin:logger.debug("reaped-session staleness check failed", exc_info=True)def _hm_evict_running_agent(self, _quick_key: str, reason: str) -> None:- from gateway.run import _INTERRUPT_REASON_EVICTED+ from gateway.run import _INTERRUPT_REASON_EVICTED, _INTERRUPT_TOOL_REASON_EVICTED_generation_at_interrupt = self._interrupt_running_turn(- _quick_key, interrupt_reason=_INTERRUPT_REASON_EVICTED, invalidation_reason=reason)+ _quick_key, interrupt_reason=_INTERRUPT_REASON_EVICTED, invalidation_reason=reason,+ tool_reason=_INTERRUPT_TOOL_REASON_EVICTED)self._drop_turn_slot(_quick_key, run_generation=_generation_at_interrupt)def _hm_merge_pending_for_source(diff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.pyindex ee20fffa2e5..4e68091527e 100644--- a/gateway/run_shutdown.py+++ b/gateway/run_shutdown.py@@ -248,7 +248,7 @@ class GatewayShutdownMixin:def _interrupt_deferred_agent_workers(self, reason: str) -> int:"""Request cancellation of detached executor-backed agent work."""- from gateway.run import request_hard_interrupt+ from gateway.run import _INTERRUPT_TOOL_REASON_GATEWAY_SHUTDOWN, request_hard_interruptworkers = getattr(self, "_deferred_agent_workers", None)if not isinstance(workers, dict):return 0@@ -259,7 +259,7 @@ class GatewayShutdownMixin:continueseen.add(id(agent))try:- request_hard_interrupt(agent, reason)+ request_hard_interrupt(agent, reason, tool_reason=_INTERRUPT_TOOL_REASON_GATEWAY_SHUTDOWN)interrupted += 1except Exception as exc:logger.debug("Failed interrupting deferred agent worker during shutdown: %s", exc)@@ -760,12 +760,12 @@ class GatewayShutdownMixin:return snapshot, timed_outdef _interrupt_running_agents(self, reason: str) -> None:- from gateway.run import _AGENT_PENDING_SENTINEL, request_hard_interrupt+ from gateway.run import _AGENT_PENDING_SENTINEL, _INTERRUPT_TOOL_REASON_GATEWAY_SHUTDOWN, request_hard_interruptfor session_key, agent in list(self._running_agents.items()):if agent is _AGENT_PENDING_SENTINEL:continuewith _log_suppressed(logging.DEBUG, "Failed interrupting agent during shutdown: %s"):- request_hard_interrupt(agent, reason)+ request_hard_interrupt(agent, reason, tool_reason=_INTERRUPT_TOOL_REASON_GATEWAY_SHUTDOWN)logger.debug("Interrupted running agent for session %s during shutdown", session_key)# API-server / desk turns are adapter-owned and never enter _running_agents, so the loop above# cannot see them even though _drain_active_agents() waited for them.diff --git a/hermes_cli/web_routers/chat_ws.py b/hermes_cli/web_routers/chat_ws.pyindex 55f59b7ddd0..cea13905786 100644--- a/hermes_cli/web_routers/chat_ws.py+++ b/hermes_cli/web_routers/chat_ws.py@@ -172,8 +172,12 @@ def _execute_console_line(async def _unwind_console_worker(worker: Any, scope: InterruptScope, reason: str) -> None:"""Stop the command's worker after cancel/timeout: asyncio can only drop the waiter, so interrupt- any agent the command forked (closing its provider request) and wait for the thread to exit."""- scope.cancel(f"Console command {reason}")+ any agent the command forked (closing its provider request) and wait for the thread to exit.+ A user cancel is attributed to the user; only the timeout is a host-issued stop (#112647)."""+ if reason == "cancelled":+ scope.cancel(f"Console command {reason}", tool_reason=None)+ else:+ scope.cancel(f"Console command {reason}")if worker.cancel(): # still queued: never ranreturnexited = asyncio.wrap_future(worker)diff --git a/tests/agent/test_cross_process_turn_lease.py b/tests/agent/test_cross_process_turn_lease.pyindex 3472bb545f4..7f7be8e4328 100644--- a/tests/agent/test_cross_process_turn_lease.py+++ b/tests/agent/test_cross_process_turn_lease.py@@ -400,7 +400,7 @@ def test_run_conversation_interrupts_when_lease_refresh_lost(monkeypatch):agent._session_turn_lease_refresh_interval = 0.01interrupt_calls = []- def track_interrupt(message=None, hard_cancel=False):+ def track_interrupt(message=None, hard_cancel=False, **kwargs):interrupt_calls.append((message, hard_cancel))agent._interrupt_requested = Trueagent._interrupt_message = message@@ -450,7 +450,7 @@ def test_run_conversation_interrupts_when_lease_refresh_errors(monkeypatch):agent._session_turn_lease_refresh_interval = 0.01interrupt_calls = []- def track_interrupt(message=None, hard_cancel=False):+ def track_interrupt(message=None, hard_cancel=False, **kwargs):interrupt_calls.append((message, hard_cancel))agent._interrupt_requested = Trueagent._interrupt_message = message@@ -499,7 +499,7 @@ def test_refresh_error_after_loop_completion_does_not_poison_next_turn(monkeypatinterrupt_started = threading.Event()interrupt_calls = []- def track_interrupt(message=None, hard_cancel=False):+ def track_interrupt(message=None, hard_cancel=False, **kwargs):interrupt_calls.append((message, hard_cancel))interrupt_started.set()release_refresh.wait(timeout=2.0)@@ -553,7 +553,7 @@ def test_late_refresh_miss_after_release_does_not_interrupt(monkeypatch):released = threading.Event()interrupt_calls = []- def track_interrupt(message=None, hard_cancel=False):+ def track_interrupt(message=None, hard_cancel=False, **kwargs):interrupt_calls.append((message, hard_cancel))agent._interrupt_requested = Trueagent._interrupt_message = messagediff --git a/tests/agent/test_interrupt_issuer_attribution.py b/tests/agent/test_interrupt_issuer_attribution.pyindex e3a63a43670..8664fb24167 100644--- a/tests/agent/test_interrupt_issuer_attribution.py+++ b/tests/agent/test_interrupt_issuer_attribution.py@@ -56,3 +56,43 @@ def test_human_stops_have_no_system_issuer():assert interrupt_issuer(agent) is Nonefinally:set_interrupt(False)+++def test_gateway_lifecycle_producers_name_a_system_issuer():+ """Gateway stop, session eviction and an abandoned SSE run are system stops: none of them may fall+ through to the reason-less default that books ``interrupted_by_user`` (#112647)."""+ import asyncio+ from types import SimpleNamespace++ from gateway.platforms.api_server import _abandon_agent_task+ from gateway.run_agent_cache import GatewayAgentCacheMixin+ from gateway.run_inbound import GatewayInboundMixin+ from gateway.run_shutdown import GatewayShutdownMixin++ try:+ stopping_agent = _bare_agent()+ runner = SimpleNamespace(+ _running_agents={"k": stopping_agent}, _interrupt_api_server_runs=lambda reason: 0,+ _interrupt_deferred_agent_workers=lambda reason: 0,+ )+ GatewayShutdownMixin._interrupt_running_agents(runner, "Gateway shutting down")+ assert interrupt_issuer(stopping_agent) == "gateway_shutdown"++ evicted_agent = _bare_agent()+ runner = SimpleNamespace(+ _peek_session_state=lambda key: SimpleNamespace(turn=SimpleNamespace(agent=evicted_agent)),+ _invalidate_session_run_generation=lambda key, reason="": 1,+ _drop_turn_slot=lambda key, run_generation=None: None,+ )+ runner._interrupt_running_turn = (+ lambda *a, **kw: GatewayAgentCacheMixin._interrupt_running_turn(runner, *a, **kw)+ )+ GatewayInboundMixin._hm_evict_running_agent(runner, "k", "history_reset")+ assert interrupt_issuer(evicted_agent) == "session_evicted"++ sse_agent = _bare_agent()+ asyncio.run(_abandon_agent_task(+ [sse_agent], SimpleNamespace(done=lambda: True), "SSE client disconnected", await_cancel=False))+ assert interrupt_issuer(sse_agent) == "sse_client_disconnected"+ finally:+ set_interrupt(False)diff --git a/tests/gateway/test_gateway_shutdown.py b/tests/gateway/test_gateway_shutdown.pyindex 0bbd47f1ee9..233f7fbde27 100644--- a/tests/gateway/test_gateway_shutdown.py+++ b/tests/gateway/test_gateway_shutdown.py@@ -96,7 +96,7 @@ async def test_gateway_stop_interrupts_running_agents_and_cancels_adapter_tasks():await runner.stop()- running_agent.interrupt.assert_called_once_with("Gateway shutting down")+ running_agent.interrupt.assert_called_once_with("Gateway shutting down", tool_reason="gateway shutdown")disconnect_mock.assert_awaited_once()shutdown_cached_clients.assert_called_once()assert runner.adapters == {}diff --git a/tests/gateway/test_hygiene_deferred_work_drain.py b/tests/gateway/test_hygiene_deferred_work_drain.pyindex 99be4e46f8e..3f19cd122f1 100644--- a/tests/gateway/test_hygiene_deferred_work_drain.py+++ b/tests/gateway/test_hygiene_deferred_work_drain.py@@ -71,7 +71,7 @@ async def test_timed_out_codex_hygiene_worker_remains_visible_to_shutdown():assert runner._active_deferred_agent_worker_count() == 1with patch("gateway.run.request_hard_interrupt") as interrupt:runner._interrupt_running_agents("gateway shutdown")- interrupt.assert_called_once_with(agent, "gateway shutdown")+ interrupt.assert_called_once_with(agent, "gateway shutdown", tool_reason="gateway shutdown")release.set()for _ in range(100):@@ -112,7 +112,7 @@ async def test_deferred_hygiene_worker_times_out_and_receives_interrupt():assert _snapshot == {}with patch("gateway.run.request_hard_interrupt") as interrupt:runner._interrupt_running_agents("gateway shutdown")- interrupt.assert_called_once_with(agent, "gateway shutdown")+ interrupt.assert_called_once_with(agent, "gateway shutdown", tool_reason="gateway shutdown")worker.cancel()