Skip to content

The agent that grows with you

fix(gateway): a /v1/runs steer sent before the turn builds its agent reaches that agent

Tekniumb70a971ebced
diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.py
index 4b407bbbaea..a1c8b61bcfe 100644
--- a/gateway/platforms/api_server_runs.py
+++ b/gateway/platforms/api_server_runs.py
@@ -1349,6 +1349,11 @@ async def _handle_run_clarify(self, request, *, _api_server):
return await _respond_authority_run(self, run_id, body, kind='clarify', _api_server=_api_server)
+def _steer_refused(_openai_error, run_id):
+ return _json_error(_openai_error, f"Run is not currently accepting steer input: {run_id}",
+ code="run_not_accepting_steer", status=409)
+
+
async def _handle_steer_run(self, request: web.Request, *, _api_server) -> web.Response:
"""POST /v1/runs/{run_id}/steer — inject guidance into a running agent."""
_openai_error = _api_server._openai_error
@@ -1356,25 +1361,16 @@ async def _handle_steer_run(self, request: web.Request, *, _api_server) -> web.R
self, request, _api_server=_api_server, permission=None, active_fallback=False)
if err is not None:
return err
+ owned = None
if getattr(self.gateway_runner, 'session_authority', None) is not None:
from gateway.platforms.api_server_authority_runs import run_admission
- from hermes_state_runtime import RuntimeStoreError
owned = run_admission(self, run_id)
+ owned = owned if run_id not in self._stopping_run_ids else None
agent = None
- if owned is not None and run_id not in self._stopping_run_ids:
- authority, row = owned
- try:
- authority.check_approval_generation(row['target_session_id'], row['generation'])
- from gateway.session_contract import SessionRef
- agent = authority.agent(SessionRef(authority.profile_id, row['target_session_id']))
- except RuntimeStoreError:
- pass
# /stop keeps agent refs during cooperative shutdown, so the status gate (not the
# agent ref) is what rejects stop-then-steer.
- if status.get("status") != "running" or not hasattr(agent, "steer"):
- return _json_error(
- _openai_error, f"Run is not currently accepting steer input: {run_id}",
- code="run_not_accepting_steer", status=409)
+ if status.get("status") != "running" or (owned is None and not hasattr(agent, "steer")):
+ return _steer_refused(_openai_error, run_id)
body, err = await self._read_json_body(request)
if err:
return err
@@ -1384,6 +1380,23 @@ async def _handle_steer_run(self, request: web.Request, *, _api_server) -> web.R
return _json_error(
_openai_error, "Missing non-empty steer text; expected 'input', 'message', or 'text'.",
code="invalid_steer_input", status=400)
+ if owned is not None:
+ from gateway.session_contract import SessionRef
+ from hermes_state_runtime import RuntimeStoreError
+ authority, row = owned
+ sid, latched = row['target_session_id'], False
+ try:
+ with authority.sessions[sid].event_stream.lock:
+ authority.check_approval_generation(sid, row['generation'])
+ # Before the claimed turn adopts its agent the steer is latched for that agent.
+ agent, latched = authority.steer_agent(SessionRef(authority.profile_id, sid), row['generation'], steer_text)
+ except (KeyError, RuntimeStoreError):
+ agent = None
+ if not latched and not hasattr(agent, "steer"):
+ return _steer_refused(_openai_error, run_id)
+ if latched:
+ _mark_run_event(self, run_id, "run.steered", accepted=True)
+ return web.json_response({"object": "hermes.run.steer", "run_id": run_id, "accepted": True})
try:
accepted = bool(agent.steer(steer_text))
except Exception as exc:
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 7c4b741d01b..65168a1355d 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -642,6 +642,22 @@ class SessionAuthority:
agent = running.get(self.sessions[ref.session_id].route)
return agent is not None and agent is not _AGENT_PENDING_SENTINEL
+ def steer_agent(self, ref, generation, text):
+ """The agent a steer for this running generation reaches; the caller holds the session's
+ event_stream.lock after check_approval_generation. Before the turn adopts its agent the
+ resident one is the previous turn's cached agent, which this turn may replace, so *text* is
+ latched for the agent this generation adopts (adopt_agent, under the same lock):
+ ``(None, True)``. A claim with no steer seam (cron, managed worker) latches nothing."""
+ adopted_generation, agent = self.adopted.get(ref.session_id, (None, None))
+ if adopted_generation != generation:
+ agent = self.agent(ref) if self._runs_own_agent(ref) else None
+ from gateway.session_busy_controls import adopts_owner_agent
+ if agent is not None or text is None or not adopts_owner_agent(self, ref):
+ return agent, False
+ latched, texts = self.pending_steers.get(ref.session_id, (None, []))
+ self.pending_steers[ref.session_id] = (generation, [*texts, text] if latched == generation else [text])
+ return None, True
+
def adopt_agent(self, session_id, generation, agent):
"""The turn installs its agent for the running claim; a Stop latched while there
was no agent to deliver it to fires now, never against a later generation. A Stop
diff --git a/gateway/session_busy_controls.py b/gateway/session_busy_controls.py
index cb9b63f43d5..96c239e92a2 100644
--- a/gateway/session_busy_controls.py
+++ b/gateway/session_busy_controls.py
@@ -111,7 +111,7 @@ async def yolo_config(connection, ref, params, write):
return {'key': 'yolo', 'value': '1' if enabled else '0', 'scope': 'session'}
-def _adopts_owner_agent(authority, ref):
+def adopts_owner_agent(authority, ref):
"""The claimed turn runs an in-process owner agent, which adopt_agent hands latched steers to;
a cron job or a managed worker has no steer seam, so a latch there would be acknowledged and lost."""
from gateway.session_managed_worker import managed_policy
@@ -138,17 +138,10 @@ async def correct(connection, ref, params, *, verb):
# agent. Refuse explicitly instead of acknowledging undeliverable text.
if ref.session_id in getattr(authority, '_managed_workers', {}):
raise RuntimeStoreError('unsupported_control')
- adopted_generation, agent = authority.adopted.get(ref.session_id, (None, None))
- if adopted_generation != generation:
- # Before adoption the resident agent is the previous turn's cached one, which this
- # turn may replace: only a running slot holding a real agent is this turn's own.
- agent = authority.agent(ref) if authority._runs_own_agent(ref) else None
- if agent is None and verb == 'steer' and _adopts_owner_agent(authority, ref):
- # Accepted for this exact claim before its turn built an agent: adopt_agent hands it
- # to the agent this generation adopts (under this lock), never to a later one.
- latched, texts = authority.pending_steers.get(ref.session_id, (None, []))
- authority.pending_steers[ref.session_id] = (generation, [*texts, params['text']] if latched == generation
- else [params['text']])
+ # Accepted for this exact claim before its turn built an agent: steer_agent latches it for
+ # the agent this generation adopts, never a later one.
+ agent, latched = authority.steer_agent(ref, generation, params['text'] if verb == 'steer' else None)
+ if latched:
return {'status': 'queued', 'text': params['text'], 'execution_generation': generation,
'authority_epoch': authority.epoch}
method = getattr(agent, verb, None)
diff --git a/tests/gateway/test_api_run_steer_before_adopt.py b/tests/gateway/test_api_run_steer_before_adopt.py
new file mode 100644
index 00000000000..6d757d82acd
--- /dev/null
+++ b/tests/gateway/test_api_run_steer_before_adopt.py
@@ -0,0 +1,80 @@
+"""POST /v1/runs/{id}/steer accepted while the claimed turn is still building its agent reaches it."""
+import asyncio
+import threading
+from types import SimpleNamespace
+
+import pytest
+
+from agent.interrupt_control import InterruptControlMixin
+from gateway.config import GatewayConfig
+from gateway.session import SessionStore
+from gateway.session_authority import initialize_session_authority
+from hermes_state import SessionDB
+from tests.gateway.test_api_unknown_resolution import _AUTH_HEADERS, _adapter, _runs_client
+
+
+class Agent(InterruptControlMixin):
+ def __init__(self):
+ self._pending_steer = None
+ self._interrupt_requested = False
+
+ def interrupt(self, *args, **kwargs):
+ self._interrupt_requested = True
+
+
+async def test_run_steer_before_adoption_reaches_the_turns_agent_not_the_cached_one(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ store = SessionStore(tmp_path / "sessions", GatewayConfig())
+ db = SessionDB(tmp_path / "state.db")
+ stale, fresh = Agent(), Agent()
+ claimed, steered = asyncio.Event(), threading.Event()
+ seen = {}
+
+ async def answer(event):
+ from gateway.session_results import execution_result
+ authority = runner.session_authority
+ sid = next(iter(authority.sessions))
+ claimed.set()
+ await asyncio.to_thread(steered.wait, 5)
+ # The turn builds a fresh agent (the cached one is replaced) and the wiring adopts it.
+ generation = authority._handle(SimpleNamespace(profile_id=authority.profile_id, session_id=sid)).execution_generation
+ await asyncio.to_thread(authority.adopt_agent, sid, generation, fresh)
+ seen["drained"] = fresh._drain_pending_steer()
+ execution_result.get()["result"] = {"final_response": "ok", "messages": []}
+ return "ok"
+
+ # The previous turn's reusable agent is what the route resolves to before adoption.
+ runner = SimpleNamespace(_session_db=db, session_store=store, _draining=False, _handle_message=answer,
+ _cached_agent_for=lambda route: stale)
+ authority = await initialize_session_authority(runner, profile_id="default", instance_id="api-steer")
+ adapter = _adapter(runner, db)
+ runner._adapter_for_source = lambda source: adapter
+ client = _runs_client(adapter)
+ await client.start_server()
+ try:
+ started = await client.post("/v1/runs", json={"input": "build it", "session_id": "api-session"},
+ headers=_AUTH_HEADERS | {"Idempotency-Key": "steer-run"})
+ assert started.status == 202, await started.text()
+ run_id = (await started.json())["run_id"]
+ await asyncio.wait_for(claimed.wait(), 5)
+
+ for text in ("use the staging db", "and skip tests"):
+ response = await client.post(f"/v1/runs/{run_id}/steer", json={"input": text}, headers=_AUTH_HEADERS)
+ assert response.status == 200, await response.text()
+ assert (await response.json())["accepted"] is True
+ steered.set()
+ await asyncio.wait_for(authority.sessions["api-session"].task, 5)
+
+ assert seen["drained"] == "use the staging db\nand skip tests", "the acknowledged steer was lost"
+ assert stale._pending_steer is None, "the replaced cached agent must not swallow it"
+ assert not authority.pending_steers
+ finally:
+ steered.set()
+ for task in list(adapter._active_run_tasks.values()):
+ task.cancel()
+ await client.close()
+ adapter._response_store.close()
+ adapter._run_idempotency_store.close()
+ db.close()
+ store.close_all_db_handles()