The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): close remaining unified-runtime review gaps
Brian Fernstrom83cdc63a1992
diff --git a/gateway/platforms/api_server_openai_routes.py b/gateway/platforms/api_server_openai_routes.pyindex a35de3a2134..95f3321845b 100644--- a/gateway/platforms/api_server_openai_routes.py+++ b/gateway/platforms/api_server_openai_routes.py@@ -76,8 +76,10 @@ def _finish_reason(completed, is_partial, is_failed, err_msg, agent_error=None)return 'cancelled' if not completed else 'stop'-_RESPONSES_FINGERPRINT_KEYS = ("input", "instructions", "previous_response_id", "conversation", "model",- "provider", "model_options", "tools")+_RESPONSES_FINGERPRINT_KEYS = (+ "input", "instructions", "previous_response_id", "conversation", "conversation_history", "model",+ "provider", "model_options", "tools",+)def _response_status(result):diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.pyindex 711d40b04df..000f1618b55 100644--- a/hermes_cli/gateway_chat_view.py+++ b/hermes_cli/gateway_chat_view.py@@ -22,6 +22,8 @@ class GatewayChatView:self.quiet = quiet or emitter is not Noneself.finite = Falseself.unattended = False # `-z`: the classic one-shot auto-approves; `-q` stays single-query+ self.finite_admission = None+ self._finite_events = []self.streams = {}self.completions = {}self.changed = asyncio.Event()@@ -69,16 +71,27 @@ class GatewayChatView:self.changed.set()returnadmission = params.get("admission_id") or payload.get("admission_id")- handler = {- "message.delta": self._delta, "message.complete": self._complete,- "tool.start": self._tool_start, "tool.complete": self._tool_complete,- "approval.request": self._request, "clarify.request": self._request,- "approval.settled": self._settled, "clarify.settled": self._settled,- }.get(kind)- if handler:- handler(admission, payload)+ if self.finite and admission:+ if self.finite_admission is None:+ # The owner can publish before prompt.submit's receipt reaches this client.+ # Hold admission-scoped events until we know which admission this invocation owns.+ self._finite_events.append((kind, admission, payload))+ continue+ if admission != self.finite_admission:+ continue+ self._dispatch_event(kind, admission, payload)self.changed.set()+ def _dispatch_event(self, kind, admission, payload):+ handler = {+ "message.delta": self._delta, "message.complete": self._complete,+ "tool.start": self._tool_start, "tool.complete": self._tool_complete,+ "approval.request": self._request, "clarify.request": self._request,+ "approval.settled": self._settled, "clarify.settled": self._settled,+ }.get(kind)+ if handler:+ handler(admission, payload)+def _tool_start(self, admission, payload):# Deltas before a tool call are interim commentary the final reply does not repeat;# close that segment so `_complete` measures only the final's own stream.@@ -237,6 +250,12 @@ class GatewayChatView:if receipt is None:raise GatewayClientError("One-shot requires a query")admission = receipt["admission_id"]+ self.finite_admission = admission+ for kind, event_admission, payload in self._finite_events:+ if event_admission == admission:+ self._dispatch_event(kind, event_admission, payload)+ self._finite_events.clear()+ self.changed.set()while admission not in self.completions:self.changed.clear()if self.failure:diff --git a/tests/gateway/test_api_responses_stream_retry.py b/tests/gateway/test_api_responses_stream_retry.pyindex f111ebd6f07..589c8a401dc 100644--- a/tests/gateway/test_api_responses_stream_retry.py+++ b/tests/gateway/test_api_responses_stream_retry.py@@ -42,3 +42,36 @@ async def test_exact_streaming_retry_on_named_conversation_replays_the_recorded_assert first[-1]['type'] == retry[-1]['type'] == 'response.completed'assert retry[-1]['response'] == first[-1]['response'] == plain_bodyassert calls == ['stream named']+++async def test_changed_explicit_history_conflicts_with_same_responses_idempotency_key(api, owner):+ calls = []++ async def handle(event):+ from gateway.session_results import execution_result+ calls.append(event.text)+ execution_result.get()['result'] = {'final_response': 'reply', 'messages': []}+ return 'reply'++ owner.runner._handle_message = handle+ app = web.Application()+ app.router.add_post('/v1/responses', api._handle_responses)+ body = {+ 'input': 'question',+ 'conversation_history': [{'role': 'user', 'content': 'history A'}],+ }+ headers = {'Idempotency-Key': 'history-sensitive-retry'}++ async with TestClient(TestServer(app)) as client:+ first = await client.post('/v1/responses', json=body, headers=headers)+ assert first.status == 200+ changed = await client.post('/v1/responses', json={+ **body,+ 'conversation_history': [{'role': 'user', 'content': 'history B'}],+ }, headers=headers)+ payload = await changed.json()++ assert changed.status == 409+ assert payload['error']['code'] == 'admission_conflict'+ assert calls == ['question']diff --git a/tests/gateway/test_api_server_runs.py b/tests/gateway/test_api_server_runs.pyindex 140ffcf1ce4..3549c3d3c5f 100644--- a/tests/gateway/test_api_server_runs.py+++ b/tests/gateway/test_api_server_runs.py@@ -653,6 +653,38 @@ class TestRunEvents:assert "run.completed" in bodyassert "Hello!" in body+ @pytest.mark.asyncio+ async def test_failed_sse_prepare_releases_subscriber(self, adapter):+ """A failed HTTP prepare must not leave an orphan fanout queue subscribed forever."""+ from gateway.platforms import api_server as api_server_module+ from gateway.platforms import api_server_runs++ run_id = "run_prepare_failure"+ stream = _RunStream()+ adapter._run_streams[run_id] = stream+ adapter._run_streams_created[run_id] = time.time()+ _claim_run(adapter, run_id)++ request = MagicMock()+ request.match_info = {"run_id": run_id}+ request.headers = {}+ request.path = f"/v1/runs/{run_id}/events"+ request.method = "GET"++ class FailingResponse:+ def __init__(self, *args, **kwargs):+ pass++ async def prepare(self, _request):+ raise RuntimeError("prepare failed")++ with patch.object(api_server_runs.web, "StreamResponse", FailingResponse):+ await api_server_runs._handle_run_events(+ adapter, request, _api_server=api_server_module)++ assert stream.subscribers == set()+ assert run_id not in adapter._run_streams+@pytest.mark.asyncioasync def test_two_subscribers_each_receive_every_event_and_survive_one_disconnect(self, adapter):"""/events is fanout, not a work queue: every subscriber sees the whole ordered stream,diff --git a/tests/hermes_cli/test_gateway_chat_failures.py b/tests/hermes_cli/test_gateway_chat_failures.pyindex 9faccc081b4..c7f63104e4d 100644--- a/tests/hermes_cli/test_gateway_chat_failures.py+++ b/tests/hermes_cli/test_gateway_chat_failures.py@@ -59,6 +59,47 @@ async def test_oneshot_matches_own_terminal_receipt_not_neighbor(capsys):assert capsys.readouterr().out == "mine\n"+async def test_stream_json_oneshot_filters_neighbor_events_that_arrive_before_submit_receipt(capsys):+ """Same-session work from another admission must not contaminate this invocation's JSONL."""+ import json+ from hermes_cli.gateway_chat_view import GatewayChatView+ from hermes_cli.stream_json import StreamJsonEmitter++ class Peer:+ events = asyncio.Queue()++ async def rpc(self, method, **params):+ assert method == "prompt.submit"+ for admission, text in (("neighbor", "wrong"), ("mine", "right")):+ self.events.put_nowait({"method": "event", "params": {+ "type": "message.delta", "session_id": "stored", "admission_id": admission,+ "payload": {"text": text}}})+ self.events.put_nowait({"method": "event", "params": {+ "type": "tool.start", "session_id": "stored", "admission_id": admission,+ "payload": {"tool_call_id": admission + "-tool", "tool_name": "read_file", "args": {}}}})+ self.events.put_nowait({"method": "event", "params": {+ "type": "tool.complete", "session_id": "stored", "admission_id": admission,+ "payload": {"tool_call_id": admission + "-tool", "tool_name": "read_file",+ "args": {}, "result": text, "is_error": False}}})+ self.events.put_nowait({"method": "event", "params": {+ "type": "message.complete", "session_id": "stored", "admission_id": admission,+ "payload": {"text": text, "outcome": "completed"}}})+ # Force render() to consume the events before this receipt identifies our admission.+ await asyncio.sleep(0)+ return {"admission_id": "mine"}++ emitter = StreamJsonEmitter(model="m", session_id="stored")+ view = GatewayChatView(Peer(), {"stored_session_id": "stored"}, emitter=emitter)+ assert await asyncio.wait_for(view.run("query", oneshot=True), 2) == 0++ records = [json.loads(line) for line in capsys.readouterr().out.splitlines() if line.strip()]+ assert "".join(row.get("text", "") for row in records if row["type"] == "text") == "right"+ tool_ids = [row.get("tool_call_id") for row in records if row["type"] in {"tool_use", "tool_result"}]+ assert tool_ids == ["mine-tool", "mine-tool"]+ assert all("wrong" not in json.dumps(row) and "neighbor-tool" not in json.dumps(row) for row in records)++@pytest.mark.asyncioasync def test_oneshot_replay_gap_fails_instead_of_waiting_forever():from hermes_cli.gateway_chat_view import GatewayChatView