Skip to content

The agent that grows with you

feat: run bound API turns on the shared cached agent

Tekniumdea4f0c568e6
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index 1cbe0f215dc..102d21d4bcb 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -3637,6 +3637,17 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
``agent_ref[0]`` receives the agent so SSE writers can interrupt it; ``active_run_id``
registers it in ``_active_run_agents``. Under a confirmed model lock the actual
provider/model must match or the turn fails; ``runtime`` metadata is attached."""
+ if getattr(self.gateway_runner, "session_authority", None) is not None:
+ from gateway.session_api_turn import run_api_turn
+ return await run_api_turn(self, user_message=user_message, conversation_history=conversation_history,
+ ephemeral_system_prompt=ephemeral_system_prompt, session_id=session_id,
+ stream_delta_callback=stream_delta_callback, tool_progress_callback=tool_progress_callback,
+ tool_start_callback=tool_start_callback, tool_complete_callback=tool_complete_callback,
+ agent_ref=agent_ref, active_run_id=active_run_id, gateway_session_key=gateway_session_key,
+ requested_model=requested_model, requested_provider=requested_provider, model_options=model_options,
+ route=route, session_model=session_model, requested_runtime=requested_runtime,
+ route_source=route_source, confirmed_runtime_lock=confirmed_runtime_lock,
+ bind_declared_conversation=bind_declared_conversation)
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/run_turn_runner.py b/gateway/run_turn_runner.py
index 810e8c85c48..845db8e43ac 100644
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@ -462,6 +462,12 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
_select_cached_agent_history,
)
ctx = self._ctx
+ from gateway.session_api_turn import api_execution
+ api = api_execution.get()
+ if api is not None and api['history'] is not None:
+ from gateway.run import _collect_history_media_paths
+ history = api['history']
+ return history, None, _collect_history_media_paths(history)
# Transcript rows ({role, content, timestamp}) lose timestamps; interrupt-path agent messages
# (tool_calls/tool_call_id/reasoning) pass through intact so the API sees valid assistant→tool
# sequences. Telegram observed=True rows are withheld from replayable history and attached to
@@ -607,7 +613,17 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
# turn so a restart-interrupted turn is recorded WITH its id for drain-window dedup.
if ctx.inbound_message_id is not None:
kwargs["persist_user_platform_id"] = str(ctx.inbound_message_id)
- return agent.run_conversation(api_message, **kwargs)
+ from gateway.session_results import execution_result
+ captured = execution_result.get()
+ before = (getattr(agent, 'session_prompt_tokens', 0) or 0,
+ getattr(agent, 'session_completion_tokens', 0) or 0)
+ result = agent.run_conversation(api_message, **kwargs)
+ if captured is not None:
+ incoming = max(0, (getattr(agent, 'session_prompt_tokens', 0) or 0) - before[0])
+ outgoing = max(0, (getattr(agent, 'session_completion_tokens', 0) or 0) - before[1])
+ captured['usage'] = {'input_tokens': incoming, 'output_tokens': outgoing,
+ 'total_tokens': incoming + outgoing}
+ return result
finally:
unregister_gateway_notify(session_key)
# Cancel pending clarify entries so blocked agent threads don't hang past the end of the
@@ -726,6 +742,10 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
"""Platform context + YAML channel_prompts hint + channel_overrides system_prompt (or global
ephemeral) + the gateway ephemeral prompt."""
ctx = self._ctx
+ from gateway.session_api_turn import api_execution
+ api = api_execution.get()
+ if api is not None:
+ return api['settings'].get('ephemeral_system_prompt') or ''
combined = ctx.context_prompt or ""
for extra in (
(ctx.channel_prompt or "").strip(),
@@ -771,7 +791,12 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
from gateway.session_policy import policy_for_source, policy_scope
with policy_scope(policy_for_source(self._runner, self._ctx.source),
authority=getattr(self._runner, "session_authority", None)):
- return self._run_sync_scoped()
+ result = self._run_sync_scoped()
+ from gateway.session_results import execution_result
+ captured = execution_result.get()
+ if captured is not None:
+ captured['result'] = result
+ return result
def _run_sync_scoped(self):
"""Executor-thread body of the turn; returns the gateway result dict.
@@ -803,6 +828,8 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
model, runtime_kwargs = runner._resolve_session_agent_runtime(
source=ctx.source, session_key=ctx.session_key, user_config=ctx.user_config,
)
+ from gateway.session_api_turn import prepare_api_runtime
+ model, runtime_kwargs = prepare_api_runtime(model, runtime_kwargs)
if policy and policy.model:
model = policy.model
logger.debug(
diff --git a/gateway/session_api.py b/gateway/session_api.py
index 5389fe4cd66..f63d1411fcd 100644
--- a/gateway/session_api.py
+++ b/gateway/session_api.py
@@ -16,6 +16,8 @@ def bind_api_session(authority, session_id):
if not isinstance(session_id, str) or not session_id or _is_path_unsafe(session_id):
raise RuntimeStoreError('invalid_params')
if session_id in authority.sessions:
+ if authority.sessions[session_id].source.platform != Platform.API_SERVER:
+ raise RuntimeStoreError('permission_denied')
return SessionRef(authority.profile_id, session_id)
source = SessionSource(platform=Platform.API_SERVER, chat_id=session_id,
user_id='api', chat_type='dm')
diff --git a/gateway/session_api_turn.py b/gateway/session_api_turn.py
new file mode 100644
index 00000000000..0120b4b648b
--- /dev/null
+++ b/gateway/session_api_turn.py
@@ -0,0 +1,106 @@
+"""Trusted API preparation and observation of the canonical durable FIFO."""
+import asyncio
+from contextvars import ContextVar
+import json
+import uuid
+
+from gateway.config import Platform
+from gateway.session_api import bind_api_session, restore_api_session
+from gateway.session_results import admission_result
+from hermes_state_runtime import RuntimeStoreError, admit_session_input, _epoch, _json
+
+api_execution: ContextVar[dict | None] = ContextVar('api_execution', default=None)
+_SETTINGS_PREFIX = 'gateway.api.settings.v1.'
+_SETTING_KEYS = ('ephemeral_system_prompt', 'requested_model', 'requested_provider',
+ 'model_options', 'route', 'session_model', 'confirmed_runtime_lock',
+ 'requested_runtime', 'route_source')
+
+
+def api_settings(authority, ref):
+ with authority.db._read_ctx() as conn:
+ saved = conn.execute('SELECT value FROM state_meta WHERE key=?',
+ (_SETTINGS_PREFIX + ref.session_id,)).fetchone()
+ return json.loads(saved[0]) if saved else {}
+
+
+def check_api_turn(authority, ref, payload):
+ live = authority.sessions[ref.session_id]
+ if live.source.platform == Platform.API_SERVER:
+ restore_api_session(authority, ref.session_id)
+ adapter = authority.runner._adapter_for_source(live.source)
+ if adapter is None or getattr(adapter, 'gateway_runner', None) is not authority.runner:
+ raise RuntimeStoreError('runtime_draining')
+ if 'api_turn_v1' in payload:
+ data = payload['api_turn_v1']
+ if set(data) != {'history', 'settings'} or not isinstance(data['history'], list):
+ raise RuntimeStoreError('invalid_params')
+ if set(data['settings']) - set(_SETTING_KEYS):
+ raise RuntimeStoreError('invalid_params')
+ return adapter
+
+
+async def run_api_turn(adapter, **kwargs):
+ authority = adapter.gateway_runner.session_authority
+ if adapter._ensure_session_db() is not authority.db:
+ raise RuntimeStoreError('profile_mismatch')
+ sid = kwargs.get('session_id') or uuid.uuid4().hex
+ ref = bind_api_session(authority, sid)
+ settings = {key: kwargs.get(key) for key in _SETTING_KEYS}
+ # Route credentials remain in the server's configuration, never admission JSON.
+ route = settings.get('route')
+ if route and route.get('api_key'):
+ alias = settings.get('requested_model')
+ configured = adapter._model_routes.get(alias)
+ if configured != route:
+ raise RuntimeStoreError('permission_denied')
+ 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': kwargs['conversation_history'], 'settings': settings}}))
+ check_api_turn(authority, ref, payload)
+ row = admit_session_input(authority.db, epoch=authority.epoch, principal_id='api',
+ session_id=sid, request_id=kwargs.get('active_run_id') or uuid.uuid4().hex,
+ payload=payload)
+ if row['status'] == 'terminal':
+ result = admission_result(authority.db, row['admission_id'])
+ if result is None:
+ raise RuntimeStoreError('unknown_execution')
+ return result['result'], result['usage']
+ waiter = authority.waiters.setdefault(row['admission_id'], asyncio.get_running_loop().create_future())
+ authority._publish_pending(ref)
+ authority._schedule(ref)
+ await asyncio.shield(waiter)
+ saved = admission_result(authority.db, row['admission_id'])
+ if saved is None:
+ raise RuntimeStoreError('unknown_execution')
+ return saved['result'], saved['usage']
+
+
+def prepare_api_execution(authority, ref, payload):
+ adapter = check_api_turn(authority, ref, payload)
+ data = payload.get('api_turn_v1')
+ settings = data['settings'] if data else api_settings(authority, ref)
+ if data:
+ def write(conn):
+ _epoch(conn, authority.epoch)
+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?) '
+ 'ON CONFLICT(key) DO UPDATE SET value=excluded.value',
+ (_SETTINGS_PREFIX + ref.session_id, _json(settings)))
+ authority.db._execute_write(write)
+ return {'adapter': adapter, 'settings': settings, 'history': data['history'] if data else None}
+
+
+def prepare_api_runtime(model, runtime_kwargs):
+ current = api_execution.get()
+ if current is None:
+ return model, runtime_kwargs
+ options = current['settings']
+ route = options.get('route')
+ configured = current['adapter']._model_routes.get(options.get('requested_model'))
+ if configured and {k: v for k, v in configured.items() if k != 'api_key'} == route:
+ route = configured
+ model, _, _, _ = current['adapter']._select_agent_runtime(runtime_kwargs, model,
+ requested_model=options.get('requested_model'), requested_provider=options.get('requested_provider'),
+ route=route, session_model=options.get('session_model'),
+ confirmed_runtime_lock=bool(options.get('confirmed_runtime_lock')),
+ gateway_session_key=None, session_id=None)
+ return model, runtime_kwargs
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 4adb87ecb3a..e1d283ebe22 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -323,6 +323,9 @@ class SessionAuthority:
current = get_session_admission(self.db, admission_id=first['admission_id'])
if current is None or current['status'] != 'queued':
continue
+ if first is not None and live.source.platform == Platform.API_SERVER:
+ from gateway.session_api_turn import check_api_turn
+ check_api_turn(self, ref, first['payload'])
self._require_admission_open()
row = claim_session_input(self.db, epoch=self.epoch, session_id=ref.session_id)
except RuntimeStoreError as exc:
diff --git a/gateway/session_ingress.py b/gateway/session_ingress.py
index 24c596b64b1..4c549f7f7ef 100644
--- a/gateway/session_ingress.py
+++ b/gateway/session_ingress.py
@@ -39,17 +39,32 @@ async def execute_admission(authority, ref, row):
from gateway.session_ingress_context import restore_provenance
home = restore_provenance(authority.runner, event.source, provenance)
scope = _profile_runtime_scope(home)
+ from gateway.config import Platform
+ from gateway.session_api_turn import api_execution, prepare_api_execution
+ from gateway.session_results import execution_result, retain_result
+ is_api = live.source.platform == Platform.API_SERVER
+ prepared = prepare_api_execution(authority, ref, row['payload']) if is_api else None
+ if is_api:
+ event.internal = True # trust comes from the private binding and preclaim, never client JSON
+ api_token = api_execution.set(prepared)
+ captured = {}
+ result_token = execution_result.set(captured)
token = executing_admission.set(True)
try:
with scope:
response = await authority.runner._handle_message(event)
- if not native and response:
+ result = captured.get('result') or {'final_response': response or '', 'messages': []}
+ retain_result(authority.db, epoch=authority.epoch, row=row,
+ result={'result': result, 'usage': captured.get('usage', {})})
+ if not native and not is_api and response:
adapter = authority.runner._adapter_for_source(event.source)
if adapter is not None:
await deliver_response(adapter, event, live.route, response)
return response
finally:
executing_admission.reset(token)
+ execution_result.reset(result_token)
+ api_execution.reset(api_token)
async def deliver_response(adapter, event, session_key, response):
diff --git a/gateway/session_results.py b/gateway/session_results.py
index 0964b0ebf81..940d5d3b668 100644
--- a/gateway/session_results.py
+++ b/gateway/session_results.py
@@ -4,6 +4,9 @@ A crash between retention and settlement remains unknown, not a retryable result
The public stream keeps its text projection, not tool arguments or raw history.
"""
import json
+from contextvars import ContextVar
+
+execution_result: ContextVar[dict | None] = ContextVar("execution_result", default=None)
from hermes_state_runtime import RuntimeStoreError, _admission, _epoch, _json, _session
diff --git a/tests/gateway/fixtures/api_authority_peer.py b/tests/gateway/fixtures/api_authority_peer.py
new file mode 100644
index 00000000000..d4fc5ca7b9a
--- /dev/null
+++ b/tests/gateway/fixtures/api_authority_peer.py
@@ -0,0 +1,126 @@
+"""Real HTTP/WS API execution probe with a loopback inference peer."""
+import asyncio
+import json
+import os
+from pathlib import Path
+import sys
+import threading
+import traceback
+from http.server import ThreadingHTTPServer
+
+from shared_authority_peer import ModelPeer
+
+
+async def probe(peer):
+ import aiohttp
+ import websockets
+ from gateway.config import Platform, PlatformConfig
+ from gateway.platforms.api_server import APIServerAdapter
+ from gateway.run import GatewayRunner
+ from gateway.run_api import start_gateway_api, stop_gateway_api
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_contract import SessionRef
+ from hermes_cli import web_server
+ from hermes_state_runtime import list_session_admissions
+
+ runner = GatewayRunner()
+ await initialize_session_authority(runner, profile_id='default', instance_id='api-peer')
+ adapter = APIServerAdapter(PlatformConfig(enabled=True, extra={'key': 'api-probe-owned-secret', 'port': 0}))
+ adapter.gateway_runner = runner
+ adapter.set_message_handler(runner._handle_message)
+ runner.adapters[Platform.API_SERVER] = adapter
+ assert await adapter.connect()
+ api_port = adapter._site._server.sockets[0].getsockname()[1]
+ handle = await start_gateway_api(runner)
+ frames = []
+ try:
+ async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=35)) as client:
+ url = f'http://127.0.0.1:{api_port}/v1/chat/completions'
+ headers = {'Authorization': 'Bearer api-probe-owned-secret', 'X-Hermes-Session-Id': 'api-shared'}
+ body = {'messages': [{'role': 'system', 'content': 'API_STABLE_SYSTEM'}, {'role': 'user', 'content': 'MESSAGING_WARM'}]}
+ async with client.post(url, json=body) as denied:
+ assert denied.status == 401
+ async with client.post(url, json=body, headers=headers) as response:
+ data = await response.json()
+ assert response.status == 200, data
+ authority = runner.session_authority
+ ref = SessionRef('default', 'api-shared')
+ assert ref.session_id in authority.sessions, 'API bypassed canonical authority'
+ agent = authority.agent(ref)
+ assert agent is not None
+ port = handle.socket.getsockname()[1]
+ async with websockets.connect(f'ws://127.0.0.1:{port}/api/ws?token={web_server._SESSION_TOKEN}') as ws:
+ async def until(predicate):
+ async with asyncio.timeout(30):
+ while True:
+ frame = json.loads(await ws.recv())
+ frames.append(frame)
+ if predicate(frame):
+ return frame
+ await until(lambda f: f.get('params', {}).get('type') == 'gateway.ready')
+ await ws.send(json.dumps({'jsonrpc': '2.0', 'id': 1, 'method': 'session.resume', 'params': {'session_id': ref.session_id}}))
+ resumed = await until(lambda f: f.get('id') == 1)
+ assert 'result' in resumed, resumed
+ await ws.send(json.dumps({'jsonrpc': '2.0', 'id': 2, 'method': 'prompt.submit', 'params': {'session_id': ref.session_id, 'input_id': 'ws-shared', 'text': 'WS_SHARED'}}))
+ submitted = await until(lambda f: f.get('id') == 2)
+ assert 'result' in submitted, submitted
+ final = await until(lambda f: f.get('params', {}).get('type') == 'message.complete')
+ assert 'LOCAL_ACK_WS_SHARED' in json.dumps(final), final
+ assert authority.agent(ref) is agent, 'WS replaced the selected API agent'
+ rows = list_session_admissions(authority.db, session_id=ref.session_id, pending_only=False)
+ assert len(rows) == 2 and all(r['status'] == 'terminal' for r in rows), rows
+ systems = [[m for m in req['messages'] if m['role'] in ('system', 'developer')] for req in peer.requests]
+ assert systems[0] == systems[1] and 'API_STABLE_SYSTEM' in json.dumps(systems[0]), systems
+ if os.environ.get('API_ADVANCED'):
+ await ws.send(json.dumps({'jsonrpc': '2.0', 'id': 3, 'method': 'prompt.submit', 'params': {'session_id': ref.session_id, 'input_id': 'ws-block', 'text': 'BLOCK_FIFO'}}))
+ await until(lambda f: f.get('id') == 3)
+ assert await asyncio.to_thread(peer.blocked.wait, 10)
+ retry_headers = {**headers, 'Idempotency-Key': 'durable-api-retry'}
+ follow = {'messages': [{'role': 'system', 'content': 'API_STABLE_SYSTEM'}, {'role': 'user', 'content': 'FIFO_SECOND'}]}
+ async def request_follow(stream=False):
+ async with client.post(url, json={**follow, 'stream': stream}, headers=retry_headers) as response:
+ text = await response.text()
+ assert response.status == 200, text
+ return text
+ pending = asyncio.create_task(request_follow())
+ async with asyncio.timeout(10):
+ while not any(r['payload'].get('text') == 'FIFO_SECOND' for r in list_session_admissions(authority.db, session_id=ref.session_id)):
+ await asyncio.sleep(.01)
+ peer.release.set()
+ first_reply = json.loads(await pending)
+ assert first_reply['choices'][0]['message']['content']
+ count = len(peer.requests)
+ await request_follow()
+ streamed = await request_follow(stream=True)
+ assert 'data: [DONE]' in streamed and 'LOCAL_ACK' in streamed, streamed
+ assert len(peer.requests) == count, 'retry reexecuted canonical admission'
+ assert 'BLOCK_FIFO' in json.dumps(peer.requests[-1]['messages']), 'queued API used stale admission-time history'
+ assert authority.agent(ref) is agent
+ Path(os.environ['HERMES_HOME'], 'receipt.json').write_text(json.dumps({'same_agent': True, 'rows': rows, 'http': data, 'frames': frames}))
+ finally:
+ await stop_gateway_api(handle)
+ await adapter.disconnect()
+
+
+if __name__ == '__main__':
+ peer = ThreadingHTTPServer(('127.0.0.1', 0), ModelPeer)
+ peer.requests, peer.metadata_requests = [], []
+ peer.blocked, peer.release = threading.Event(), threading.Event()
+ threading.Thread(target=peer.serve_forever, daemon=True).start()
+ base = f'http://127.0.0.1:{peer.server_port}/v1'
+ os.environ.update(OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=base)
+ Path(os.environ['HERMES_HOME'], 'config.yaml').write_text(
+ f'model:\n default: local-wire-stub\n provider: custom\n base_url: {base}\n'
+ f'auxiliary:\n title_generation:\n enabled: false\nterminal:\n cwd: {os.environ["HERMES_HOME"]}\n')
+ code = 0
+ try:
+ asyncio.run(probe(peer))
+ except BaseException:
+ traceback.print_exc()
+ code = 1
+ finally:
+ peer.shutdown()
+ peer.server_close()
+ sys.stdout.flush()
+ sys.stderr.flush()
+ os._exit(code)
diff --git a/tests/gateway/test_api_authority_execution.py b/tests/gateway/test_api_authority_execution.py
new file mode 100644
index 00000000000..18c039dcdc5
--- /dev/null
+++ b/tests/gateway/test_api_authority_execution.py
@@ -0,0 +1,27 @@
+"""API and authenticated WS share the existing selected cached agent."""
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+
+def _probe(tmp_path, *, advanced=False):
+ repo = Path(__file__).resolve().parents[2]
+ home, state = tmp_path / 'home', tmp_path / 'state'
+ home.mkdir()
+ state.mkdir()
+ env = {key: os.environ[key] for key in ('PATH', 'LANG', 'TZ', 'SYSTEMROOT') if key in os.environ}
+ env.update(HOME=str(home), USERPROFILE=str(home), HERMES_HOME=str(state), PYTHONPATH=str(repo))
+ if advanced:
+ env['API_ADVANCED'] = '1'
+ result = subprocess.run([sys.executable, str(Path(__file__).parent / 'fixtures' / 'api_authority_peer.py')],
+ cwd=repo, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=100)
+ assert result.returncode == 0, result.stdout + '\n' + result.stderr
+ receipt = json.loads((state / 'receipt.json').read_text())
+ assert receipt['same_agent'], receipt
+ print(json.dumps(receipt))
+
+
+def test_api_and_ws_use_one_turnrunner(tmp_path):
+ _probe(tmp_path)