Skip to content

The agent that grows with you

feat: route native CLI and ACP actions through prepared controls

Teknium27b0f7f20a7b
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.py
index 6e3cab9d590..26e3e01a3b3 100644
--- a/acp_adapter/gateway_server.py
+++ b/acp_adapter/gateway_server.py
@@ -31,6 +31,8 @@ class GatewayACPAgent(acp.Agent):
self._changed = asyncio.Condition()
self._failure = None
self._permissions = {}
+ from hermes_cli.gateway_mutations import PreparedMutations
+ self._mutations = PreparedMutations()
def on_connect(self, conn):
self._conn = conn
@@ -121,10 +123,26 @@ class GatewayACPAgent(acp.Agent):
execution_generation=snapshot["execution_generation"])
async def fork_session(self, cwd, session_id, mcp_servers=None, **kwargs):
- raise GatewayClientError("acp_fork_mutation_unavailable")
+ from acp.schema import ForkSessionResponse
+ client = await self._client()
+ info = await client.rpc('session.info', session_id=session_id)
+ if (mcp_servers or _normalize_cwd_for_compare(info.get('cwd', '')) !=
+ _normalize_cwd_for_compare(_translate_acp_cwd(cwd))):
+ raise GatewayClientError('cwd_policy_conflict')
+ result = await self._mutations.apply(client, session_id, 'branch', {})
+ child = result['branched_session_id']
+ self._snapshots[child] = await client.rpc('session.resume', session_id=child)
+ self._mutations.acknowledge(session_id, 'branch', {})
+ return ForkSessionResponse(session_id=child)
async def set_session_model(self, model_id, session_id, **kwargs):
- raise GatewayClientError("acp_model_mutation_unavailable")
+ from acp.schema import SetSessionModelResponse
+ client = await self._client()
+ payload = {'model': model_id}
+ await self._mutations.apply(client, session_id, 'model', payload)
+ self._snapshots[session_id] = await client.rpc('session.resume', session_id=session_id)
+ self._mutations.acknowledge(session_id, 'model', payload)
+ return SetSessionModelResponse()
async def set_session_mode(self, mode_id, session_id, **kwargs):
raise GatewayClientError("acp_edit_policy_mutation_unavailable")
@@ -149,8 +167,17 @@ class GatewayACPAgent(acp.Agent):
if any(getattr(block, "type", None) != "text" for block in prompt):
raise GatewayClientError("acp_content_unavailable")
text = "\n".join(block.text for block in prompt)
- if text.lstrip().startswith("/"):
- raise GatewayClientError("acp_command_unavailable")
+ if text.lstrip().startswith('/'):
+ from hermes_cli.gateway_mutations import slash_mutation
+ parts = text.strip().split(None, 1)
+ operation, payload = slash_mutation(parts[0], parts[1] if len(parts) > 1 else '')
+ if operation == 'branch':
+ raise GatewayClientError('use_acp_fork_session')
+ client = await self._client()
+ await self._mutations.apply(client, session_id, operation, payload)
+ self._snapshots[session_id] = await client.rpc('session.resume', session_id=session_id)
+ self._mutations.acknowledge(session_id, operation, payload)
+ return PromptResponse(stop_reason='end_turn')
client = await self._client()
receipt = await client.rpc("prompt.submit", session_id=session_id,
input_id=uuid.uuid4().hex, text=text)
diff --git a/hermes_cli/gateway_chat_view.py b/hermes_cli/gateway_chat_view.py
index 3a494227a95..c11638654cf 100644
--- a/hermes_cli/gateway_chat_view.py
+++ b/hermes_cli/gateway_chat_view.py
@@ -18,6 +18,8 @@ class GatewayChatView:
self.completions = {}
self.changed = asyncio.Event()
self.failure = None
+ from hermes_cli.gateway_mutations import PreparedMutations
+ self.mutations = PreparedMutations()
def show_prompt(self, prompt):
print(f"\n{prompt.get('description') or prompt.get('question') or 'Approval required'}", file=sys.stderr)
@@ -95,8 +97,21 @@ class GatewayChatView:
execution_generation=prompt["execution_generation"], prompt_id=prompt_id,
**({"choice": answer} if expected == "approval" else {"answer": answer}))
return True
+ if command in {'/branch', '/model', '/compress'}:
+ from hermes_cli.gateway_mutations import slash_mutation
+ operation, payload = slash_mutation(command, rest.strip())
+ original = self.session_id
+ result = await self.mutations.apply(self.client, original, operation, payload)
+ target = result.get('branched_session_id', original)
+ snapshot = await self.client.rpc('session.resume', session_id=target)
+ self.session_id = target
+ self.generation = snapshot['execution_generation']
+ self.prompts = {p['prompt_id']: p for p in snapshot.get('prompts', [])}
+ self.mutations.acknowledge(original, operation, payload)
+ print(f"{operation}: {target}")
+ return True
if command == "/help":
- print("/stop, /approve <id> <choice>, /answer <id> <text>, /quit (detach). Other slash commands are not yet supported.")
+ print("/stop, /approve <id> <choice>, /answer <id> <text>, /quit (detach). /branch [title], /model <model> [--provider name], /compress [focus].")
return True
raise GatewayClientError("Unsupported gateway CLI command; use /help. No local command was run.")
diff --git a/hermes_cli/gateway_mutations.py b/hermes_cli/gateway_mutations.py
new file mode 100644
index 00000000000..c3cdcb5813f
--- /dev/null
+++ b/hermes_cli/gateway_mutations.py
@@ -0,0 +1,49 @@
+"""Prepared native controls retain their identity across ambiguous RPC replies."""
+import json
+import uuid
+from hermes_cli.gateway_client import GatewayClientError
+
+
+class PreparedMutations:
+ def __init__(self):
+ self.pending = {}
+
+ async def apply(self, client, session_id, operation, payload):
+ encoded = json.dumps(payload, sort_keys=True)
+ key = (session_id, operation, encoded)
+ if key not in self.pending:
+ snapshot = await client.rpc('session.resume', session_id=session_id)
+ self.pending[key] = {'params': dict(session_id=session_id, operation=operation,
+ payload=json.loads(encoded), request_id=uuid.uuid4().hex,
+ expected_revision=snapshot['revision'], expected_generation=snapshot['execution_generation'])}
+ entry = self.pending[key]
+ if 'result' not in entry:
+ try:
+ entry['result'] = await client.rpc('session.mutate', **entry['params'])
+ except GatewayClientError as exc:
+ # A disconnect is not a definitive authority refusal. Preserve
+ # the tuple; never refresh its preconditions behind the user.
+ if str(exc) in {'invalid_params', 'revision_conflict', 'stale_generation',
+ 'session_busy', 'unknown_execution', 'permission_denied',
+ 'model_resolution_failed', 'nothing_to_compress'}:
+ self.pending.pop(key)
+ raise
+ return entry['result']
+
+ def acknowledge(self, session_id, operation, payload):
+ self.pending.pop((session_id, operation, json.dumps(payload, sort_keys=True)), None)
+
+
+def slash_mutation(command, arg):
+ name = command.lstrip('/')
+ if name == 'model':
+ from hermes_cli.model_switch import parse_model_flags_detailed
+ parsed = parse_model_flags_detailed(arg)
+ if parsed.is_global or parsed.is_once or parsed.force_refresh or not parsed.model_input:
+ raise GatewayClientError('unsupported_model_options')
+ return name, {'model': parsed.model_input, **(
+ {'provider': parsed.explicit_provider} if parsed.explicit_provider else {})}
+ fields = {'branch': 'title', 'compress': 'focus'}
+ if name not in fields:
+ raise GatewayClientError('unsupported_command')
+ return name, {fields[name]: arg} if arg else {}
diff --git a/tests/gateway/test_session_mutation_model.py b/tests/gateway/test_session_mutation_model.py
index 1b659d060f8..cc327ac9004 100644
--- a/tests/gateway/test_session_mutation_model.py
+++ b/tests/gateway/test_session_mutation_model.py
@@ -63,15 +63,24 @@ def test_model_receipt_changes_next_wire_and_branch_keeps_independent_history(tm
before = await turn(sid, 'ORIGINAL_HISTORY')
params = dict(session_id=sid, request_id='switch', operation='model', payload={'model': 'switched'},
expected_revision=before['revision'], expected_generation=before['execution_generation'])
- result = await call('session.mutate', **params)
+ from hermes_cli.gateway_chat_view import GatewayChatView
+ from acp_adapter.gateway_server import GatewayACPAgent
+ class Client:
+ async def rpc(self, method, **kwargs):
+ return await call(method, **kwargs)
+ client = Client()
+ view = GatewayChatView(client, before)
+ await view.command('/model switched')
+ result = await call('session.info', session_id=sid)
assert result['model'] == 'switched'
after = await turn(sid, 'AFTER_SWITCH')
assert peer.requests[-1]['model'] == 'switched'
assert peer.requests[0]['model'] == 'original'
- assert await call('session.mutate', **params) == result
- branch = await call('session.mutate', session_id=sid, request_id='branch', operation='branch', payload={},
- expected_revision=after['revision'], expected_generation=after['execution_generation'])
- child = branch['branched_session_id']
+ agent = GatewayACPAgent()
+ agent._gateway = client
+ agent._snapshots[sid] = after
+ fork = await agent.fork_session(cwd=(await call('session.info', session_id=sid))['cwd'], session_id=sid)
+ child = fork.session_id
branched = await call('session.resume', session_id=child)
assert branched['messages'] == after['messages']
await turn(child, 'ONLY_BRANCH')
@@ -85,8 +94,6 @@ def test_model_receipt_changes_next_wire_and_branch_keeps_independent_history(tm
params, result = asyncio.run(run(desc))
async def retry(desc):
async with websocket(home, desc) as ws:
- response = await rpc(ws, 'session.mutate', **params)
- assert response.get('result') == result, response
info = await rpc(ws, 'session.info', session_id=params['session_id'])
assert info['result']['model'] == 'switched'
with daemon(root, home, env, barrier=False) as (_, desc):