The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(api): resolve unknown runs with durable owner scope
unsupportedpastels129c0ab02cd2
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex 9f725413e25..6536f746c1a 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -83,6 +83,7 @@ _CAPABILITY_ENDPOINTS = (("run_events", ("GET", "/v1/runs/{run_id}/events")),("run_approval", ("POST", "/v1/runs/{run_id}/approval")),("run_steer", ("POST", "/v1/runs/{run_id}/steer")),+ ("run_unknown_resolution", ("POST", "/v1/runs/{run_id}/resolve-unknown")),("run_stop", ("POST", "/v1/runs/{run_id}/stop")), ("skills", ("GET", "/v1/skills")),("toolsets", ("GET", "/v1/toolsets")), ("sessions", ("GET", "/api/sessions")),("session_create", ("POST", "/api/sessions")),@@ -2274,6 +2275,8 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):@_require_authasync def _handle_capabilities(self, request: "web.Request") -> "web.Response":"""GET /v1/capabilities — the stable, machine-readable API surface for external UIs."""+ runner = getattr(self, "gateway_runner", None)+ canonical_authority = getattr(runner, "session_authority", None) is not Nonereturn web.json_response({"object": "hermes.api_server.capabilities", "platform": "hermes-agent","model": self._model_name,@@ -2289,6 +2292,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):"responses_api": True, "responses_streaming": True, "run_submission": True,"runs_idempotency": _api_runs._idempotency_capabilities(self, store_type=RunIdempotencyStore),**_STATIC_FEATURE_FLAGS,+ "run_unknown_resolution": canonical_authority,"cors": bool(self._cors_origins),# Always advertised for feature-detection; enabled follows config."browser_extension_control": {@@ -2309,7 +2313,10 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):"transports": {"local_vps": "websocket-subprotocol-ticket","cloud": "authenticated-gateway-rpc"}}},- "endpoints": {name: {"method": m, "path": p} for name, (m, p) in _CAPABILITY_ENDPOINTS},+ "endpoints": {+ name: {"method": m, "path": p}+ for name, (m, p) in _CAPABILITY_ENDPOINTS+ if name != "run_unknown_resolution" or canonical_authority},})# -- Browser-extension control (authenticated local/VPS API) ----------------------@@ -3863,6 +3870,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):_handle_run_approval = _run_route_delegate("_handle_run_approval")_handle_run_clarify = _run_route_delegate("_handle_run_clarify")_handle_steer_run = _run_route_delegate("_handle_steer_run")+ _handle_resolve_unknown_run = _run_route_delegate("_handle_resolve_unknown_run")_handle_stop_run = _run_route_delegate("_handle_stop_run")async def _sweep_orphaned_runs(self) -> None:diff --git a/gateway/platforms/api_server_authority_runs.py b/gateway/platforms/api_server_authority_runs.pyindex cfaddf95f78..fb5d7aa4194 100644--- a/gateway/platforms/api_server_authority_runs.py+++ b/gateway/platforms/api_server_authority_runs.py@@ -1,4 +1,6 @@"""API run controls resolve durable claims, never adapter agent/task ownership."""+from dataclasses import asdict+from gateway.session_contract import Principal, SessionReffrom gateway.session_results import admission_resultfrom hermes_state_runtime import RuntimeStoreError, _row@@ -102,3 +104,25 @@ async def stop_run(adapter, run_id):elif row['status'] == 'unknown':raise RuntimeStoreError('unknown_execution')return run_projection(adapter, run_id)+++async def resolve_unknown_run(adapter, run_id, body):+ """Resolve only the exact unknown admission durably bound to an owned API run."""+ owned = run_admission(adapter, run_id)+ if owned is None:+ raise RuntimeStoreError('not_found')+ authority, row = owned+ if not isinstance(body, dict) or set(body) != {'admission_id', 'execution_generation'}:+ raise RuntimeStoreError('invalid_params')+ if body['admission_id'] != row['admission_id']:+ raise RuntimeStoreError('not_found')+ generation = body['execution_generation']+ if row['status'] != 'unknown' or type(generation) is not int or generation != row['generation']:+ raise RuntimeStoreError('stale_generation')+ actor = Principal(+ 'api', authority.profile_id, frozenset({'session:submit', 'session:control'}),+ 'api-run:' + run_id)+ receipt = await authority.resolve_unknown(+ actor, SessionRef(authority.profile_id, row['target_session_id']),+ row['admission_id'], generation)+ return asdict(receipt)diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.pyindex c1c5c04795d..3bbdeb57241 100644--- a/gateway/platforms/api_server_runs.py+++ b/gateway/platforms/api_server_runs.py@@ -111,6 +111,7 @@ def _http_routes(self) -> list[tuple[str, str, Any]]:("POST", "/v1/runs/{run_id}/approval", self._handle_run_approval),("POST", "/v1/runs/{run_id}/clarify", self._handle_run_clarify),("POST", "/v1/runs/{run_id}/steer", self._handle_steer_run),+ ("POST", "/v1/runs/{run_id}/resolve-unknown", self._handle_resolve_unknown_run),("POST", "/v1/runs/{run_id}/stop", self._handle_stop_run)]@@ -187,8 +188,10 @@ def _make_run_event_callback(self, run_id: str, loop: "asyncio.AbstractEventLoop# Answering a prompt the run raised is one capability whichever tool asked: approvals-# and clarify share the grant's ``approve`` permission.-_ROOM_CONTROL_PERMISSIONS = {"/stop": "stop", "/approval": "approve", "/clarify": "approve"}+# and clarify share the grant's ``approve`` permission. Acknowledging a lost owner epoch+# ends the run like a stop, so ``/resolve-unknown`` rides the ``stop`` permission.+_ROOM_CONTROL_PERMISSIONS = {+ "/stop": "stop", "/resolve-unknown": "stop", "/approval": "approve", "/clarify": "approve"}def _room_permission_for(request: "web.Request") -> str:@@ -543,6 +546,7 @@ async def _handle_runs(self, request: "web.Request", *, _api_server) -> "web.Reswith self._profile_scope(launch.request_profile):launch.admission = admit_api_turn(self, user_message=launch.user_message,conversation_history=launch.conversation_history, active_run_id=run_id,+ run_owner_scope=self._run_owners[run_id],turn_author=launch.turn_author,history_from_session=session_history_delivery,session_history_delivery='1' if session_history_delivery else '',@@ -772,7 +776,10 @@ def _request_owns_run(self, request: "web.Request", run_id: str) -> bool:# Run state that exists without an owner stamp is an unanswered authorization question, not a run anyone# may control — under gateway.multiplex_profiles every served profile holds a valid key, so admitting it# would make the boundary allow-all (#93689).- return self._run_idempotency_store.owns_run(scope, run_id)+ if self._run_idempotency_store.owns_run(scope, run_id):+ return True+ from gateway.session_api_turn import owns_api_run+ return owns_api_run(self, run_id, scope)def _load_owned_run(self, request, *, _api_server, permission: Optional[str], active_fallback: bool):@@ -1014,6 +1021,28 @@ async def _handle_stop_run(self, request: "web.Request", *, _api_server) -> "webreturn web.json_response({"run_id": run_id, "status": "stopping"})+async def _handle_resolve_unknown_run(+ self, request: "web.Request", *, _api_server+) -> "web.Response":+ """POST /v1/runs/{run_id}/resolve-unknown — acknowledge one lost owner epoch."""+ run_id, _, _, _, err = _load_owned_run(+ self, request, _api_server=_api_server, permission="stop", active_fallback=False)+ if err is not None:+ return err+ try:+ body = await request.json()+ except Exception:+ body = None+ from gateway.platforms.api_server_authority_runs import resolve_unknown_run+ from hermes_state_runtime import RuntimeStoreError+ try:+ result = await resolve_unknown_run(self, run_id, body)+ return web.json_response({'run_id': run_id, **result})+ except RuntimeStoreError as exc:+ return _json_error(+ _api_server._openai_error, exc.reason, code=exc.reason, status=409)++async def _sweep_orphaned_runs(self) -> None:"""Periodically expire transport buffers and terminal status records."""while True:diff --git a/gateway/session_api_turn.py b/gateway/session_api_turn.pyindex 38d32f64d53..c7e75582523 100644--- a/gateway/session_api_turn.py+++ b/gateway/session_api_turn.py@@ -2,7 +2,9 @@import asynciofrom contextvars import ContextVarfrom contextlib import contextmanager+import hmacimport json+import reimport uuidfrom gateway.config import Platform@@ -16,6 +18,7 @@ _SETTING_KEYS = ('ephemeral_system_prompt', 'requested_model', 'requested_provid'model_options', 'route', 'session_model', 'confirmed_runtime_lock','requested_runtime', 'route_source', 'room_dispatch', 'room_execution_policy','session_history_delivery')+_OWNER_SCOPE_RE = re.compile(r'[0-9a-f]{64}')def api_settings(authority, ref):@@ -34,9 +37,10 @@ def check_api_turn(authority, ref, payload):raise RuntimeStoreError('runtime_draining')if 'api_turn_v1' in payload:data = payload['api_turn_v1']- if (set(data) - {'history', 'settings', 'turn_author', 'media'}+ if (set(data) - {'history', 'settings', 'turn_author', 'media', 'run_owner_scope'}or not {'history', 'settings'} <= set(data)- or (data['history'] is not None and not isinstance(data['history'], list))):+ or (data['history'] is not None and not isinstance(data['history'], list))+ or ('run_owner_scope' in data and not _valid_owner_scope(data['run_owner_scope']))):raise RuntimeStoreError('invalid_params')if set(data['settings']) - set(_SETTING_KEYS):raise RuntimeStoreError('invalid_params')@@ -45,6 +49,10 @@ def check_api_turn(authority, ref, payload):return adapter+def _valid_owner_scope(value):+ return isinstance(value, str) and _OWNER_SCOPE_RE.fullmatch(value) is not None++def check_api_settings(adapter, settings):dispatch = settings.get('room_dispatch')if dispatch is not None:@@ -101,6 +109,13 @@ def admit_api_turn(adapter, **kwargs):settings['route'] = {k: v for k, v in route.items() if k != 'api_key'}payload = json.loads(_json({'text': kwargs['user_message'], 'api_turn_v1': {'history': None if kwargs.get('history_from_session') else kwargs['conversation_history'], 'settings': settings}}))+ run_owner_scope = kwargs.get('run_owner_scope')+ if run_owner_scope is not None:+ if not _valid_owner_scope(run_owner_scope):+ raise RuntimeStoreError('invalid_params')+ # This opaque namespace is persisted in the same row/transaction as+ # admission. It is never a bearer credential or execution input.+ payload['api_turn_v1']['run_owner_scope'] = run_owner_scopeif isinstance(kwargs['user_message'], list):from gateway.session_api_media import commit_api_imagespayload['api_turn_v1']['media'] = commit_api_images(kwargs['user_message'])@@ -125,6 +140,27 @@ def admit_api_turn(adapter, **kwargs):return authority, ref, row+def owns_api_run(adapter, run_id, owner_scope):+ """Match a caller scope against one canonical API admission, failing closed."""+ if not _valid_owner_scope(owner_scope):+ return False+ from gateway.session_authorities import active_authority+ authority = active_authority(adapter.gateway_runner)+ if authority is None:+ return False+ with authority.db._read_ctx() as conn:+ rows = conn.execute(+ "SELECT payload_json FROM session_admissions "+ "WHERE principal_id='api' AND request_id=?", (run_id,)).fetchall()+ if len(rows) != 1:+ return False+ try:+ stored = json.loads(rows[0][0])['api_turn_v1']['run_owner_scope']+ except (KeyError, TypeError, ValueError, json.JSONDecodeError):+ return False+ return _valid_owner_scope(stored) and hmac.compare_digest(stored, owner_scope)++def recover_api_turns(adapter):"""Recover committed work only after the real API adapter is published."""from gateway.session_authorities import all_authoritiesdiff --git a/tests/gateway/test_api_cutover_contract.py b/tests/gateway/test_api_cutover_contract.pyindex a57c7c2d9d1..2972f82b3b6 100644--- a/tests/gateway/test_api_cutover_contract.py+++ b/tests/gateway/test_api_cutover_contract.py@@ -1,4 +1,5 @@"""Private API ingress preserves caller content and conversation authority."""+import jsonfrom types import SimpleNamespaceimport pytest@@ -97,3 +98,29 @@ def test_api_author_is_admission_scoped_not_session_identity(api, owner):finally:api_execution.reset(token)assert seen == [row['payload']['api_turn_v1']['turn_author'], None]+++def test_persisted_owner_scope_is_private_strict_and_legacy_safe(api, owner):+ from gateway.platforms.api_server_authority_runs import run_projection+ from gateway.session_api_turn import owns_api_run, prepare_api_execution+ from hermes_state_runtime import RuntimeStoreError++ scope = 'a' * 64+ authority, ref, row = admit_api_turn(+ api, session_id='private-owner', active_run_id='run_private_owner',+ user_message='hello', conversation_history=[], run_owner_scope=scope)+ assert row['payload']['api_turn_v1']['run_owner_scope'] == scope+ assert 'run_owner_scope' not in prepare_api_execution(authority, ref, row['payload'])+ assert 'run_owner_scope' not in json.dumps(run_projection(api, 'run_private_owner'))+ assert owns_api_run(api, 'run_private_owner', scope)++ for malformed in ('A' * 64, 'a' * 63, 'g' * 64, 7):+ with pytest.raises(RuntimeStoreError, match='invalid_params'):+ admit_api_turn(+ api, session_id='invalid-owner', user_message='x',+ conversation_history=[], run_owner_scope=malformed)++ admit_api_turn(+ api, session_id='legacy-ownerless', active_run_id='run_legacy_ownerless',+ user_message='old', conversation_history=[])+ assert not owns_api_run(api, 'run_legacy_ownerless', scope)diff --git a/tests/gateway/test_api_server_runs.py b/tests/gateway/test_api_server_runs.pyindex 28b19cea3c8..1bcbf78361c 100644--- a/tests/gateway/test_api_server_runs.py+++ b/tests/gateway/test_api_server_runs.py@@ -2095,7 +2095,7 @@ class TestHostedRoomRuns:@pytest.mark.asyncio@pytest.mark.parametrize(("method", "suffix"),- [("GET", ""), ("POST", "/stop")],+ [("GET", ""), ("POST", "/stop"), ("POST", "/resolve-unknown")],)async def test_room_grant_cannot_access_ownerless_compat_run(self, auth_adapter, tmp_path, method, suffixdiff --git a/tests/gateway/test_api_server_runs_extraction.py b/tests/gateway/test_api_server_runs_extraction.pyindex 1aa43100a79..8940458932a 100644--- a/tests/gateway/test_api_server_runs_extraction.py+++ b/tests/gateway/test_api_server_runs_extraction.py@@ -176,6 +176,7 @@ def test_roomlink_and_run_route_tuples_are_shard_owned():("POST", "/v1/runs/{run_id}/approval"),("POST", "/v1/runs/{run_id}/clarify"),("POST", "/v1/runs/{run_id}/steer"),+ ("POST", "/v1/runs/{run_id}/resolve-unknown"),("POST", "/v1/runs/{run_id}/stop"),]assert all(handler.__self__ is adapter for _, _, handler in room_routes)diff --git a/tests/gateway/test_api_unknown_resolution.py b/tests/gateway/test_api_unknown_resolution.pynew file mode 100644index 00000000000..214e9f10f32--- /dev/null+++ b/tests/gateway/test_api_unknown_resolution.py@@ -0,0 +1,341 @@+"""HTTP run owners can acknowledge an exact unknown API admission after restart."""+import asyncio+from contextlib import suppress+from contextvars import ContextVar+from types import SimpleNamespace++import pytest+from aiohttp import web+from aiohttp.test_utils import TestClient, TestServer++from gateway.config import GatewayConfig, PlatformConfig+from gateway.platforms.api_server import APIServerAdapter+from gateway.session import SessionStore+from gateway.session_authority import initialize_session_authority+from gateway.session_api import restore_api_session+from hermes_state import SessionDB+from hermes_state_runtime import claim_session_input, list_session_admissions+++_OWNER = ContextVar("test_api_unknown_owner", default="owner")+_API_KEYS = {"owner": "checkpoint-two-api-key", "other": "other-valid-api-key"}+_AUTH_HEADERS = {"Authorization": f"Bearer {_API_KEYS['owner']}", "X-Test-Owner": "owner"}+_OTHER_AUTH_HEADERS = {+ "Authorization": f"Bearer {_API_KEYS['other']}", "X-Test-Owner": "other"+}+++def _runs_client(adapter):+ @web.middleware+ async def select_owner(request, handler):+ token = _OWNER.set(request.headers.get("X-Test-Owner", "owner"))+ try:+ return await handler(request)+ finally:+ _OWNER.reset(token)++ adapter._expected_api_key = lambda: _API_KEYS[_OWNER.get()]+ app = web.Application(middlewares=[select_owner])+ for method, path, handler in adapter._http_route_table():+ if path.startswith("/v1/runs"):+ app.router.add_route(method, path, handler)+ return TestClient(TestServer(app))+++def _adapter(runner, db):+ adapter = APIServerAdapter(PlatformConfig(enabled=True))+ adapter.gateway_runner = runner+ adapter._session_db = db+ return adapter+++async def _restarted_api_runs(tmp_path, monkeypatch, *, idempotent=True):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ store = SessionStore(tmp_path / "sessions", GatewayConfig())+ db = SessionDB(tmp_path / "state.db")+ executed = []++ async def answer(event):+ from gateway.session_results import execution_result++ executed.append(event.text)+ result = {"final_response": "ACK_" + event.text, "messages": []}+ execution_result.get()["result"] = result+ return result["final_response"]++ runner = SimpleNamespace(+ _session_db=db,+ session_store=store,+ _draining=False,+ _handle_message=answer,+ )+ first = await initialize_session_authority(+ runner, profile_id="default", instance_id="api-owner-1"+ )+ adapter = _adapter(runner, db)+ runner._adapter_for_source = lambda source: adapter++ # Exercise the public admission handler so run ownership and the canonical+ # principal/request-id binding are the same ones the resolution route sees.+ first._schedule = lambda ref: None+ client = _runs_client(adapter)+ await client.start_server()+ tasks = []+ try:+ admitted = []+ inputs = (("run-a", "HEAD"), ("run-b", "FOLLOWER")) if idempotent else (+ ("run-a", "SAME BODY"), ("run-b", "SAME BODY"))+ for run_id, text in inputs:+ headers = dict(_AUTH_HEADERS)+ if idempotent:+ headers["Idempotency-Key"] = run_id+ response = await client.post(+ "/v1/runs",+ json={"input": text, "session_id": "api-session"},+ headers=headers,+ )+ assert response.status == 202, await response.text()+ admitted.append(await response.json())+ assert admitted[0]["run_id"] != admitted[1]["run_id"]+ tasks = list(adapter._active_run_tasks.values())+ await asyncio.sleep(0)++ rows = list_session_admissions(db, session_id="api-session")+ head = claim_session_input(db, epoch=first.epoch, session_id="api-session")+ assert head["admission_id"] == rows[0]["admission_id"]++ restarted = await initialize_session_authority(+ runner, profile_id="default", instance_id="api-owner-2"+ )+ restore_api_session(restarted, "api-session")+ rows = list_session_admissions(db, session_id="api-session")+ assert [row["status"] for row in rows] == ["unknown", "queued"]+ await client.close()++ # A process restart constructs a new API adapter. Keeping the original+ # adapter here would preserve _run_owners and conceal the recovery gap.+ fresh = _adapter(runner, db)+ runner._adapter_for_source = lambda source: fresh+ client = _runs_client(fresh)+ await client.start_server()+ return client, (adapter, fresh), store, restarted, rows[0], rows[1], executed, tasks+ except Exception:+ await client.close()+ adapter._response_store.close()+ adapter._run_idempotency_store.close()+ store.close_all_db_handles()+ raise+++async def _close_fixture(client, adapters, store, tasks):+ for task in tasks:+ task.cancel()+ for task in tasks:+ with suppress(asyncio.CancelledError):+ await task+ await client.close()+ for adapter in adapters:+ adapter._response_store.close()+ adapter._run_idempotency_store.close()+ adapters[-1].gateway_runner.session_authority.db.close()+ store.close_all_db_handles()+++async def test_http_resolve_unknown_releases_follower_once_without_replaying_head(+ tmp_path, monkeypatch+):+ client, adapters, store, owner, unknown, follower, executed, tasks = (+ await _restarted_api_runs(tmp_path, monkeypatch)+ )+ try:+ body = {+ "admission_id": unknown["admission_id"],+ "execution_generation": unknown["generation"],+ }+ path = "/v1/runs/" + unknown["request_id"] + "/resolve-unknown"+ unauthenticated = await client.post(path, json=body)+ assert unauthenticated.status == 401+ assert (await unauthenticated.json())["error"]["code"] == "gateway_auth_failed"++ response = await client.post(path, json=body, headers=_AUTH_HEADERS)+ assert response.status == 200, await response.text()+ result = await response.json()+ assert result["run_id"] == unknown["request_id"]+ assert result["admission_id"] == unknown["admission_id"]+ assert result["status"] == "terminal" and result["outcome"] == "interrupted"++ await owner.sessions["api-session"].task+ assert executed == ["FOLLOWER"]+ statuses = {+ row["admission_id"]: (row["status"], row["outcome"])+ for row in list_session_admissions(owner.db, session_id="api-session", pending_only=False)+ }+ assert statuses[unknown["admission_id"]] == ("terminal", "interrupted")+ assert statuses[follower["admission_id"]] == ("terminal", "completed")++ again = await client.post(path, json=body, headers=_AUTH_HEADERS)+ assert again.status == 409+ assert (await again.json())["error"]["code"] == "stale_generation"+ assert executed == ["FOLLOWER"]+ finally:+ await _close_fixture(client, adapters, store, tasks)+++async def test_http_resolve_unknown_refuses_stale_or_foreign_admission(+ tmp_path, monkeypatch+):+ client, adapters, store, owner, unknown, follower, executed, tasks = (+ await _restarted_api_runs(tmp_path, monkeypatch)+ )+ try:+ run_path = "/v1/runs/" + unknown["request_id"] + "/resolve-unknown"+ stop = await client.post(+ "/v1/runs/" + unknown["request_id"] + "/stop",+ headers=_AUTH_HEADERS,+ )+ assert stop.status == 409+ assert (await stop.json())["error"]["code"] == "unknown_execution"+ attempts = (+ ({+ "admission_id": unknown["admission_id"],+ "execution_generation": unknown["generation"] + 1,+ }, "stale_generation"),+ ({+ "admission_id": follower["admission_id"],+ "execution_generation": unknown["generation"],+ }, "not_found"),+ ({+ "admission_id": unknown["admission_id"],+ "execution_generation": False,+ }, "stale_generation"),+ ({+ "admission_id": unknown["admission_id"],+ "execution_generation": unknown["generation"],+ "extra": True,+ }, "invalid_params"),+ ([unknown["admission_id"], unknown["generation"]], "invalid_params"),+ )+ for body, code in attempts:+ response = await client.post(run_path, json=body, headers=_AUTH_HEADERS)+ assert response.status == 409+ assert (await response.json())["error"]["code"] == code++ await asyncio.sleep(0.05)+ rows = {+ row["admission_id"]: row["status"]+ for row in list_session_admissions(owner.db, session_id="api-session")+ }+ assert rows == {+ unknown["admission_id"]: "unknown",+ follower["admission_id"]: "queued",+ }+ assert executed == []+ finally:+ await _close_fixture(client, adapters, store, tasks)+++async def test_fresh_adapter_recovers_non_idempotent_owner_but_refuses_other_credential(+ tmp_path, monkeypatch+):+ client, adapters, store, owner, unknown, follower, executed, tasks = (+ await _restarted_api_runs(tmp_path, monkeypatch, idempotent=False)+ )+ try:+ path = "/v1/runs/" + unknown["request_id"] + "/resolve-unknown"+ body = {+ "admission_id": unknown["admission_id"],+ "execution_generation": unknown["generation"],+ }++ foreign = await client.post(path, json=body, headers=_OTHER_AUTH_HEADERS)+ assert foreign.status == 404+ assert (await foreign.json())["error"]["code"] == "run_not_found"++ response = await client.post(path, json=body, headers=_AUTH_HEADERS)+ assert response.status == 200, await response.text()+ assert (await response.json())["outcome"] == "interrupted"+ finally:+ await _close_fixture(client, adapters, store, tasks)+++async def test_run_owner_rolls_back_with_failed_canonical_admission(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ store = SessionStore(tmp_path / "sessions", GatewayConfig())+ db = SessionDB(tmp_path / "state.db")+ runner = SimpleNamespace(+ _session_db=db, session_store=store, _draining=False,+ _handle_message=lambda event: None,+ )+ authority = await initialize_session_authority(+ runner, profile_id="default", instance_id="api-owner-atomic"+ )+ authority._schedule = lambda ref: None+ adapter = _adapter(runner, db)+ runner._adapter_for_source = lambda source: adapter+ from gateway.platforms import api_server_runs+ monkeypatch.setattr(+ api_server_runs.uuid, "uuid4", lambda: SimpleNamespace(hex="atomic_boundary")+ )++ def install_abort(conn):+ conn.execute(+ "CREATE TRIGGER abort_api_owner BEFORE INSERT ON session_admissions "+ "WHEN NEW.principal_id='api' BEGIN SELECT RAISE(ABORT, 'forced rollback'); END"+ )++ db._execute_write(install_abort)+ client = _runs_client(adapter)+ await client.start_server()+ fresh = None+ try:+ response = await client.post(+ "/v1/runs", json={"input": "must roll back", "session_id": "atomic"},+ headers=_AUTH_HEADERS,+ )+ assert response.status == 500+ with db._read_ctx() as conn:+ assert conn.execute(+ "SELECT COUNT(*) FROM session_admissions WHERE request_id='run_atomic_boundary'"+ ).fetchone()[0] == 0+ await client.close()+ fresh = _adapter(runner, db)+ runner._adapter_for_source = lambda source: fresh+ client = _runs_client(fresh)+ await client.start_server()+ refused = await client.get("/v1/runs/run_atomic_boundary", headers=_AUTH_HEADERS)+ assert refused.status == 404+ finally:+ await client.close()+ for item in (adapter, fresh):+ if item is not None:+ item._response_store.close()+ item._run_idempotency_store.close()+ db.close()+ store.close_all_db_handles()+++def test_unknown_resolution_uses_the_existing_room_stop_permission():+ from gateway.platforms.api_server_runs import _room_permission_for++ request = SimpleNamespace(path="/v1/runs/run-a/resolve-unknown", method="POST")+ assert _room_permission_for(request) == "stop"+++async def test_capability_advertised_only_with_canonical_authority():+ request = SimpleNamespace(headers={})+ for authority, expected in ((None, False), (object(), True)):+ adapter = APIServerAdapter(PlatformConfig(enabled=True))+ adapter.gateway_runner = SimpleNamespace(session_authority=authority)+ try:+ response = await adapter._handle_capabilities(request)+ body = __import__("json").loads(response.text)+ assert body["features"]["run_unknown_resolution"] is expected+ assert ("run_unknown_resolution" in body["endpoints"]) is expected+ finally:+ adapter._response_store.close()+ adapter._run_idempotency_store.close()diff --git a/website/docs/developer-guide/programmatic-integration.md b/website/docs/developer-guide/programmatic-integration.mdindex 050ae6ff4a9..f8e6fdd3d78 100644--- a/website/docs/developer-guide/programmatic-integration.md+++ b/website/docs/developer-guide/programmatic-integration.md@@ -112,6 +112,7 @@ GET /v1/runs/{id} Run statusGET /v1/runs/{id}/events SSE stream of lifecycle eventsPOST /v1/runs/{id}/approval Resolve a pending approvalPOST /v1/runs/{id}/steer Inject mid-run guidance at the next tool boundary+POST /v1/runs/{id}/resolve-unknown Acknowledge an exact restart-unknown admissionPOST /v1/runs/{id}/stop Interrupt the runGET /v1/capabilities Machine-readable feature flagsPOST /v1/browser-control/register Register a browser controller@@ -158,6 +159,27 @@ Use `/v1/models` for OpenAI-client compatibility. Use `/api/model/options` orA `200` (and the `run.steered` event) means the text was **queued**, not that the agent consumed it. If a steer lands after the agent's final response — with no later tool boundary to deliver it at — the undelivered text is returned as `pending_steer` on the terminal `run.completed` event and run status, so the client can replay it as the next user turn instead of losing it.+`POST /v1/runs/{id}/resolve-unknown` is a canonical-authority recovery+operation, not a generic status mutation. Send exactly the `admission_id` and+integer `execution_generation` projected by the run status. The server binds the+authenticated owner, selected profile, path run, API principal, target session,+admission, and generation before the authority performs its compare-and-set.+Resolution settles the lost head as interrupted and releases the next FIFO item;+it never requeues the head. Feature-detect+`features.run_unknown_resolution` because legacy execution mode does not+advertise this endpoint.++New canonical API admissions retain an opaque owner scope in the admission row,+so keyed and non-keyed runs can be authorized after an adapter restart for as+long as that canonical admission remains available. This does not change+non-keyed request semantics: identical submissions still create distinct runs.+Pre-upgrade non-keyed admissions contain no owner scope and remain deliberately+unresolvable after restart; there is no safe credential ownership to backfill.+Existing keyed records retain their replay-ledger recovery path. Explicit+session retirement removes the canonical payload and therefore ends this owner+recovery path. Replay reservation and canonical admission still use separate+databases, so this endpoint does not provide a global exactly-once guarantee.+---## Which one should I use?diff --git a/website/docs/user-guide/features/api-server.md b/website/docs/user-guide/features/api-server.mdindex 4478f5f1b7f..49c05fcc119 100644--- a/website/docs/user-guide/features/api-server.md+++ b/website/docs/user-guide/features/api-server.md@@ -546,6 +546,48 @@ still executing remains visible to status polling, approval, stop control, andconcurrency accounting until its executor work actually exits. A connected SSEsubscriber continues draining normally.+### POST /v1/runs/\{run_id\}/resolve-unknown++After an authority-owner restart, a turn that was already claimed has an+unknown execution outcome. Hermes pauses later work in that session rather than+risk replaying the lost head. Read the exact `admission_id` and+`execution_generation` from `GET /v1/runs/{run_id}`, then acknowledge that the+lost execution will not finish:++```json+{+ "admission_id": "adm_abc123",+ "execution_generation": 7+}+```++The request is authenticated and run-owner scoped like the other run controls;+hosted-room callers need the existing `stop` grant. A successful response is the+canonical terminal receipt (`outcome: "interrupted"`) plus `run_id`. It releases+the FIFO once and schedules the queued follower without replaying the unknown+head. Repeated resolution, a stale or non-integer generation, and a run that is+not currently unknown return `409 stale_generation`; an admission ID that does+not belong to the path run returns `409 not_found`. The body must contain exactly+those two fields, or the server returns `409 invalid_params`.++This recovery control is advertised as `features.run_unknown_resolution` and as+the `run_unknown_resolution` endpoint only when the canonical session authority+is active. Legacy API execution mode does not advertise it. Ordinary+`POST /v1/runs/{run_id}/stop` deliberately remains separate and returns+`409 unknown_execution` for an unknown admission.++For admissions created by this version, the opaque run-owner scope is stored+atomically with the canonical admission and retained for that admission's+control/status lifetime, including terminal state. It is private server state,+not a bearer credential, model input, or API response field. Non-keyed requests+remain non-idempotent, so matching request bodies still create separate runs.+Older non-keyed admissions have no persisted owner scope and continue to fail+closed after an adapter restart; they cannot be safely backfilled. Older keyed+runs continue to use the existing idempotency ledger. Explicit session+retirement removes the canonical admission payload and its recoverable owner.+The replay ledger and canonical admission are separate database transactions;+this recovery control does not promise global exactly-once execution.+### POST /v1/runs/\{run_id\}/stopInterrupt 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.