Skip to content

The agent that grows with you

feat: apply local launch policy through real gateway turns

Teknium080c5da6f201
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index 7323d76a029..eff3f334446 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -756,9 +756,13 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gateway
)
from gateway.display_config import resolve_display_setting
from gateway.status_phrases import choose_status_phrase, resolve_status_phrase_catalog
- user_config = _load_gateway_config()
- platform_key = _platform_config_key(source.platform)
+ from gateway.session_policy import policy_for_source
+ policy = policy_for_source(self, source)
+ user_config = policy.config() if policy else _load_gateway_config()
+ platform_key = policy.platform if policy else _platform_config_key(source.platform)
enabled_toolsets, disabled_toolsets = self._resolve_turn_toolsets(user_config, source, platform_key)
+ if policy:
+ enabled_toolsets = list(policy.toolsets)
adapter = self._adapter_for_source(source)
# display.platforms.<platform>.<key> → display.<key> → built-in platform defaults.
_display_cfg = user_config.get("display", {})
@@ -1423,7 +1427,9 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gateway
_result_for_fb = turn_ctx.result_holder[0]
if _agent is None or not hasattr(_agent, 'model') or (_result_for_fb and _result_for_fb.get("failed")):
return
- _cfg_model = _resolve_gateway_model()
+ from gateway.session_policy import policy_for_source
+ policy = policy_for_source(self, turn_ctx.source)
+ _cfg_model = policy.model if policy and policy.model else _resolve_gateway_model()
# Normalize as AIAgent.__init__ does (vendor prefix stripped on native providers), else the
# cached agent is evicted every turn, destroying prompt caching.
with suppress(Exception):
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py
index f2cb77a8333..9b4777c8870 100644
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@ -765,6 +765,11 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
return final_response + "\n" + "\n".join(unique_tags)
def run_sync(self):
+ from gateway.session_policy import policy_for_source, policy_scope
+ with policy_scope(policy_for_source(self._runner, self._ctx.source)):
+ return self._run_sync_scoped()
+
+ def _run_sync_scoped(self):
"""Executor-thread body of the turn; returns the gateway result dict.
The turn message lives on the shared TurnContext (``ctx.message``) so ``_run_agent_inner`` sees
@@ -785,13 +790,17 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
# session via contextvars (set_current_session_key / session context), and only the TUI slash-worker
# *subprocess* exports HERMES_SESSION_KEY (from its own --session-key argv, a separate process) — so
# removing this in-process gateway write does not affect any of them.
- platform_key = "cli" if ctx.source.platform == Platform.LOCAL else ctx.source.platform.value
+ from gateway.session_policy import policy_for_source
+ policy = policy_for_source(runner, ctx.source)
+ platform_key = policy.platform if policy else ("cli" if ctx.source.platform == Platform.LOCAL else ctx.source.platform.value)
combined_ephemeral = self._combined_ephemeral_prompt()
max_iterations = _current_max_iterations()
try:
model, runtime_kwargs = runner._resolve_session_agent_runtime(
source=ctx.source, session_key=ctx.session_key, user_config=ctx.user_config,
)
+ if policy and policy.model:
+ model = policy.model
logger.debug(
"run_agent resolved: model=%s provider=%s session=%s",
model, runtime_kwargs.get("provider"), ctx.session_key or "",
diff --git a/gateway/session_local.py b/gateway/session_local.py
index aacf65bd3d6..abd976e5705 100644
--- a/gateway/session_local.py
+++ b/gateway/session_local.py
@@ -22,6 +22,7 @@ class LocalSessionAdapter(BasePlatformAdapter):
super().__init__(PlatformConfig(enabled=True), Platform.LOCAL)
self.authority = authority
self.sources = {}
+ self.policies = {}
def authorize_source(self, source):
saved = self.sources.get(source.chat_id)
@@ -82,11 +83,9 @@ def create_local_session(authority, actor, params):
raise RuntimeStoreError('profile_mismatch')
if 'session:create' not in actor.capabilities:
raise RuntimeStoreError('permission_denied')
- if set(params) - {'request_id', 'source'}:
- raise RuntimeStoreError('invalid_params')
- # LOCAL maps to CLI policy in the existing TurnRunner; do not label this GUI.
- if params.get('source', 'cli') != 'cli':
- raise RuntimeStoreError('invalid_params')
+ from gateway.session_policy import build_policy
+ from gateway.run import _load_gateway_config
+ policy = build_policy(params, _load_gateway_config())
request_id = params.get('request_id', uuid.uuid4().hex)
if not isinstance(request_id, str) or not request_id or len(request_id) > 256:
raise RuntimeStoreError('invalid_params')
@@ -99,10 +98,14 @@ def create_local_session(authority, actor, params):
# Stable route lets the persisted SessionStore recover a lost create ACK.
identity = json.dumps([authority.profile_id, actor.subject, request_id], separators=(',', ':'))
chat_id = 'local-' + hashlib.sha256(identity.encode()).hexdigest()
+ existing = adapter.policies.get(chat_id)
+ if existing is not None and existing.request_json != policy.request_json:
+ raise RuntimeStoreError('invalid_params')
source = SessionSource(platform=Platform.LOCAL, chat_id=chat_id,
user_id=actor.subject, chat_type='dm')
ref = authority.register(source)
source = authority.sessions[ref.session_id].source
+ adapter.policies.setdefault(chat_id, policy)
adapter.register_source(source)
return ref
@@ -110,7 +113,8 @@ def create_local_session(authority, actor, params):
def local_session_info(authority, ref):
live = authority.sessions[ref.session_id]
agent = authority.agent(ref)
- return {'source': 'cli' if isinstance(authority.runner._adapter_for_source(live.source),
- LocalSessionAdapter) else live.source.platform.value,
- 'model': getattr(agent, 'model', None), 'lazy': agent is None,
+ from gateway.session_policy import policy_for_source
+ policy = policy_for_source(authority.runner, live.source)
+ return {'source': policy.source if policy else live.source.platform.value,
+ 'model': getattr(agent, 'model', policy.model if policy else None), 'lazy': agent is None,
'profile_id': authority.profile_id}
diff --git a/tests/gateway/fixtures/session_policy_peer.py b/tests/gateway/fixtures/session_policy_peer.py
new file mode 100644
index 00000000000..ee8d55e5e70
--- /dev/null
+++ b/tests/gateway/fixtures/session_policy_peer.py
@@ -0,0 +1,145 @@
+"""Real concurrent source/model/tool/cwd launch proof; no external provider."""
+import asyncio
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+import json
+import os
+from pathlib import Path
+import sys
+import threading
+import traceback
+
+
+class Peer(BaseHTTPRequestHandler):
+ def log_message(self, *args):
+ pass
+
+ def do_POST(self):
+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))
+ self.server.requests.append(body)
+ messages = body.get('messages', [])
+ done = any(m.get('role') == 'tool' for m in messages)
+ message = {'role': 'assistant', 'content': 'POLICY_DONE'}
+ if not done:
+ message = {'role': 'assistant', 'content': None, 'tool_calls': [
+ {'id': 'owned', 'type': 'function', 'function': {'name': 'terminal',
+ 'arguments': json.dumps({'command': 'pwd; printf owned > policy-proof.txt'})}}]}
+ payload = json.dumps({'id': 'policy', 'object': 'chat.completion', 'model': body.get('model'),
+ 'choices': [{'index': 0, 'message': message, 'finish_reason': 'stop' if done else 'tool_calls'}],
+ 'usage': {'prompt_tokens': 10, 'completion_tokens': 10, 'total_tokens': 20}}).encode()
+ content_type = 'application/json'
+ if body.get('stream'):
+ delta = dict(message)
+ if delta.get('tool_calls'):
+ delta['tool_calls'][0]['index'] = 0
+ chunk = {'id': 'policy', 'object': 'chat.completion.chunk', 'model': body.get('model'),
+ 'choices': [{'index': 0, 'delta': delta, 'finish_reason': 'stop' if done else 'tool_calls'}]}
+ payload = ('data: ' + json.dumps(chunk) + '\n\ndata: [DONE]\n\n').encode()
+ content_type = 'text/event-stream'
+ self.send_response(200)
+ self.send_header('Content-Type', content_type)
+ self.send_header('Content-Length', str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+
+
+async def probe(peer):
+ import websockets
+ from gateway.run import GatewayRunner
+ from gateway.session_authority import initialize_session_authority
+ from gateway.run_api import start_gateway_api, stop_gateway_api
+ from gateway.session_contract import SessionRef
+ from hermes_cli import web_server
+ from hermes_cli.dashboard_auth.ws_tickets import mint_ticket
+ runner = GatewayRunner()
+ authority = await initialize_session_authority(runner, profile_id='fixture', instance_id='policy')
+ api = await start_gateway_api(runner)
+ web_server.app.state.auth_required = True
+ async def connect():
+ ticket = mint_ticket(user_id='creator', provider='fixture')
+ return await websockets.connect(f'ws://127.0.0.1:{api.socket.getsockname()[1]}/api/ws?ticket={ticket}')
+ async def rpc(ws, method, **params):
+ await ws.send(json.dumps({'jsonrpc': '2.0', 'id': method, 'method': method, 'params': params}))
+ async with asyncio.timeout(20):
+ while True:
+ result = json.loads(await ws.recv())
+ if result.get('id') == method:
+ return result
+ sockets, sessions = [], []
+ before = dict(os.environ)
+ config_before = Path(os.environ['HERMES_HOME'], 'config.yaml').read_bytes()
+ try:
+ for source in ('cli', 'tui', 'gui'):
+ ws = await connect()
+ sockets.append(ws)
+ cwd = Path(os.environ['HERMES_HOME'], source)
+ cwd.mkdir()
+ params = dict(request_id=source, source=source, cwd=str(cwd), model='policy-' + source)
+ if source == 'cli':
+ params['toolsets'] = ['terminal']
+ created = await rpc(ws, 'session.create', **params)
+ assert 'result' in created, created
+ sid = created['result']['session_id']
+ sessions.append(sid)
+ again = await rpc(ws, 'session.create', **params)
+ assert again['result']['session_id'] == sid
+ conflict = await rpc(ws, 'session.create', **{**params, 'model': 'conflict'})
+ assert 'error' in conflict, conflict
+ accepted = await rpc(ws, 'prompt.submit', session_id=sid, input_id=source, text='Write owned cwd proof')
+ assert 'result' in accepted, accepted
+ for sid in sessions:
+ async with asyncio.timeout(30):
+ while authority.sessions[sid].task is None:
+ await asyncio.sleep(.01)
+ await asyncio.wait_for(authority.sessions[sid].task, 40)
+ for source, sid, ws in zip(('cli', 'tui', 'gui'), sessions, sockets):
+ agent = authority.agent(SessionRef(authority.profile_id, sid))
+ assert agent is not None, (source, list(runner._agent_cache), peer.requests, await rpc(ws, 'session.resume', session_id=sid))
+ assert agent.platform == {'cli': 'cli', 'tui': 'tui', 'gui': 'desktop'}[source], vars(agent).get('platform')
+ cwd = Path(os.environ['HERMES_HOME'], source)
+ assert (cwd / 'policy-proof.txt').read_text() == 'owned'
+ requests = [r for r in peer.requests if r.get('model') == 'policy-' + source]
+ assert len(requests) >= 2, peer.requests
+ assert any(str(cwd) in json.dumps(m) for r in requests for m in r['messages'] if m['role'] == 'tool')
+ names = {t['function']['name'] for t in requests[0]['tools']}
+ assert 'terminal' in names
+ assert ('desktop_ui' in agent.enabled_toolsets) == (source == 'gui')
+ await ws.close()
+ reconnected = await connect()
+ sockets.append(reconnected)
+ result = await rpc(reconnected, 'session.resume', session_id=sid)
+ assert result['result']['session_id'] == sid
+ assert authority.agent(SessionRef(authority.profile_id, sid)) is agent
+ assert Path(os.environ['HERMES_HOME'], 'config.yaml').read_bytes() == config_before
+ assert {k: os.environ.get(k) for k in ('HERMES_DESKTOP', 'TERMINAL_CWD', 'HERMES_TUI_TOOLSETS')} == {k: before.get(k) for k in ('HERMES_DESKTOP', 'TERMINAL_CWD', 'HERMES_TUI_TOOLSETS')}
+ Path(os.environ['HERMES_HOME'], 'policy-receipt.json').write_text(json.dumps({'sources': ['cli', 'tui', 'gui'], 'requests': len(peer.requests), 'cwd_effects': True, 'same_agents': True, 'no_spill': True}))
+ finally:
+ for ws in sockets:
+ await ws.close()
+ await stop_gateway_api(api)
+
+
+def main():
+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Peer)
+ peer.requests = []
+ threading.Thread(target=peer.serve_forever, daemon=True).start()
+ url = f'http://127.0.0.1:{peer.server_port}/v1'
+ os.environ.update(OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)
+ Path(os.environ['HERMES_HOME'], 'config.yaml').write_text(
+ f'model:\n default: policy-default\n provider: custom\n base_url: {url}\n'
+ 'terminal:\n env_type: local\nstreaming:\n enabled: false\n'
+ 'platform_toolsets:\n cli: [terminal]\nauxiliary:\n title_generation:\n enabled: false\n')
+ try:
+ asyncio.run(probe(peer))
+ finally:
+ peer.shutdown()
+ peer.server_close()
+
+
+if __name__ == '__main__':
+ status = 0
+ try:
+ main()
+ except BaseException:
+ traceback.print_exc()
+ status = 1
+ os._exit(status)
diff --git a/tests/gateway/test_session_policy.py b/tests/gateway/test_session_policy.py
index e0a5d777510..2344dee7321 100644
--- a/tests/gateway/test_session_policy.py
+++ b/tests/gateway/test_session_policy.py
@@ -35,3 +35,22 @@ def test_policy_selects_surface_and_isolates_cwd(tmp_path):
{'provider': 'custom'}, {'skills': ['x']}, {'toolsets': ['desktop_ui'], 'source': 'cli'}):
with pytest.raises(RuntimeStoreError, match='invalid_params'):
build_policy(params, {})
+
+
+def test_launch_policy_reaches_real_turn_runner(tmp_path):
+ import json
+ from pathlib import Path
+ import subprocess
+ import sys
+ repo = Path(__file__).resolve().parents[2]
+ home, state = tmp_path / 'home', tmp_path / 'state'
+ home.mkdir()
+ state.mkdir()
+ env = {k: os.environ[k] for k in ('PATH', 'SYSTEMROOT', 'LANG', 'TZ') if k in os.environ}
+ env.update(HOME=str(home), USERPROFILE=str(home), HERMES_HOME=str(state), PYTHONPATH=str(repo))
+ result = subprocess.run([sys.executable, str(Path(__file__).parent / 'fixtures' / 'session_policy_peer.py')],
+ cwd=repo, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=130)
+ assert result.returncode == 0, result.stdout + '\n' + result.stderr
+ receipt = json.loads((state / 'policy-receipt.json').read_text())
+ assert receipt['cwd_effects'] and receipt['same_agents'] and receipt['no_spill']
+ print(json.dumps(receipt))