Skip to content

The agent that grows with you

fix(gateway): load declared-key history and deny wake for response-chain runs

liuhao10243db45bab6e79
diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.py
index 9c5ee6b7fff..86918e0bcef 100644
--- a/gateway/platforms/api_server_runs.py
+++ b/gateway/platforms/api_server_runs.py
@@ -318,6 +318,9 @@ class _RunLaunch:
declared_selected: bool
user_message: str
conversation_history: List[Dict[str, str]]
+ # #98619: only continuation paths that reload session history may grant wake authority —
+ # a previous_response_id continuation consumes its ResponseStore snapshot instead.
+ wake_capable: bool
agent_kwargs: dict # ``_create_agent`` keyword arguments (prompt, model overrides, route, room policy)
request_profile: Any
browser_control_principal: Any
@@ -416,15 +419,23 @@ async def _handle_runs(self, request: "web.Request", *, _api_server) -> "web.Res
limited = self._concurrency_limited_response()
if limited is not None:
return limited
- if not conversation_history and session_id and not previous_response_id:
- conversation_history = await self._conversation_history_for_session(str(session_id))
run_id = f"run_{uuid.uuid4().hex}"
self._run_owners[run_id] = self._run_idempotency_scope(request)
# Same precedence as /v1/responses: body session_id > response chain > X-Hermes-Session-Key
# conversation > run_id (which would otherwise re-key every affinity surface per run).
# An explicit or chained session owns its routing key and is never rebound to the header.
_declared_selected = not session_id and bool(gateway_session_key)
- session_id = session_id or self._declared_conversation_session(gateway_session_key) or run_id
+ selected_session_id = session_id or (
+ self._declared_conversation_session(gateway_session_key) if _declared_selected else None)
+ session_id = selected_session_id or run_id
+ # History loads for the session the request actually selected — including one resolved from
+ # a declared X-Hermes-Session-Key, whose persisted delivery rows must reach the next
+ # same-key run's context (#98619). previous_response_id continuations keep their
+ # ResponseStore snapshot as history (they cannot consume a SessionDB delivery row and are
+ # accordingly denied wake capability in _run_agent_sync); the fresh run_id fallback has
+ # nothing persisted to load yet.
+ if not conversation_history and selected_session_id and not previous_response_id:
+ conversation_history = await self._conversation_history_for_session(str(selected_session_id))
q = self._run_streams[run_id] = asyncio.Queue()
created_at = self._run_streams_created[run_id] = time.time()
self._run_approval_sessions[run_id] = run_id # approval session key (see _RunLaunch)
@@ -443,7 +454,7 @@ async def _handle_runs(self, request: "web.Request", *, _api_server) -> "web.Res
self._run_idempotency_ids.add(run_id)
launch = _RunLaunch(
self, run_id, q, session_id, gateway_session_key, _declared_selected, user_message,
- conversation_history,
+ conversation_history, not previous_response_id,
agent_kwargs=dict(
ephemeral_system_prompt=instructions, session_id=session_id, gateway_session_key=gateway_session_key,
route=route, room_dispatch=room_dispatch, room_execution_policy=room_execution_policy,
@@ -487,11 +498,14 @@ def _run_agent_sync(self, run: _RunLaunch, agent, approval_notify, *, _api_serve
chat_id=session_id or "", session_key=run.approval_session_key, session_id=session_id or "",
browser_control_principal=run.browser_control_principal,
browser_control_transport_family=run.browser_control_transport_family,
- # #98619 audited opt-in: every /v1/runs session id is one the client can address
- # again (body session_id, a response chain id, a declared session key, or the
- # run_id fallback returned by the create response) — and a wake-injected turn
- # lands in session history a later run on the same id will load.
- wake_capable="1")
+ # #98619 audited opt-in: the /v1/runs session id is wake-capable only when its
+ # own continuation path reloads session history — an explicit body/chained
+ # session id or a declared X-Hermes-Session-Key conversation (both load
+ # SessionDB in _handle_runs), or the run_id fallback the client can post back
+ # as body.session_id. A previous_response_id continuation consumes its
+ # ResponseStore snapshot instead and can never see a SessionDB delivery row,
+ # so it stays default-denied until a merge contract exists for that chain.
+ wake_capable="1" if run.wake_capable else "")
if session_tokens:
resets.append((session_tokens, clear_session_vars))
if run.agent_kwargs["room_dispatch"] is not None:
diff --git a/tests/gateway/test_api_server_runs.py b/tests/gateway/test_api_server_runs.py
index 43fdbc4a268..eb5a057b173 100644
--- a/tests/gateway/test_api_server_runs.py
+++ b/tests/gateway/test_api_server_runs.py
@@ -1460,6 +1460,171 @@ class TestRunIdempotency:
assert response.status == 202
history.assert_not_awaited()
+ @pytest.mark.asyncio
+ async def test_declared_session_key_loads_selected_session_history(
+ self, auth_adapter, tmp_path
+ ):
+ """#98619: a header-only X-Hermes-Session-Key run must load the declared
+ conversation's SessionDB history — a persisted async-delegation delivery
+ row has to reach the next same-key run's context for the /v1/runs wake
+ opt-in to mean anything."""
+ adapter = auth_adapter
+ _use_idempotency_db(adapter, tmp_path / "idem.db")
+ delivered = [
+ {"role": "user", "content": "run the batch"},
+ {
+ "role": "assistant",
+ "content": "[delegated task complete] background result payload",
+ },
+ ]
+ mock_db = MagicMock()
+ mock_db.find_latest_gateway_session_for_peer.return_value = {
+ "id": "declared-session"
+ }
+ mock_db.get_messages_as_conversation.return_value = delivered
+ adapter._session_db = mock_db
+ app = _create_runs_app(adapter)
+ async with TestClient(TestServer(app)) as cli:
+ with patch.object(adapter, "_create_agent") as create:
+ agent = MagicMock()
+ agent.run_conversation.return_value = {"final_response": "done"}
+ agent.session_prompt_tokens = agent.session_completion_tokens = (
+ agent.session_total_tokens
+ ) = 0
+ create.return_value = agent
+ response = await cli.post(
+ "/v1/runs",
+ json={"input": "follow up"},
+ headers={
+ "Authorization": "Bearer sk-secret",
+ "X-Hermes-Session-Key": "conv-key",
+ },
+ )
+ assert response.status == 202
+ for _ in range(40):
+ if agent.run_conversation.called:
+ break
+ await asyncio.sleep(0.05)
+ mock_db.find_latest_gateway_session_for_peer.assert_called_with(
+ source="api_server", session_key="conv-key"
+ )
+ mock_db.get_messages_as_conversation.assert_called_with("declared-session")
+ assert (
+ agent.run_conversation.call_args.kwargs["conversation_history"] == delivered
+ )
+
+ @pytest.mark.asyncio
+ async def test_declared_key_without_live_session_row_loads_nothing(
+ self, auth_adapter, tmp_path
+ ):
+ """A declared key with no live session row keeps the fresh run_id
+ session — nothing is persisted under it yet, so no history load."""
+ adapter = auth_adapter
+ _use_idempotency_db(adapter, tmp_path / "idem.db")
+ mock_db = MagicMock()
+ mock_db.find_latest_gateway_session_for_peer.return_value = None
+ adapter._session_db = mock_db
+ history = AsyncMock(return_value=[])
+ app = _create_runs_app(adapter)
+ async with TestClient(TestServer(app)) as cli:
+ with (
+ patch.object(adapter, "_conversation_history_for_session", new=history),
+ patch.object(adapter, "_create_agent") as create,
+ ):
+ agent = MagicMock()
+ agent.run_conversation.return_value = {"final_response": "done"}
+ agent.session_prompt_tokens = agent.session_completion_tokens = (
+ agent.session_total_tokens
+ ) = 0
+ create.return_value = agent
+ response = await cli.post(
+ "/v1/runs",
+ json={"input": "fresh conversation"},
+ headers={
+ "Authorization": "Bearer sk-secret",
+ "X-Hermes-Session-Key": "conv-key",
+ },
+ )
+ assert response.status == 202
+ history.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_previous_response_id_continuation_is_not_wake_capable(
+ self, adapter, tmp_path
+ ):
+ """#98619: a previous_response_id continuation consumes its ResponseStore
+ snapshot as history and can never see a SessionDB delivery row (async
+ completion persists to SessionDB only), so it must NOT be granted wake
+ authority — delegate_task keeps its synchronous fallback on that branch."""
+ _use_idempotency_db(adapter, tmp_path / "idem.db")
+ chain_history = [
+ {"role": "user", "content": "seed turn"},
+ {"role": "assistant", "content": "seed reply"},
+ ]
+ adapter._response_store.put(
+ "resp-seed",
+ {"conversation_history": chain_history, "session_id": "chain-session"},
+ )
+ bind = MagicMock(return_value=[])
+ app = _create_runs_app(adapter)
+ async with TestClient(TestServer(app)) as cli:
+ with (
+ patch.object(adapter, "_bind_api_server_session", new=bind),
+ patch.object(adapter, "_create_agent") as create,
+ ):
+ agent = MagicMock()
+ agent.run_conversation.return_value = {"final_response": "done"}
+ agent.session_prompt_tokens = agent.session_completion_tokens = (
+ agent.session_total_tokens
+ ) = 0
+ create.return_value = agent
+ response = await cli.post(
+ "/v1/runs",
+ json={"input": "continue", "previous_response_id": "resp-seed"},
+ )
+ assert response.status == 202
+ for _ in range(40):
+ if bind.called:
+ break
+ await asyncio.sleep(0.05)
+ assert bind.call_args.kwargs["wake_capable"] == ""
+ assert (
+ agent.run_conversation.call_args.kwargs["conversation_history"]
+ == chain_history
+ )
+
+ @pytest.mark.asyncio
+ async def test_plain_run_grants_wake_capability(self, adapter, tmp_path):
+ """Control: a /v1/runs request whose session the client addresses again
+ (explicit body session_id, loaded from SessionDB) stays wake-capable."""
+ _use_idempotency_db(adapter, tmp_path / "idem.db")
+ mock_db = MagicMock()
+ mock_db.get_messages_as_conversation.return_value = []
+ adapter._session_db = mock_db
+ bind = MagicMock(return_value=[])
+ app = _create_runs_app(adapter)
+ async with TestClient(TestServer(app)) as cli:
+ with (
+ patch.object(adapter, "_bind_api_server_session", new=bind),
+ patch.object(adapter, "_create_agent") as create,
+ ):
+ agent = MagicMock()
+ agent.run_conversation.return_value = {"final_response": "done"}
+ agent.session_prompt_tokens = agent.session_completion_tokens = (
+ agent.session_total_tokens
+ ) = 0
+ create.return_value = agent
+ response = await cli.post(
+ "/v1/runs",
+ json={"input": "hello", "session_id": "client-held-session"},
+ )
+ assert response.status == 202
+ for _ in range(40):
+ if bind.called:
+ break
+ await asyncio.sleep(0.05)
+ assert bind.call_args.kwargs["wake_capable"] == "1"
+
class TestHostedRoomRuns:
@pytest.mark.asyncio