Skip to content

The agent that grows with you

fix: resolve API prompts through canonical pending controls

Tekniumf35358a60f22
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index a36ceecc669..b8f11721119 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -3788,6 +3788,7 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
_handle_get_run = _run_route_delegate("_handle_get_run")
_handle_run_events = _run_route_delegate("_handle_run_events")
_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_stop_run = _run_route_delegate("_handle_stop_run")
@@ -3976,6 +3977,12 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
"""Not used — the HTTP request/response cycle handles delivery directly."""
return SendResult(success=False, error="API server uses HTTP request/response, not send()")
+ async def send_clarify(self, chat_id: str, question: str, choices: Optional[list],
+ clarify_id: str, session_key: str,
+ metadata: Optional[Dict[str, Any]] = None) -> SendResult:
+ from gateway.platforms.api_server_authority_runs import send_clarify
+ return await send_clarify(self, chat_id=chat_id, clarify_id=clarify_id)
+
async def get_chat_info(self, chat_id: str) -> Dict[str, Any]:
"""Return basic info about the API server."""
return {"name": "API Server", "type": "api", "host": self._host, "port": self._port}
diff --git a/gateway/platforms/api_server_authority_runs.py b/gateway/platforms/api_server_authority_runs.py
index 5ac3adbc429..2090c84b5e1 100644
--- a/gateway/platforms/api_server_authority_runs.py
+++ b/gateway/platforms/api_server_authority_runs.py
@@ -25,11 +25,53 @@ def run_projection(adapter, run_id):
result = saved.get('result', {}) if saved else {}
if row['status'] == 'terminal' and result.get('failed'):
status = 'failed'
- return {'run_id': run_id, 'status': status, 'session_id': row['target_session_id'],
+ pending = []
+ live = authority.sessions.get(row['target_session_id'])
+ if live is not None and row['status'] == 'started':
+ pending = list(live.controls.snapshot(row['target_session_id'], row['generation']))
+ return {'pending_controls': pending, 'run_id': run_id, 'status': status, 'session_id': row['target_session_id'],
'admission_id': row['admission_id'], 'execution_generation': row['generation'],
'output': result.get('final_response', ''), 'usage': saved.get('usage', {}) if saved else {}}
+async def send_clarify(adapter, *, chat_id, **kwargs):
+ from gateway.platforms.base import SendResult
+ authority = getattr(adapter.gateway_runner, 'session_authority', None)
+ if authority is None or chat_id not in authority.sessions:
+ return SendResult(success=False, error='No canonical API session')
+ handle = authority._handle(SessionRef(authority.profile_id, chat_id))
+ if handle.execution_state != 'running':
+ return SendResult(success=False, error='No active API execution')
+ # TurnRunner registers the shared prompt after this ACK; HTTP polling and WS
+ # subscribers consume that projection rather than an adapter-local message.
+ return SendResult(success=True, message_id=kwargs['clarify_id'])
+
+
+async def respond_run(adapter, run_id, body, *, kind):
+ import uuid
+ owned = run_admission(adapter, run_id)
+ if owned is None:
+ raise RuntimeStoreError('not_found')
+ authority, row = owned
+ generation = body.get('execution_generation')
+ prompt_id = body.get('request_id')
+ field = 'choice' if kind == 'approval' else 'answer'
+ if set(body) != {'request_id', 'execution_generation', field}:
+ raise RuntimeStoreError('invalid_params')
+ if row['status'] != 'started' or type(generation) is not int or generation != row['generation']:
+ raise RuntimeStoreError('stale_generation')
+ ref = SessionRef(authority.profile_id, row['target_session_id'])
+ actor = Principal('api', authority.profile_id,
+ frozenset({'session:read', 'session:approve', 'session:respond'}), 'api-control:' + uuid.uuid4().hex)
+ snapshot = await authority.attach(actor, ref)
+ try:
+ if not any(p['prompt_id'] == prompt_id and p['kind'] == kind for p in snapshot.prompts):
+ raise RuntimeStoreError('approval_not_pending')
+ return await authority.respond(actor, ref, generation, prompt_id, {field: body[field]}, kind=kind)
+ finally:
+ await authority.detach(actor, snapshot.subscription_id)
+
+
async def stop_run(adapter, run_id):
owned = run_admission(adapter, run_id)
if owned is None:
diff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.py
index 3499788e917..5035c7806bd 100644
--- a/gateway/platforms/api_server_runs.py
+++ b/gateway/platforms/api_server_runs.py
@@ -101,6 +101,7 @@ def _http_routes(self) -> list[tuple[str, str, Any]]:
("POST", "/v1/runs", self._handle_runs), ("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),
+ ("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}/stop", self._handle_stop_run)]
@@ -740,6 +741,10 @@ async def _handle_run_approval(self, request: "web.Request", *, _api_server) ->
body = await request.json()
except Exception:
return _json_error(_openai_error, "Invalid JSON", status=400)
+ if getattr(self.gateway_runner, 'session_authority', None) is not None:
+ if self._room_grant_token(request) and body.get('choice') not in {'once', 'deny'}:
+ return _json_error(_openai_error, 'Room approvals require once or deny', status=400)
+ return await _respond_authority_run(self, run_id, body, kind='approval', _api_server=_api_server)
raw_choice = str(body.get("choice", "")).strip().lower()
choice = _APPROVAL_CHOICE_ALIASES.get(raw_choice, raw_choice)
room_scoped = bool(self._room_grant_token(request))
@@ -780,6 +785,27 @@ async def _handle_run_approval(self, request: "web.Request", *, _api_server) ->
"resolved": resolved})
+async def _respond_authority_run(self, run_id, body, *, kind, _api_server):
+ from gateway.platforms.api_server_authority_runs import respond_run
+ from hermes_state_runtime import RuntimeStoreError
+ try:
+ result = await respond_run(self, run_id, body, kind=kind)
+ 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 _handle_run_clarify(self, request, *, _api_server):
+ run_id, _, _, _, err = _load_owned_run(
+ self, request, _api_server=_api_server, permission=None, active_fallback=False)
+ if err is not None:
+ return err
+ body, err = await self._read_json_body(request)
+ if err is not None:
+ return err
+ return await _respond_authority_run(self, run_id, body, kind='clarify', _api_server=_api_server)
+
+
async def _handle_steer_run(self, request: "web.Request", *, _api_server) -> "web.Response":
"""POST /v1/runs/{run_id}/steer — inject guidance into a running agent."""
_openai_error = _api_server._openai_error
diff --git a/tests/gateway/test_api_pending_daemon.py b/tests/gateway/test_api_pending_daemon.py
new file mode 100644
index 00000000000..a0fc376d41f
--- /dev/null
+++ b/tests/gateway/test_api_pending_daemon.py
@@ -0,0 +1,125 @@
+"""API controls and WS views resolve the same real blocking tool waiter."""
+import asyncio
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+import json
+import os
+from pathlib import Path
+import socket
+import threading
+
+import aiohttp
+
+from tests.gateway.fixtures.local_recovery_probe import daemon, websocket, rpc
+
+
+class PromptPeer(BaseHTTPRequestHandler):
+ def log_message(self, *args):
+ pass
+
+ def do_POST(self):
+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))
+ messages = body.get('messages', [])
+ if messages:
+ self.server.requests.append(body)
+ last = messages[-1] if messages else {}
+ text = json.dumps(last)
+ message = {'role': 'assistant', 'content': 'CONTROL_DONE'}
+ if last.get('role') != 'tool' and ('ASK_APPROVAL' in text or 'ASK_CLARIFY' in text):
+ approval = 'ASK_APPROVAL' in text
+ name = 'terminal' if approval else 'clarify'
+ args = {'command': 'rm -rf ' + str(self.server.target)} if approval else {
+ 'question': 'Choose the answer', 'choices': ['BLUE', 'GREEN']}
+ message = {'role': 'assistant', 'content': None, 'tool_calls': [{
+ 'id': 'call_control', 'type': 'function', 'function': {'name': name, 'arguments': json.dumps(args)}}]}
+ finish = 'tool_calls' if 'tool_calls' in message else 'stop'
+ self.send_response(200)
+ self.send_header('Content-Type', 'text/event-stream' if body.get('stream') else 'application/json')
+ self.end_headers()
+ if body.get('stream'):
+ delta = dict(message)
+ if 'tool_calls' in delta:
+ delta['tool_calls'][0]['index'] = 0
+ data = {'id': 'control', 'choices': [{'index': 0, 'delta': delta, 'finish_reason': finish}]}
+ self.wfile.write(('data: ' + json.dumps(data) + '\n\ndata: [DONE]\n\n').encode())
+ else:
+ self.wfile.write(json.dumps({'id': 'control', 'choices': [{'index': 0, 'message': message, 'finish_reason': finish}]}).encode())
+
+
+def test_api_and_ws_pending_controls_share_identity(tmp_path):
+ root = Path(__file__).resolve().parents[2]
+ home, user = tmp_path / 'state', tmp_path / 'user'
+ home.mkdir(mode=0o700); user.mkdir()
+ peer = ThreadingHTTPServer(('127.0.0.1', 0), PromptPeer)
+ peer.requests = []
+ peer.target = home / 'owned-removal-target'
+ peer.target.mkdir()
+ (peer.target / 'owned.txt').write_text('owned')
+ threading.Thread(target=peer.serve_forever, daemon=True).start()
+ with socket.socket() as sock:
+ sock.bind(('127.0.0.1', 0)); port = sock.getsockname()[1]
+ base = f'http://127.0.0.1:{peer.server_port}/v1'
+ cfg = {'model': {'provider': 'custom', 'default': 'local-wire-stub', 'base_url': base},
+ 'gateway': {'platforms': {'api_server': {'enabled': True, 'port': port, 'host': '127.0.0.1'}}, 'multiplex_profiles': False},
+ 'auxiliary': {'title_generation': {'enabled': False}}, 'terminal': {'cwd': str(home)},
+ 'platform_toolsets': {'api_server': ['terminal', 'clarify']}, 'approvals': {'mode': 'manual'}}
+ (home / 'config.yaml').write_text(json.dumps(cfg))
+ env = {k: os.environ[k] for k in ('PATH', 'LANG', 'TZ') if k in os.environ}
+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),
+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=base, API_SERVER_KEY='ordinary-daemon-owned-secret',
+ API_SERVER_ENABLED='true', API_SERVER_PORT=str(port), PYTHONUNBUFFERED='1')
+
+ async def exercise(desc):
+ headers = {'Authorization': 'Bearer ordinary-daemon-owned-secret'}
+ async with aiohttp.ClientSession(headers=headers, timeout=aiohttp.ClientTimeout(total=30)) as client:
+ url = f'http://127.0.0.1:{port}/v1/runs'
+ async def post(path, body):
+ async with client.post(url + path, json=body) as response:
+ return response.status, await response.json()
+ for kind, text in [('approval', 'ASK_APPROVAL'), ('clarify', 'ASK_CLARIFY')]:
+ status, accepted = await post('', {'input': text, 'session_id': 'api-controls'})
+ assert status == 202, accepted
+ run = accepted['run_id']
+ async with websocket(home, desc) as ws:
+ prompt = None
+ async with asyncio.timeout(15):
+ while not prompt:
+ resumed = await rpc(ws, 'session.resume', session_id='api-controls')
+ assert 'result' in resumed, resumed
+ prompt = next((p for p in resumed['result'].get('prompts', []) if p['kind'] == kind), None)
+ if not prompt:
+ await asyncio.sleep(.05)
+ async with client.get(url + '/' + run) as response:
+ projected = await response.json()
+ assert projected['pending_controls'] == [prompt], projected
+ body = {'request_id': prompt['prompt_id'], 'execution_generation': prompt['execution_generation']}
+ body.update({'choice': 'once'} if kind == 'approval' else {'answer': 'BLUE'})
+ path = '/' + run + ('/approval' if kind == 'approval' else '/clarify')
+ wrong = {**body, 'execution_generation': body['execution_generation'] + 1}
+ assert (await post(path, wrong))[0] == 409
+ foreign = {**body, 'request_id': 'not-this-prompt'}
+ assert (await post(path, foreign))[0] == 409
+ if kind == 'approval':
+ assert peer.target.exists()
+ status, result = await post(path, body)
+ assert status == 200 and result['status'] == 'resolved', result
+ late = await rpc(ws, 'approval.respond' if kind == 'approval' else 'clarify.respond',
+ session_id='api-controls', execution_generation=body['execution_generation'],
+ prompt_id=body['request_id'], **({'choice': 'once'} if kind == 'approval' else {'answer': 'GREEN'}))
+ assert 'error' in late or late['result']['status'] == 'already_resolved', late
+ async with asyncio.timeout(20):
+ while True:
+ async with client.get(url + '/' + run) as response:
+ final = await response.json()
+ if final['status'] == 'completed':
+ break
+ await asyncio.sleep(.05)
+ assert (await post(path, body))[0] == 409
+ assert not peer.target.exists()
+ tools = [m for req in peer.requests for m in req.get('messages', []) if m['role'] == 'tool']
+ assert any('BLUE' in str(m['content']) for m in tools), tools
+ print(json.dumps({'ordinary_daemon': True, 'shared_pending_identity': True, 'requests': len(peer.requests)}))
+ try:
+ with daemon(root, home, env, barrier=False) as (_, desc):
+ asyncio.run(exercise(desc))
+ finally:
+ peer.shutdown(); peer.server_close()
diff --git a/website/docs/user-guide/features/api-server.md b/website/docs/user-guide/features/api-server.md
index 6b9acf6dcd6..085620d0718 100644
--- a/website/docs/user-guide/features/api-server.md
+++ b/website/docs/user-guide/features/api-server.md
@@ -502,6 +502,24 @@ running.
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.
+With the canonical gateway owner, `GET /v1/runs/{run_id}` exposes
+`pending_controls`, using the same `prompt_id` and `execution_generation` as
+attached WebSocket viewers. Respond with the exact current identity:
+
+```json
+{"request_id": "<prompt_id>", "execution_generation": 3, "choice": "once"}
+```
+
+Canonical controls do not accept identityless or bulk responses. Stale generations,
+foreign prompt IDs, and settled runs return HTTP 409. Existing run authentication
+and hosted-room approval restrictions still apply.
+
+### POST /v1/runs/\{run_id\}/clarify
+
+Answer a canonical clarification with `request_id`, `execution_generation`, and
+`answer` (a string). This authenticated endpoint and WebSocket `clarify.respond`
+resolve the same waiting tool; answering does not submit another inference turn.
+
## Jobs API (background scheduled work)
The server exposes a lightweight jobs CRUD surface for managing scheduled / background agent runs from a remote client. All endpoints are gated behind the same bearer auth.