Skip to content

The agent that grows with you

fix(api): streaming chat approvals reach the SSE and answer via /v1/runs under the gateway

Teknium714c262f56bf
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index afe364641c0..9c3b4fda331 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -4159,7 +4159,8 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
route_source=route_source, confirmed_runtime_lock=confirmed_runtime_lock,
bind_declared_conversation=bind_declared_conversation, request_id=request_id,
history_from_session=history_from_session, session_history_delivery=session_history_delivery,
- turn_author=turn_author, resume_unanswered_turn=resume_unanswered_turn)
+ turn_author=turn_author, resume_unanswered_turn=resume_unanswered_turn,
+ approval_notify_callback=approval_notify_callback, approval_session_key=approval_session_key)
loop = asyncio.get_running_loop()
# ContextVars do not follow run_in_executor threads: capture here, re-enter in _run().
request_profile = _api_request_profile.get()
diff --git a/gateway/platforms/api_server_authority_runs.py b/gateway/platforms/api_server_authority_runs.py
index 4cf914a5f89..2460efb0469 100644
--- a/gateway/platforms/api_server_authority_runs.py
+++ b/gateway/platforms/api_server_authority_runs.py
@@ -16,8 +16,13 @@ def run_admission(adapter, run_id):
authority = _authority(adapter)
if authority is None:
return None
+ # A streaming completion's public run id names its admission through the in-memory binding
+ # its own request holds; every other run id is the admission's durable request id.
+ alias = getattr(adapter, '_run_admission_aliases', {}).get(run_id)
+ column, value = ('admission_id', alias) if alias else ('request_id', run_id)
with authority.db._read_ctx() as conn:
- rows = conn.execute("SELECT * FROM session_admissions WHERE principal_id='api' AND request_id=?", (run_id,)).fetchall()
+ rows = conn.execute(f"SELECT * FROM session_admissions WHERE principal_id='api' AND {column}=?",
+ (value,)).fetchall()
if len(rows) > 1:
raise RuntimeStoreError('admission_conflict')
return (authority, _row(rows[0])) if rows else None
diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.py
index ac2bc685ba4..7a8fee4f910 100644
--- a/gateway/platforms/api_server_runs.py
+++ b/gateway/platforms/api_server_runs.py
@@ -230,6 +230,8 @@ def _initialize_run_state(self, *, store_factory) -> None:
self._stopping_run_ids: set[str] = set()
self._shutdown_interrupted_run_ids: set[str] = set()
self._run_shutdown_requested_at: Optional[float] = None
+ # Streaming run id -> its canonical admission id, held while that request observes the turn.
+ self._run_admission_aliases: dict[str, str] = {}
(
self._run_owners, self._run_streams, self._run_streams_created, self._active_run_agents,
self._active_run_tasks, self._run_statuses, self._run_approval_sessions,
diff --git a/gateway/session_api_turn.py b/gateway/session_api_turn.py
index aae086c14fe..c7a4807a8cd 100644
--- a/gateway/session_api_turn.py
+++ b/gateway/session_api_turn.py
@@ -191,9 +191,29 @@ def _recover_api_turns(adapter, authority):
logging.getLogger(__name__).warning('API session %s paused: %s', sid, exc.reason)
-async def run_api_turn(adapter, **kwargs):
+async def run_api_turn(adapter, *, approval_notify_callback=None, approval_session_key=None, **kwargs):
admitted = admit_api_turn(adapter, **kwargs)
- return await observe_api_turn(admitted, **kwargs)
+ if approval_notify_callback is None or not approval_session_key:
+ return await observe_api_turn(admitted, **kwargs)
+ # A streaming surface advertises its own run id (``chatcmpl-*`` / ``run_*``): bind it to this
+ # exact admission so ``/v1/runs/{id}/approval`` answers the shared, generation-fenced prompt,
+ # and hand that prompt to the stream's notifier in the event shape it already emits.
+ aliases = adapter._run_admission_aliases
+ aliases[approval_session_key] = admitted[2]['admission_id']
+
+ def sink(event_type, prompt):
+ if event_type == 'approval.request':
+ choices = prompt.get('choices') or ()
+ approval_notify_callback({
+ **{k: v for k, v in prompt.items() if k not in ('kind', 'prompt_id', 'choices')},
+ 'request_id': prompt['prompt_id'], 'allow_session': 'session' in choices,
+ 'allow_permanent': 'always' in choices})
+ try:
+ with observe_api_controls(admitted, sink):
+ return await observe_api_turn(admitted, **kwargs)
+ finally:
+ if aliases.get(approval_session_key) == admitted[2]['admission_id']:
+ aliases.pop(approval_session_key)
async def observe_api_turn(admitted, **kwargs):
diff --git a/tests/gateway/test_chat_completions_approval.py b/tests/gateway/test_chat_completions_approval.py
index ba4dd9c69ee..c261c2e2443 100644
--- a/tests/gateway/test_chat_completions_approval.py
+++ b/tests/gateway/test_chat_completions_approval.py
@@ -57,3 +57,69 @@ async def test_streamed_completion_approval_resolves_via_runs_endpoint(monkeypat
assert decisions and decisions[0]["choice"] == "once"
assert event["run_id"] not in adapter._run_approval_sessions
assert adapter._run_statuses[event["run_id"]]["status"] == "completed"
+
+
+def _canonical_approval_turn(owner, decisions):
+ """A controlled canonical turn: the real blocking gateway wait, published through the
+ authority's shared controls exactly as ``TurnRunner._approval_notify_sync`` does."""
+ async def handle(event):
+ from gateway.session_results import execution_result
+ from tools.approval_gateway_wait import _await_gateway_decision
+ sid = event.source.chat_id
+ live, generation = owner.sessions[sid], owner.db.get_session(sid)['runtime_generation']
+
+ def notify(data):
+ owner.register_approval(sid, generation, live.route, data)
+ decisions.append(await asyncio.to_thread(_await_gateway_decision, live.route, notify, {
+ "command": "rm -rf /tmp/x", "description": "dangerous", "pattern_key": "rm"}))
+ execution_result.get()['result'] = {'final_response': 'ok', 'messages': []}
+ return 'ok'
+ return handle
+
+
+async def _sse_event(resp, name):
+ pending = None
+ async for raw in resp.content:
+ line = raw.decode().strip()
+ if line == f"event: {name}":
+ pending = True
+ elif pending and line.startswith("data: "):
+ return json.loads(line[6:])
+ return None
+
+
[email protected]("surface", ["chat_completions", "session_stream"])
+async def test_canonical_streamed_approval_reaches_sse_and_resolves_via_runs_endpoint(api, owner, monkeypatch, surface):
+ """Under the session authority the advertised stream run id is bound to its exact durable
+ admission: the shared approval prompt reaches the SSE, and the generation-fenced reply to
+ ``POST /v1/runs/{run_id}/approval`` resolves the same waiter WS viewers see."""
+ monkeypatch.setattr("tools.approval_context._get_approval_timeout", lambda: 5)
+ decisions = []
+ owner.runner._handle_message = _canonical_approval_turn(owner, decisions)
+ app = _create_app(api)
+ app.router.add_post("/v1/runs/{run_id}/approval", api._handle_run_approval)
+ async with TestClient(TestServer(app)) as cli:
+ if surface == "chat_completions":
+ resp = await cli.post("/v1/chat/completions", json={
+ "model": "hermes-agent", "stream": True, "messages": [{"role": "user", "content": "hi"}]})
+ prefix = "chatcmpl"
+ else:
+ owner.db.create_session("api-stream", source="api_server")
+ resp = await cli.post("/api/sessions/api-stream/chat/stream", json={"message": "hi"})
+ prefix = "run_"
+ assert resp.status == 200, await resp.text()
+ event = await asyncio.wait_for(_sse_event(resp, "approval.request"), 10)
+ assert event and event["run_id"].startswith(prefix) and event["command"], event
+ assert set(event["choices"]) == {"once", "session", "always", "deny"}
+ stale = await cli.post(f"/v1/runs/{event['run_id']}/approval", json={
+ "request_id": event["request_id"], "execution_generation": event["execution_generation"] + 1,
+ "choice": "once"})
+ assert stale.status == 409 and (await stale.json())["error"]["code"] == "stale_generation"
+ approval = await cli.post(f"/v1/runs/{event['run_id']}/approval", json={
+ "request_id": event["request_id"], "execution_generation": event["execution_generation"],
+ "choice": "once"})
+ assert approval.status == 200, await approval.text()
+ assert (await approval.json())["status"] == "resolved"
+ await asyncio.wait_for(resp.text(), 10)
+ assert decisions and decisions[0]["choice"] == "once"