From 385ebfd33c88838e565824e677d01a025ac86f78 Mon Sep 17 00:00:00 2001 From: Ryan Monroe <36248507+rm0nroe@users.noreply.github.com> Date: Tue, 11 Aug 2026 18:28:00 -0400 Subject: [PATCH] feat(api-server): exactly-once affordances on the /v1/runs API A client that submits a run and loses the response must be able to retry without dispatching a second agent, and correlate its own Idempotency-Key back to the run the server already started. Stop must be replay-safe. - POST /v1/runs honors Idempotency-Key: a retry with the same key replays the existing run's status payload (202) instead of dispatching a second agent. Replays are served even under the concurrency limit (a replay dispatches nothing). - POST /v1/runs returns the run's full status payload snapshotted at creation (status "queued"), not the old {"run_id","status":"started"} stub, so clients can validate identity fields without an immediate poll. - Run status payloads echo idempotency_key when one was supplied. - New GET /v1/runs correlation lookup by Idempotency-Key header or idempotency_key query param (400 missing key, 404 unknown/aged-out). - POST /v1/runs/{id}/stop is terminal-safe (completed/failed/cancelled runs return their outcome unchanged) and returns the full status payload. - /v1/capabilities advertises run_idempotency, run_correlation_lookup, run_stop_idempotent + the run_lookup endpoint. run_status_durable is deliberately NOT advertised - statuses stay in-memory. - The orphan sweep prunes idempotency entries whose statuses were reaped. - Docs: user-guide api-server.md + developer-guide programmatic integration updated (zh-Hans translations left to maintainers). Known caveat: a retry reusing a key with a different body replays the first run (no body fingerprinting, unlike _idem_cache on chat/completions). 20 new tests in tests/gateway/test_api_server_idempotency.py; existing api_server + runs suites pass (one runs-suite assertion updated for the full-payload 202). Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01PudBue8TJkXx9eYg4f6niN --- gateway/platforms/api_server.py | 110 +++++- tests/gateway/test_api_server_idempotency.py | 357 ++++++++++++++++++ tests/gateway/test_api_server_runs.py | 4 +- .../programmatic-integration.md | 4 +- .../docs/user-guide/features/api-server.md | 45 ++- 5 files changed, 503 insertions(+), 17 deletions(-) create mode 100644 tests/gateway/test_api_server_idempotency.py diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py index 0097c1e11bb4d..1505de376712d 100644 --- a/gateway/platforms/api_server.py +++ b/gateway/platforms/api_server.py @@ -14,7 +14,9 @@ Exposes an HTTP server with endpoints: - GET /api/sessions/{session_id}/messages — read session message history - POST /api/sessions/{session_id}/fork — branch a session using SessionDB lineage - POST /api/sessions/{session_id}/chat[/stream] — chat with a persisted session -- POST /v1/runs — start a run, returns run_id immediately (202) +- POST /v1/runs — start a run, returns full status payload (202); + Idempotency-Key replays instead of re-dispatching +- GET /v1/runs — correlation lookup by Idempotency-Key - GET /v1/runs/{run_id} — retrieve current run status - GET /v1/runs/{run_id}/events — SSE stream of structured lifecycle events - POST /v1/runs/{run_id}/approval — resolve a pending run approval @@ -1431,6 +1433,11 @@ class APIServerAdapter(BasePlatformAdapter): self._stopping_run_ids: set[str] = set() # Pollable run status for dashboards and external control-plane UIs. self._run_statuses: Dict[str, Dict[str, Any]] = {} + # Idempotency-Key -> run_id, so a client that retries a submission + # after a lost response correlates back to the run it already + # started instead of dispatching a second agent. Pruned alongside + # _run_statuses by the orphan sweep. + self._run_idempotency: Dict[str, str] = {} # Active approval session key for each run_id. The approval core # resolves requests by session key, while API clients address the # in-flight run by run_id. @@ -2088,6 +2095,7 @@ class APIServerAdapter(BasePlatformAdapter): ("POST", "/api/jobs/{job_id}/resume", self._handle_resume_job), ("POST", "/api/jobs/{job_id}/run", self._handle_run_job), ("POST", "/v1/runs", self._handle_runs), + ("GET", "/v1/runs", self._handle_lookup_run), ("GET", "/v1/runs/{run_id}", self._handle_get_run), ("GET", "/v1/runs/{run_id}/events", self._handle_run_events), ("POST", "/v1/runs/{run_id}/approval", self._handle_run_approval), @@ -3128,6 +3136,9 @@ class APIServerAdapter(BasePlatformAdapter): "run_events_sse": True, "run_stop": True, "run_approval_response": True, + "run_idempotency": True, + "run_correlation_lookup": True, + "run_stop_idempotent": True, "tool_progress_events": True, "approval_events": True, "session_resources": True, @@ -3154,6 +3165,7 @@ class APIServerAdapter(BasePlatformAdapter): "chat_completions": {"method": "POST", "path": "/v1/chat/completions"}, "responses": {"method": "POST", "path": "/v1/responses"}, "runs": {"method": "POST", "path": "/v1/runs"}, + "run_lookup": {"method": "GET", "path": "/v1/runs"}, "run_status": {"method": "GET", "path": "/v1/runs/{run_id}"}, "run_events": {"method": "GET", "path": "/v1/runs/{run_id}/events"}, "run_approval": {"method": "POST", "path": "/v1/runs/{run_id}/approval"}, @@ -6467,6 +6479,25 @@ class APIServerAdapter(BasePlatformAdapter): if key_err is not None: return key_err + # Exactly-once submission: a retry carrying an Idempotency-Key already + # bound to a live run replays that run's status instead of starting a + # second agent. + # + # This deliberately precedes the concurrency gate. A replay is a dict + # lookup that dispatches no agent, so saturation is no reason to + # refuse it — and refusing it is actively harmful: a caller that + # reads 429 as a terminal rejection would journal the run as rejected + # while the original agent is still running. Recovery retries are + # exactly what a saturated server produces, so they must be the + # requests it keeps answering. + idempotency_key = request.headers.get("Idempotency-Key") + if idempotency_key: + existing_run_id = self._run_idempotency.get(idempotency_key) + if existing_run_id is not None: + existing_status = self._run_statuses.get(existing_run_id) + if existing_status is not None: + return web.json_response(existing_status, status=202) + # Enforce concurrency limit (shared across all agent-serving # endpoints; configurable via gateway.api_server.max_concurrent_runs). limited = self._concurrency_limited_response() @@ -6585,13 +6616,19 @@ class APIServerAdapter(BasePlatformAdapter): except Exception: pass - self._set_run_status( - run_id, - "queued", - created_at=created_at, - session_id=session_id, - model=body.get("model", self._model_name), - ) + if idempotency_key: + self._run_idempotency[idempotency_key] = run_id + + status_fields: Dict[str, Any] = { + "created_at": created_at, + "session_id": session_id, + "model": body.get("model", self._model_name), + } + if idempotency_key: + status_fields["idempotency_key"] = idempotency_key + # Snapshot: the live record is mutated by the background task, and the + # submit response must describe the run as it was accepted. + creation_status = dict(self._set_run_status(run_id, "queued", **status_fields)) # Background task outlives the HTTP response (and thus the middleware # profile scope). Capture now and re-enter inside the task/executor. @@ -6861,8 +6898,13 @@ class APIServerAdapter(BasePlatformAdapter): response_headers = ( {"X-Hermes-Session-Key": gateway_session_key} if gateway_session_key else {} ) + # Full hermes.run payload, identical in shape to the replay path and + # to GET /v1/runs/{run_id}: callers validate run identity (run_id, + # session_id, idempotency_key echo) straight off the submit response. + # Note this reports the real lifecycle status ("queued") rather than + # the former "started" sentinel, which was never a run status. return web.json_response( - {"run_id": run_id, "status": "started"}, + creation_status, status=202, headers=response_headers, ) @@ -6882,6 +6924,37 @@ class APIServerAdapter(BasePlatformAdapter): ) return web.json_response(status) + async def _handle_lookup_run(self, request: "web.Request") -> "web.Response": + """GET /v1/runs — resolve a run by Idempotency-Key. + + Recovery path for a client that submitted a run but lost the response: + it can correlate its own key back to the run without knowing the + server-assigned run_id. The key may travel as the Idempotency-Key + header or an ``idempotency_key`` query parameter. + """ + auth_err = self._check_auth(request) + if auth_err: + return auth_err + + key = request.headers.get("Idempotency-Key") or request.query.get("idempotency_key") + if not key: + return web.json_response( + _openai_error( + "Missing Idempotency-Key header or idempotency_key query parameter", + code="missing_idempotency_key", + ), + status=400, + ) + + run_id = self._run_idempotency.get(key) + status = self._run_statuses.get(run_id) if run_id is not None else None + if status is None: + return web.json_response( + _openai_error(f"No run found for idempotency key: {key}", code="run_not_found"), + status=404, + ) + return web.json_response(status) + async def _handle_run_events(self, request: "web.Request") -> "web.StreamResponse": """GET /v1/runs/{run_id}/events — SSE stream of structured agent lifecycle events.""" auth_err = self._check_auth(request) @@ -7029,13 +7102,21 @@ class APIServerAdapter(BasePlatformAdapter): return auth_err run_id = request.match_info["run_id"] + + # Stop is idempotent against a finished run: replaying it must not + # rewrite a terminal outcome as "stopping", which would strand + # pollers waiting for a transition that can never happen. + current = self._run_statuses.get(run_id) + if current is not None and current.get("status") in {"completed", "failed", "cancelled"}: + return web.json_response(current) + agent = self._active_run_agents.get(run_id) task = self._active_run_tasks.get(run_id) if agent is None and task is None: return web.json_response(_openai_error(f"Run not found: {run_id}", code="run_not_found"), status=404) - self._set_run_status(run_id, "stopping", last_event="run.stopping") + stopping_status = self._set_run_status(run_id, "stopping", last_event="run.stopping") self._stopping_run_ids.add(run_id) if agent is not None: @@ -7052,7 +7133,7 @@ class APIServerAdapter(BasePlatformAdapter): agent, source="api_server_run_stop" ) - return web.json_response({"run_id": run_id, "status": "stopping"}) + return web.json_response(stopping_status) async def _sweep_orphaned_runs(self) -> None: """Periodically expire transport buffers and terminal status records.""" @@ -7102,6 +7183,13 @@ class APIServerAdapter(BasePlatformAdapter): for run_id in stale_statuses: self._run_statuses.pop(run_id, None) + # Correlation entries outlive nothing: once a run's status is gone the + # key can no longer resolve, so drop it rather than leak an entry per + # submitted run for the process lifetime. + for key, mapped_run_id in list(self._run_idempotency.items()): + if mapped_run_id not in self._run_statuses: + self._run_idempotency.pop(key, None) + # ------------------------------------------------------------------ # BasePlatformAdapter interface # ------------------------------------------------------------------ diff --git a/tests/gateway/test_api_server_idempotency.py b/tests/gateway/test_api_server_idempotency.py new file mode 100644 index 0000000000000..181bbb65c2df1 --- /dev/null +++ b/tests/gateway/test_api_server_idempotency.py @@ -0,0 +1,357 @@ +""" +Exactly-once affordances on the /v1/runs API. + +A client that submits a run and loses the response must be able to retry +without dispatching a second agent, and must be able to correlate its own +Idempotency-Key back to the run the server already started. Stop must also be +replay-safe: a terminal run keeps its outcome. +""" + +import asyncio +import json +from unittest.mock import MagicMock, patch + +import pytest +from aiohttp import web +from aiohttp.test_utils import TestClient, TestServer + +from tests.gateway.test_api_server import _make_adapter + + +@pytest.fixture +def adapter(): + return _make_adapter() + + +def _create_runs_app(adapter) -> web.Application: + """Build an app from the adapter's real route table. + + Using ``_http_route_table()`` rather than a hand-written route list means + these tests fail if the GET /v1/runs row is ever dropped from the table + that ``connect()`` actually registers. + """ + app = web.Application() + app["api_server_adapter"] = adapter + wanted = ("/v1/runs", "/v1/capabilities") + for method, path, handler in adapter._http_route_table(): + if path == "/v1/runs" or path.startswith("/v1/runs/") or path in wanted: + app.router.add_route(method, path, handler) + return app + + +async def _submit(client, key=None, body=None): + """POST /v1/runs, optionally carrying an Idempotency-Key.""" + headers = {"Idempotency-Key": key} if key else {} + return await client.post("/v1/runs", json=body or {"input": "hello"}, headers=headers) + + +async def _settle(adapter): + """Let each run's background task reach its terminal state.""" + for _ in range(50): + tasks = list(adapter._active_run_tasks.values()) + if all(t.done() for t in tasks): + return + await asyncio.sleep(0.01) + + +@pytest.fixture +def no_agent(adapter): + """Make the background run fail immediately. + + The endpoint contract under test is settled synchronously in the handler + (status record, key mapping, response); the agent itself only needs to + reach a terminal state without spawning executor threads. + """ + with patch.object(adapter, "_create_agent", side_effect=RuntimeError("no agent in test")): + yield + + +# --------------------------------------------------------------------------- +# POST /v1/runs — replay +# --------------------------------------------------------------------------- + + +class TestRunSubmissionIdempotency: + @pytest.mark.asyncio + async def test_repeat_key_returns_same_run_and_starts_one_run(self, adapter, no_agent): + app = _create_runs_app(adapter) + async with TestClient(TestServer(app)) as cli: + first = await _submit(cli, key="key-abc") + assert first.status == 202 + first_body = await first.json() + run_id = first_body["run_id"] + assert first_body["status"] == "queued" + + second = await _submit(cli, key="key-abc") + assert second.status == 202 + second_body = await second.json() + + # Same run, and no second agent was dispatched. + assert second_body["run_id"] == run_id + assert second_body["object"] == "hermes.run" + assert len(adapter._run_statuses) == 1 + await _settle(adapter) + + @pytest.mark.asyncio + async def test_distinct_keys_start_distinct_runs(self, adapter, no_agent): + app = _create_runs_app(adapter) + async with TestClient(TestServer(app)) as cli: + first = await _submit(cli, key="key-1") + second = await _submit(cli, key="key-2") + assert (await first.json())["run_id"] != (await second.json())["run_id"] + assert len(adapter._run_statuses) == 2 + await _settle(adapter) + + @pytest.mark.asyncio + async def test_no_key_never_replays(self, adapter, no_agent): + app = _create_runs_app(adapter) + async with TestClient(TestServer(app)) as cli: + first = await _submit(cli) + second = await _submit(cli) + assert (await first.json())["run_id"] != (await second.json())["run_id"] + assert adapter._run_idempotency == {} + await _settle(adapter) + + @pytest.mark.asyncio + async def test_fresh_submit_returns_full_status_payload(self, adapter, no_agent): + """Callers validate run identity straight off the submit response.""" + app = _create_runs_app(adapter) + async with TestClient(TestServer(app)) as cli: + resp = await _submit(cli, key="key-shape", body={"input": "hi", "session_id": "sess-shape"}) + assert resp.status == 202 + body = await resp.json() + + assert body["object"] == "hermes.run" + assert body["run_id"].startswith("run_") + assert body["status"] == "queued" + assert body["session_id"] == "sess-shape" + assert body["idempotency_key"] == "key-shape" + await _settle(adapter) + + @pytest.mark.asyncio + async def test_replay_is_served_while_the_concurrency_gate_is_closed(self, adapter, no_agent): + """A saturated server must still answer recovery retries. + + 429-ing a replay would let a caller record a terminal rejection for a + run whose agent is still executing. + """ + app = _create_runs_app(adapter) + async with TestClient(TestServer(app)) as cli: + first = await _submit(cli, key="key-saturated") + run_id = (await first.json())["run_id"] + + def _at_capacity(): + return web.json_response({"error": "at capacity"}, status=429) + + with patch.object(adapter, "_concurrency_limited_response", side_effect=_at_capacity): + # A fresh submission is refused ... + fresh = await _submit(cli) + assert fresh.status == 429 + + # ... but the keyed retry still resolves to its run. + replay = await _submit(cli, key="key-saturated") + assert replay.status == 202 + replay_body = await replay.json() + assert replay_body["run_id"] == run_id + assert replay_body["idempotency_key"] == "key-saturated" + + assert len(adapter._run_statuses) == 1 + await _settle(adapter) + + @pytest.mark.asyncio + async def test_status_payload_echoes_idempotency_key(self, adapter, no_agent): + app = _create_runs_app(adapter) + async with TestClient(TestServer(app)) as cli: + submitted = await _submit(cli, key="key-echo") + run_id = (await submitted.json())["run_id"] + + resp = await cli.get(f"/v1/runs/{run_id}") + assert resp.status == 200 + assert (await resp.json())["idempotency_key"] == "key-echo" + + # The echo survives later status transitions. + await _settle(adapter) + resp = await cli.get(f"/v1/runs/{run_id}") + body = await resp.json() + assert body["idempotency_key"] == "key-echo" + assert body["status"] == "failed" + + @pytest.mark.asyncio + async def test_status_payload_omits_key_when_header_absent(self, adapter, no_agent): + app = _create_runs_app(adapter) + async with TestClient(TestServer(app)) as cli: + submitted = await _submit(cli) + run_id = (await submitted.json())["run_id"] + + resp = await cli.get(f"/v1/runs/{run_id}") + assert "idempotency_key" not in await resp.json() + await _settle(adapter) + + @pytest.mark.asyncio + async def test_invalid_body_is_rejected_before_key_is_recorded(self, adapter, no_agent): + """A malformed retry still gets its 400 and claims no key.""" + app = _create_runs_app(adapter) + async with TestClient(TestServer(app)) as cli: + resp = await _submit(cli, key="key-bad", body={"not_input": "x"}) + assert resp.status == 400 + assert adapter._run_idempotency == {} + assert adapter._run_statuses == {} + + +# --------------------------------------------------------------------------- +# GET /v1/runs — correlation lookup +# --------------------------------------------------------------------------- + + +class TestRunCorrelationLookup: + @pytest.mark.asyncio + async def test_lookup_by_header_returns_the_run_status(self, adapter, no_agent): + app = _create_runs_app(adapter) + async with TestClient(TestServer(app)) as cli: + run_id = (await (await _submit(cli, key="key-lookup")).json())["run_id"] + + resp = await cli.get("/v1/runs", headers={"Idempotency-Key": "key-lookup"}) + assert resp.status == 200 + body = await resp.json() + assert body["run_id"] == run_id + assert body["idempotency_key"] == "key-lookup" + + # Same payload the run_id path serves. + direct = await (await cli.get(f"/v1/runs/{run_id}")).json() + assert body == direct + await _settle(adapter) + + @pytest.mark.asyncio + async def test_lookup_accepts_query_parameter(self, adapter, no_agent): + app = _create_runs_app(adapter) + async with TestClient(TestServer(app)) as cli: + run_id = (await (await _submit(cli, key="key-query")).json())["run_id"] + + resp = await cli.get("/v1/runs", params={"idempotency_key": "key-query"}) + assert resp.status == 200 + assert (await resp.json())["run_id"] == run_id + await _settle(adapter) + + @pytest.mark.asyncio + async def test_lookup_unknown_key_is_404(self, adapter): + app = _create_runs_app(adapter) + async with TestClient(TestServer(app)) as cli: + resp = await cli.get("/v1/runs", headers={"Idempotency-Key": "never-seen"}) + assert resp.status == 404 + assert (await resp.json())["error"]["code"] == "run_not_found" + + @pytest.mark.asyncio + async def test_lookup_missing_key_is_400(self, adapter): + app = _create_runs_app(adapter) + async with TestClient(TestServer(app)) as cli: + resp = await cli.get("/v1/runs") + assert resp.status == 400 + assert (await resp.json())["error"]["code"] == "missing_idempotency_key" + + @pytest.mark.asyncio + async def test_lookup_is_404_once_the_status_is_swept(self, adapter, no_agent): + app = _create_runs_app(adapter) + async with TestClient(TestServer(app)) as cli: + await _submit(cli, key="key-swept") + await _settle(adapter) + + # Age the terminal status past its retention window and sweep. + for status in adapter._run_statuses.values(): + status["updated_at"] = 0.0 + adapter._sweep_orphaned_runs_once() + + assert adapter._run_idempotency == {} + resp = await cli.get("/v1/runs", headers={"Idempotency-Key": "key-swept"}) + assert resp.status == 404 + + @pytest.mark.asyncio + async def test_lookup_requires_auth(self): + adapter = _make_adapter(api_key="sk-secret") + app = _create_runs_app(adapter) + async with TestClient(TestServer(app)) as cli: + resp = await cli.get("/v1/runs", headers={"Idempotency-Key": "key-x"}) + assert resp.status == 401 + + +# --------------------------------------------------------------------------- +# POST /v1/runs/{run_id}/stop — terminal safety +# --------------------------------------------------------------------------- + + +class TestStopIdempotency: + @pytest.mark.asyncio + @pytest.mark.parametrize("terminal", ["completed", "failed", "cancelled"]) + async def test_stop_on_terminal_run_returns_payload_unchanged(self, adapter, terminal): + adapter._set_run_status("run_done", terminal, session_id="sess-1", idempotency_key="key-1") + before = dict(adapter._run_statuses["run_done"]) + # A live agent handle would normally make stop act; the terminal + # status must win regardless. + adapter._active_run_agents["run_done"] = MagicMock() + + request = MagicMock() + request.match_info = {"run_id": "run_done"} + resp = await adapter._handle_stop_run(request) + + assert resp.status == 200 + assert adapter._run_statuses["run_done"]["status"] == terminal + assert adapter._run_statuses["run_done"] == before + assert "run_done" not in adapter._stopping_run_ids + + @pytest.mark.asyncio + async def test_stop_on_active_run_returns_full_status_payload(self, adapter, monkeypatch): + from tools.process_registry import process_registry + + monkeypatch.setattr( + process_registry, "snapshot_running_ids", lambda _tid: frozenset(), raising=False + ) + monkeypatch.setattr( + process_registry, + "kill_started_since", + lambda task_id, baseline, *, source: 0, + raising=False, + ) + + adapter._set_run_status( + "run_live", "running", session_id="sess-live", idempotency_key="key-live" + ) + adapter._active_run_agents["run_live"] = MagicMock() + + request = MagicMock() + request.match_info = {"run_id": "run_live"} + resp = await adapter._handle_stop_run(request) + + assert resp.status == 200 + body = json.loads(resp.body) + # Callers get the session/idempotency echo, not the bare stub. + assert body["status"] == "stopping" + assert body["run_id"] == "run_live" + assert body["session_id"] == "sess-live" + assert body["idempotency_key"] == "key-live" + assert adapter._run_statuses["run_live"]["status"] == "stopping" + + @pytest.mark.asyncio + async def test_stop_on_unknown_run_is_still_404(self, adapter): + request = MagicMock() + request.match_info = {"run_id": "run_missing"} + resp = await adapter._handle_stop_run(request) + assert resp.status == 404 + + +# --------------------------------------------------------------------------- +# /v1/capabilities +# --------------------------------------------------------------------------- + + +class TestCapabilitiesAdvertisement: + @pytest.mark.asyncio + async def test_capabilities_advertise_exactly_once_affordances(self, adapter): + app = _create_runs_app(adapter) + async with TestClient(TestServer(app)) as cli: + data = await (await cli.get("/v1/capabilities")).json() + + assert data["features"]["run_idempotency"] is True + assert data["features"]["run_correlation_lookup"] is True + assert data["features"]["run_stop_idempotent"] is True + assert data["endpoints"]["run_lookup"] == {"method": "GET", "path": "/v1/runs"} + # Run statuses live in memory only — do not claim durability. + assert "run_status_durable" not in data["features"] diff --git a/tests/gateway/test_api_server_runs.py b/tests/gateway/test_api_server_runs.py index 59ce03154ff57..84296c371e931 100644 --- a/tests/gateway/test_api_server_runs.py +++ b/tests/gateway/test_api_server_runs.py @@ -135,7 +135,9 @@ class TestStartRun: resp = await cli.post("/v1/runs", json={"input": "hello"}) assert resp.status == 202 data = await resp.json() - assert data["status"] == "started" + # POST /v1/runs now returns the run's full status payload + # snapshotted at creation, not a "started" sentinel. + assert data["status"] == "queued" assert data["run_id"].startswith("run_") status_resp = await cli.get(f"/v1/runs/{data['run_id']}") diff --git a/website/docs/developer-guide/programmatic-integration.md b/website/docs/developer-guide/programmatic-integration.md index ac7469d33eab7..fc610295332ce 100644 --- a/website/docs/developer-guide/programmatic-integration.md +++ b/website/docs/developer-guide/programmatic-integration.md @@ -102,7 +102,9 @@ Endpoints: ``` POST /v1/chat/completions OpenAI Chat Completions (streaming via SSE) POST /v1/responses OpenAI Responses API (stateful) -POST /v1/runs Start a run, returns run_id (202) +POST /v1/runs Start a run, returns full status payload (202); + Idempotency-Key replays instead of re-dispatching +GET /v1/runs Correlation lookup by Idempotency-Key GET /v1/runs/{id} Run status GET /v1/runs/{id}/events SSE stream of lifecycle events POST /v1/runs/{id}/approval Resolve a pending approval diff --git a/website/docs/user-guide/features/api-server.md b/website/docs/user-guide/features/api-server.md index ccba76e104d1c..2f5a69f53d802 100644 --- a/website/docs/user-guide/features/api-server.md +++ b/website/docs/user-guide/features/api-server.md @@ -252,11 +252,20 @@ Returns a machine-readable description of the API server's stable surface for ex "run_submission": true, "run_status": true, "run_events_sse": true, - "run_stop": true + "run_stop": true, + "run_idempotency": true, + "run_correlation_lookup": true, + "run_stop_idempotent": true } } ``` +`run_idempotency`, `run_correlation_lookup`, and `run_stop_idempotent` +advertise the exactly-once affordances on the runs API (idempotent +submission replay, `GET /v1/runs` correlation lookup, and terminal-safe +stop). `run_status_durable` is deliberately **not** advertised: run +statuses live in memory and do not survive a gateway restart. + Use this endpoint when integrating dashboards, browser UIs, or control planes so they can discover whether the running Hermes version supports runs, streaming, cancellation, and session continuity without depending on private Python internals. ## Per-request model selection @@ -344,17 +353,38 @@ In addition to `/v1/chat/completions` and `/v1/responses`, the server exposes a ### POST /v1/runs -Create a new agent run. Returns a `run_id` that can be used to subscribe to progress events. +Create a new agent run. Returns `202` with the run's full status payload +snapshotted at creation, so clients can validate identity fields without an +immediate follow-up poll. ```json { + "object": "hermes.run", "run_id": "run_abc123", - "status": "started" + "status": "queued", + "session_id": "space-session", + "model": "hermes-agent" } ``` Runs accept a simple `input` string and optional `session_id`, `instructions`, `conversation_history`, or `previous_response_id`. When `session_id` is provided, Hermes surfaces it in the run status so external UIs can correlate runs with their own conversation IDs. +Submission honors an optional **`Idempotency-Key`** header: retrying with the +same key replays the existing run's current status payload (`202`) instead of +dispatching a second agent, and replays are served even when the gateway is at +its concurrency limit (a replay dispatches nothing). Status payloads echo +`idempotency_key` whenever one was supplied. A retry that reuses a key with a +*different* body still replays the original run — clients must use one key per +logical submission. + +### GET /v1/runs + +Correlation lookup by idempotency key, for clients that submitted a run but +lost the response. Pass the key as an `Idempotency-Key` header or an +`idempotency_key` query parameter; the response is the mapped run's full +status payload. Returns `400` when no key is supplied and `404` when the key +is unknown (or the run has aged out). + ### GET /v1/runs/\{run_id\} Poll the current run state. This is useful for dashboards that need status without holding an SSE connection open, or for UIs that reconnect after navigation. @@ -396,11 +426,18 @@ subscriber continues draining normally. ### POST /v1/runs/\{run_id\}/stop -Interrupt a running agent turn. The endpoint returns immediately with `{"status": "stopping"}` while Hermes asks the active agent to stop at the next safe interruption point. +Interrupt a running agent turn. The endpoint returns immediately with the +run's full status payload (`status: "stopping"`) while Hermes asks the active +agent to stop at the next safe interruption point. The run stays tracked as `stopping` until the executor-backed work exits, then settles as `cancelled`; requesting stop never hides a worker that is still running. +Stop is **terminal-safe**: requesting stop on a run that already reached +`completed`, `failed`, or `cancelled` returns that run's outcome unchanged +instead of rewriting it to `stopping`, so a replayed stop can never mask a +finished run's real result. + ### POST /v1/runs/\{run_id\}/approval Resolve a pending approval for a run that is waiting on a human decision (for example, a tool call gated behind an approval policy). The body carries the approval decision; the run resumes once the decision is recorded. This endpoint is advertised in `/v1/capabilities` as the `run_approval` feature so external UIs can detect support before surfacing an approval prompt.