Skip to content

The agent that grows with you

fix(acp): restore session metadata, commands and usage on GatewayACPAgent

unsupportedpastelsb9f4b093a2ac
diff --git a/acp_adapter/gateway_commands.py b/acp_adapter/gateway_commands.py
new file mode 100644
index 00000000000..ef8bc06e96f
--- /dev/null
+++ b/acp_adapter/gateway_commands.py
@@ -0,0 +1,109 @@
+"""Editor slash commands on the gateway path; each one is an existing gateway verb.
+
+Main served these in-process (``acp_adapter/commands.py``). The reports are the owner's own
+``slash.exec`` reads, ``/model``, ``/compress`` and ``/reset`` the retained ``session.mutate``
+controls, ``/steer`` the owner's ``session.steer``; ``/queue`` and an idle ``/steer`` become the
+next prompt, which the session's FIFO runs after any turn in flight.
+"""
+from __future__ import annotations
+
+from hermes_cli.gateway_client import GatewayClientError, GatewayRPCError
+
+# Reports the owner answers for a local session (``gateway/session_commands.py::_READ_COMMANDS``).
+_READS = frozenset({'context', 'usage', 'status', 'version'})
+_MUTATIONS = frozenset({'model', 'compress', 'new', 'branch'})
+_PROMPTS = frozenset({'steer', 'queue'})
+COMMANDS = _READS | _MUTATIONS | _PROMPTS | {'help', 'tools'}
+
+
+async def run_command(agent, session_id, command, arg):
+ """``(reply, None)`` for a command answered here, or ``(None, text)`` when ``text`` is to be
+ submitted as the prompt. Unsupported commands are refused before any gateway call."""
+ from acp_adapter.gateway_session_meta import help_text
+ if command not in COMMANDS:
+ raise GatewayClientError('unsupported_command')
+ if command == 'branch':
+ raise GatewayClientError('use_acp_fork_session')
+ if command == 'help':
+ return help_text(), None
+ if command in _PROMPTS:
+ if not arg:
+ return f"Usage: /{command} <{'guidance' if command == 'steer' else 'prompt'}>", None
+ steered = await _steer(agent, session_id, arg) if command == 'steer' else None
+ return (steered, None) if steered else (None, arg)
+ client = await agent._client()
+ if command in _READS:
+ result = await client.rpc('slash.exec', session_id=session_id, command=f'/{command} {arg}'.strip())
+ return str(result.get('output') or result.get('notice') or ''), None
+ if command == 'tools' or (command == 'model' and not arg):
+ info = await client.rpc('session.info', session_id=session_id)
+ return (_tools_text(info) if command == 'tools' else _model_text('Current model', info)), None
+ return await _mutate(agent, client, session_id, command, arg), None
+
+
+async def _steer(agent, session_id, text):
+ """Guidance for this editor's running turn; None when there is none to steer (main ran an idle
+ steer as a plain prompt, and a turn that ended meanwhile leaves the text for the next one)."""
+ if session_id not in agent._admissions:
+ return None
+ client = await agent._client()
+ try:
+ result = await client.rpc('session.steer', session_id=session_id, text=text,
+ execution_generation=agent._snapshots[session_id].get('execution_generation'))
+ except GatewayRPCError as exc:
+ # Only a turn that ended meanwhile (its generation moved on) leaves the text for the next
+ # prompt; any other refusal (permission, unsupported control, not ready) is the answer.
+ if str(exc) == 'stale_generation':
+ return None
+ raise
+ if result.get('status') != 'queued':
+ return None
+ return f"⏩ Steer queued for the active turn: {text[:80]}{'...' if len(text) > 80 else ''}"
+
+
+async def _mutate(agent, client, session_id, command, arg):
+ from hermes_cli.gateway_mutations import slash_mutation
+ operation, payload = ('reset', {}) if command == 'new' else slash_mutation('/' + command, arg)
+ confirm = agent._model_confirmer(session_id) if operation == 'model' else None
+ result = await agent._mutations.apply(client, session_id, operation, payload, confirm=confirm)
+ status = result.get('status')
+ if status == 'cancelled':
+ from agent.i18n import t
+ reply = t('cli.model.switch_cancelled')
+ elif status == 'preview':
+ # Read-only report: nothing changed, so the editor's snapshot is still current.
+ reply = '\n'.join(result['lines'])
+ elif status == 'noop':
+ # Nothing removable (an empty session too): the owner's shared report, nothing committed.
+ reply = _summary_text(result) or 'No changes from compression.'
+ else:
+ agent._snapshots[session_id] = await client.rpc('session.resume', session_id=session_id)
+ reply = {'model': lambda: _model_text('Model switched to', result),
+ 'compress': lambda: _summary_text(result) or 'Context compressed.',
+ 'reset': lambda: 'Conversation history cleared.'}[operation]()
+ agent._mutations.acknowledge(session_id, operation, payload)
+ return reply
+
+
+def _summary_text(result):
+ summary = result.get('summary') or {}
+ return '\n'.join(filter(None, (summary.get('headline'), summary.get('token_line'), summary.get('note'))))
+
+
+def _model_text(label, fields):
+ lines = [f"{label}: {fields.get('model') or 'unknown'}"]
+ if fields.get('provider'):
+ lines.append(f"Provider: {fields['provider']}")
+ return '\n'.join(lines)
+
+
+def _tools_text(info):
+ """The session's tools by toolset (``session.info`` ``tools``: toolset -> tool names)."""
+ groups = info.get('tools') or {}
+ names = sorted({name for tools in groups.values() for name in tools})
+ if not names:
+ toolsets = info.get('enabled_toolsets') or []
+ return f"Enabled toolsets: {', '.join(toolsets)}" if toolsets else "No tools available."
+ lines = [f"Available tools ({len(names)}):"]
+ lines.extend(f" {toolset}: {', '.join(sorted(tools))}" for toolset, tools in sorted(groups.items()) if tools)
+ return '\n'.join(lines)
diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.py
index c49f5a3050f..29d4f5fe4fd 100644
--- a/acp_adapter/gateway_server.py
+++ b/acp_adapter/gateway_server.py
@@ -140,6 +140,11 @@ class GatewayACPAgent(acp.Agent):
self._form_elicitation = False
from hermes_cli.gateway_mutations import PreparedMutations
self._mutations = PreparedMutations()
+ # Session -> title the editor was last shown (``session_info_update`` fires on a change).
+ self._titles = {}
+ # Session -> the owner's latest usage dict (``session.usage`` / ``session.stats``).
+ self._usage = {}
+ self._background = set()
def on_connect(self, conn):
self._conn = conn
@@ -260,15 +265,56 @@ class GatewayACPAgent(acp.Agent):
source="acp", cwd=_translate_acp_cwd(cwd),
editor={"mcp_servers": [s.model_dump(by_alias=True) for s in mcp_servers or []],
"edit_approval_policy": "ask"})
- self._snapshots[snapshot["session_id"]] = snapshot
+ session_id = snapshot["session_id"]
+ self._snapshots[session_id] = snapshot
if mcp_servers:
- self._editor_mcp[snapshot["session_id"]] = {
+ self._editor_mcp[session_id] = {
"mcp_servers": [s.model_dump(by_alias=True) for s in mcp_servers]}
- return NewSessionResponse(session_id=snapshot["session_id"])
+ info = snapshot.get("info") or await client.rpc("session.info", session_id=session_id)
+ return NewSessionResponse(session_id=session_id, **await self._session_fields(session_id, info, session_id))
def _editor_id(self, session_id):
return next((held for held, sid in self._aliases.items() if sid == session_id), session_id)
+ async def _session_fields(self, session_id, info, editor_id):
+ """Main's new/load/resume/fork reply fields (model picker, modes, provenance ``_meta``); the
+ command list and context indicator follow once the reply is queued, as main scheduled them."""
+ from acp_adapter.gateway_session_meta import model_state, provenance_meta, session_modes
+ title = info.get("title")
+ if isinstance(title, str) and title.strip():
+ self._titles[session_id] = title
+ models = await asyncio.to_thread(model_state, info)
+ meta = await asyncio.to_thread(provenance_meta, self._home / "state.db", editor_id, session_id)
+ if self._conn:
+ task = asyncio.get_running_loop().create_task(self._after_attach(session_id, editor_id))
+ self._background.add(task)
+ task.add_done_callback(self._background.discard)
+ return {"models": models, "modes": session_modes(), "field_meta": meta}
+
+ async def _after_attach(self, session_id, editor_id):
+ from acp_adapter.gateway_session_meta import available_commands_update
+ await asyncio.sleep(0) # after the session reply: the editor routes updates by a known id
+ try:
+ await self._conn.session_update(session_id=editor_id, update=available_commands_update())
+ await self._project_usage(session_id, editor_id,
+ await (await self._client()).rpc("session.stats", session_id=session_id))
+ except Exception:
+ # Boundary: a detached editor or a refused read is not the attach's failure.
+ logger.debug("ACP post-attach notices for %s not delivered", session_id, exc_info=True)
+
+ async def _attach_info(self, client, session_id):
+ """``session.info`` for a session to attach. A thread main's in-process server wrote has no
+ gateway policy yet; ``session.resume`` is the verb that adopts it (``LEGACY_LOCAL_SOURCES``)."""
+ from hermes_cli.gateway_client import GatewayRPCError
+ try:
+ return await client.rpc("session.info", session_id=session_id)
+ except GatewayRPCError as exc:
+ if str(exc) != "not_found":
+ raise
+ adopted = await client.rpc("session.resume", session_id=session_id)
+ await client.rpc("session.detach", session_id=session_id, subscription_id=adopted["subscription_id"])
+ return await client.rpc("session.info", session_id=session_id)
+
async def _resume(self, cwd, held_id, mcp_servers):
client = await self._client()
from acp_adapter.catalog import logical_session_id
@@ -277,7 +323,7 @@ class GatewayACPAgent(acp.Agent):
self._aliases = {held: sid for held, sid in self._aliases.items() if sid != session_id}
if session_id != held_id:
self._aliases[held_id] = session_id
- info = await client.rpc("session.info", session_id=session_id)
+ info = await self._attach_info(client, session_id)
if "cwd" in info and _normalize_cwd_for_compare(info["cwd"]) != _normalize_cwd_for_compare(_translate_acp_cwd(cwd)):
raise GatewayClientError("cwd_policy_conflict")
if "cwd" not in info and self._conn:
@@ -300,15 +346,13 @@ class GatewayACPAgent(acp.Agent):
for pending in snapshot.get("prompts", []):
self._permission(session_id, pending)
await self._notify_unknown(session_id)
- return snapshot
+ return await self._session_fields(session_id, {**info, **(snapshot.get("info") or {})}, held_id)
async def load_session(self, cwd, session_id, mcp_servers=None, **kwargs):
- await self._resume(cwd, session_id, mcp_servers)
- return LoadSessionResponse()
+ return LoadSessionResponse(**await self._resume(cwd, session_id, mcp_servers))
async def resume_session(self, cwd, session_id, mcp_servers=None, **kwargs):
- await self._resume(cwd, session_id, mcp_servers)
- return ResumeSessionResponse()
+ return ResumeSessionResponse(**await self._resume(cwd, session_id, mcp_servers))
async def _cancel_admission(self, session_id, admission_id):
client = await self._client()
@@ -360,7 +404,8 @@ class GatewayACPAgent(acp.Agent):
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)
+ info = self._snapshots[child].get('info') or await client.rpc('session.info', session_id=child)
+ return ForkSessionResponse(session_id=child, **await self._session_fields(child, info, child))
async def set_session_model(self, model_id, session_id, **kwargs):
from acp.schema import SetSessionModelResponse
@@ -403,11 +448,31 @@ class GatewayACPAgent(acp.Agent):
return isinstance(response.outcome, AllowedOutcome) and response.outcome.option_id == "allow_once"
return confirm
- async def set_session_mode(self, mode_id, session_id, **kwargs):
- raise GatewayClientError("acp_edit_policy_mutation_unavailable")
+ def _held_session(self, session_id):
+ session_id = self._aliases.get(session_id, session_id)
+ if session_id not in self._snapshots:
+ raise GatewayClientError("not_found")
+ return session_id
- async def set_config_option(self, config_id, session_id, **kwargs):
- raise GatewayClientError("acp_config_mutation_unavailable")
+ async def set_session_mode(self, mode_id, session_id, **kwargs):
+ """The advertised mode is the owner's own policy, so selecting it changes nothing; main's
+ Accept Edits / Don't Ask need an editor-policy change the gateway has no verb for."""
+ from acp.schema import SetSessionModeResponse
+ from acp_adapter.gateway_session_meta import DEFAULT_MODE
+ self._held_session(session_id)
+ if mode_id != DEFAULT_MODE:
+ raise GatewayClientError("acp_edit_policy_mutation_unavailable")
+ return SetSessionModeResponse()
+
+ async def set_config_option(self, config_id, session_id, value=None, **kwargs):
+ """Accepted so editors do not fail on their own config writes, as main did; only the edit
+ approval policy has a meaning here, and only the owner's ``ask`` can be selected."""
+ from acp.schema import SetSessionConfigOptionResponse
+ from acp_adapter.gateway_session_meta import DEFAULT_EDIT_APPROVAL_POLICY, EDIT_APPROVAL_POLICY_CONFIG_ID
+ self._held_session(session_id)
+ if config_id == EDIT_APPROVAL_POLICY_CONFIG_ID and value != DEFAULT_EDIT_APPROVAL_POLICY:
+ raise GatewayClientError("acp_edit_policy_mutation_unavailable")
+ return SetSessionConfigOptionResponse(config_options=[])
async def list_sessions(self, cursor=None, cwd=None, **kwargs):
from acp.schema import ListSessionsResponse, SessionInfo
@@ -433,26 +498,13 @@ class GatewayACPAgent(acp.Agent):
retained = self._unacked.pop(session_id, None)
command = _slash_command(text) if not attachments else None
if command is not None:
- from hermes_cli.gateway_mutations import slash_mutation
+ from acp_adapter.gateway_commands import run_command
parts = text.strip().split(None, 1)
- operation, payload = slash_mutation('/' + command, parts[1] if len(parts) > 1 else '')
- if operation == 'branch':
- raise GatewayClientError('use_acp_fork_session')
- client = await self._client()
- result = await self._mutations.apply(client, session_id, operation, payload,
- confirm=self._model_confirmer(session_id) if operation == 'model' else None)
- if result.get('status') == 'cancelled':
- from agent.i18n import t
- await self._conn.session_update(session_id=held_id,
- update=acp.update_agent_message_text(t('cli.model.switch_cancelled') + '\n'))
- elif result.get('status') == 'preview':
- # Read-only report: nothing changed, so the editor's snapshot is still current.
- await self._conn.session_update(session_id=held_id,
- update=acp.update_agent_message_text('\n'.join(result['lines']) + '\n'))
- else:
- 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')
+ reply, text = await run_command(self, session_id, command, parts[1].strip() if len(parts) > 1 else '')
+ if reply is not None:
+ if self._conn:
+ await self._conn.session_update(session_id=held_id, update=acp.update_agent_message_text(reply + '\n'))
+ return PromptResponse(stop_reason='end_turn')
# ... and every prepared control's (a slash keeps its own key: apply retires the rest).
self._mutations.retire(session_id)
submit = {'text': text}
@@ -516,7 +568,10 @@ class GatewayACPAgent(acp.Agent):
raise GatewayClientError(self._unknown_recovery(session_id, admission_id))
if outcome == "failed":
raise GatewayClientError("admitted_turn_failed")
- return PromptResponse(stop_reason="cancelled" if outcome == "cancelled" else "end_turn")
+ from acp_adapter.gateway_session_meta import turn_usage
+ # The turn's last ``session.usage`` precedes its ``message.complete`` on the stream.
+ return PromptResponse(stop_reason="cancelled" if outcome == "cancelled" else "end_turn",
+ usage=turn_usage(self._usage.get(session_id)))
async def _settled_receipt(self, client, held_id, session_id, receipt):
admission_id = receipt["admission_id"]
@@ -597,11 +652,8 @@ class GatewayACPAgent(acp.Agent):
kind, payload = event.get("type"), event.get("payload", {})
sid, editor_id = event["session_id"], self._editor_id(event["session_id"])
aid = event.get("admission_id")
- if kind == "session.info":
- if sid in self._snapshots and "pending" in payload:
- async with self._changed:
- self._snapshots[sid]["pending"] = payload["pending"]
- self._changed.notify_all()
+ if kind in {"session.info", "session.updated", "session.usage"}:
+ await self._project_session_state(kind, sid, editor_id, payload)
return
if kind == "session.replay_gap":
raise GatewayClientError("session_replay_gap")
@@ -670,6 +722,33 @@ class GatewayACPAgent(acp.Agent):
finally:
self._settling.discard(aid)
+ async def _project_session_state(self, kind, sid, editor_id, payload):
+ if kind == "session.usage":
+ await self._project_usage(sid, editor_id, payload)
+ return
+ if kind == "session.info" and sid in self._snapshots and "pending" in payload:
+ async with self._changed:
+ self._snapshots[sid]["pending"] = payload["pending"]
+ self._changed.notify_all()
+ await self._project_title(sid, editor_id, payload.get("title"))
+
+ async def _project_usage(self, sid, editor_id, stats):
+ """The owner's usage dict: kept for the turn's ``PromptResponse.usage``, shown as ``usage_update``."""
+ from acp_adapter.gateway_session_meta import usage_update
+ self._usage[sid] = stats
+ if self._conn and (update := usage_update(stats)) is not None:
+ await self._conn.session_update(session_id=editor_id, update=update)
+
+ async def _project_title(self, sid, editor_id, title):
+ """A new title (auto-title's ``session.info``, a rename's ``session.updated``) as main's
+ ``session_info_update``; the owner republishes an unchanged one after every turn."""
+ if not isinstance(title, str) or not title.strip() or title == self._titles.get(sid):
+ return
+ self._titles[sid] = title
+ if self._conn:
+ from acp_adapter.gateway_session_meta import title_update
+ await self._conn.session_update(session_id=editor_id, update=title_update(title))
+
def _close_segment(self, aid):
streamed = self._streamed.pop(aid, "")
if streamed.strip():
diff --git a/acp_adapter/gateway_session_meta.py b/acp_adapter/gateway_session_meta.py
new file mode 100644
index 00000000000..b6caa52c32f
--- /dev/null
+++ b/acp_adapter/gateway_session_meta.py
@@ -0,0 +1,123 @@
+"""Editor session metadata on the gateway path, projected from the gateway's existing reads.
+
+Main's in-process server read these off its live agent (``server.py`` ``_session_response_fields``,
+``_build_usage_update``, ``_send_session_info_update``); here every figure comes from a snapshot's
+``info`` (``session.info``), ``session.stats``, a ``message.complete`` ``usage`` or ``state.db``.
+"""
+from __future__ import annotations
+
+from datetime import UTC, datetime
+import logging
+from pathlib import Path
+import sqlite3
+
+from acp.schema import (
+ AvailableCommand, AvailableCommandsUpdate, ModelInfo, SessionInfoUpdate, SessionMode, SessionModeState,
+ SessionModelState, UnstructuredCommandInput, Usage, UsageUpdate,
+)
+
+logger = logging.getLogger(__name__)
+
+# The gateway honours one editor edit policy, ``ask`` (``gateway/session_local_editor.py``), and has
+# no verb that changes it on a live session, so main's Accept Edits / Don't Ask are not offered.
+DEFAULT_MODE = "default"
+DEFAULT_EDIT_APPROVAL_POLICY = "ask"
+EDIT_APPROVAL_POLICY_CONFIG_ID = "edit_approval_policy"
+
+# Advertised name -> (description, input hint). ``prompt`` serves each through a gateway verb
+# (``acp_adapter/gateway_commands.py``); ``/reset`` is the registry's alias of ``/new``.
+COMMANDS: dict[str, tuple[str, str | None]] = {
+ "help": ("List available commands", None),
+ "model": ("Show current model and provider, or switch models", "model name to switch to"),
+ "tools": ("List available tools", None),
+ "context": ("Show conversation context usage", None),
+ "reset": ("Clear conversation history", None),
+ "compress": ("Compress conversation context", None),
+ "steer": ("Inject guidance into the currently running agent turn", "guidance for the active turn"),
+ "queue": ("Queue a prompt to run after the current turn finishes", "prompt to run next"),
+ "usage": ("Show token usage and rate limits", None),
+ "status": ("Show session, model, token, and context info", None),
+ "version": ("Show Hermes version", None),
+}
+
+
+def available_commands_update() -> AvailableCommandsUpdate:
+ return AvailableCommandsUpdate(session_update="available_commands_update", available_commands=[
+ AvailableCommand(name=name, description=description,
+ input=UnstructuredCommandInput(hint=hint) if hint else None)
+ for name, (description, hint) in COMMANDS.items()])
+
+
+def help_text() -> str:
+ lines = ["Available commands:", ""]
+ lines.extend(f" /{name:10s} {description}" for name, (description, _hint) in COMMANDS.items())
+ lines.extend(["", "Unrecognized /commands are sent to the model as normal messages."])
+ return "\n".join(lines)
+
+
+def session_modes() -> SessionModeState:
+ return SessionModeState(current_mode_id=DEFAULT_MODE, available_modes=[
+ SessionMode(id=DEFAULT_MODE, name="Default", description="Ask before edits.")])
+
+
+def model_state(info: dict) -> SessionModelState | None:
+ """The picker for the session's model (``session.info``), from the shared inventory; a single
+ current-model row when nothing is listable, as main's ``_build_model_state``. Blocking."""
+ from acp_adapter.auth import detect_provider
+ from acp_adapter.model_catalog import build_model_state, encode_model_choice
+ model = str(info.get("model") or "").strip()
+ provider = info.get("provider") or detect_provider() or "openrouter"
+ try:
+ picker = build_model_state(model, provider, "")
+ if picker is not None:
+ return picker
+ except Exception:
+ # Boundary: a broken inventory must not fail session/new; the current model still shows.
+ logger.debug("Could not build ACP model state", exc_info=True)
+ if not model:
+ return None
+ choice = encode_model_choice(provider, model)
+ return SessionModelState(available_models=[ModelInfo(model_id=choice, name=model)], current_model_id=choice)
+
+
+def provenance_meta(db_path: Path, acp_session_id: str, session_id: str) -> dict | None:
+ """``_meta.hermes.sessionProvenance`` for the editor's id, the logical session's current
+ compression tip and its lineage (``acp_adapter/provenance.py``). Blocking."""
+ from acp_adapter.provenance import session_provenance_meta
+ from hermes_state import SessionDB
+ if not Path(db_path).exists():
+ return None
+ try:
+ with SessionDB(db_path=db_path, read_only=True) as db:
+ return session_provenance_meta(db, acp_session_id, db.get_compression_tip(session_id) or session_id)
+ except sqlite3.Error:
+ # Best-effort, as main's ``_provenance_meta``: an unreadable store must not fail the attach.
+ logger.debug("Could not build ACP session provenance for %s", session_id, exc_info=True)
+ return None
+
+
+# ``stats`` below is the owner's usage dict (``gateway/session_usage.py::usage_stats``): the
+# ``session.usage`` event published after every API call and at turn end, or ``session.stats``.
+
+def usage_update(stats: dict) -> UsageUpdate | None:
+ """Zed's context indicator: ``size`` the context window, ``used`` its current occupancy."""
+ size = stats.get("context_length")
+ if type(size) is not int or size <= 0:
+ return None
+ return UsageUpdate(session_update="usage_update", size=size, used=max(int(stats.get("context_tokens") or 0), 0))
+
+
+def turn_usage(stats) -> Usage | None:
+ """``PromptResponse.usage``: the agent's session counters, the figures main's turn result carried."""
+ if not isinstance(stats, dict):
+ return None
+ return Usage(input_tokens=int(stats.get("input_tokens") or 0), output_tokens=int(stats.get("output_tokens") or 0),
+ total_tokens=int(stats.get("total_tokens") or 0),
+ thought_tokens=stats.get("reasoning_tokens") or None,
+ cached_read_tokens=stats.get("cache_read_tokens") or None)
+
+
+def title_update(title: str) -> SessionInfoUpdate:
+ # ``sessions`` has no ``updated_at``; "now" is right since this fires when the title changed.
+ return SessionInfoUpdate(session_update="session_info_update", title=title,
+ updated_at=datetime.now(UTC).isoformat())
diff --git a/hermes_state_local_migration.py b/hermes_state_local_migration.py
index 4b44c55b8b7..beb42b989b3 100644
--- a/hermes_state_local_migration.py
+++ b/hermes_state_local_migration.py
@@ -11,7 +11,8 @@ LEGACY_PREFIX = 'gateway.local_legacy.v1:'
# (``chat --source tool``) are CLI runs that printed ``hermes --resume <id>``: adopted for resume like
# ``cli`` and keeping their label, so human pickers still hide them (INTERNAL_LISTING_SOURCES).
# ``desktop`` is the label main's Desktop stored; it is adopted as the ``gui`` creation source.
-LEGACY_LOCAL_SOURCES = frozenset({'cli', 'tui', 'gui', 'desktop', 'oneshot', 'tool'})
+# ``acp`` is main's in-process editor server (Zed, VS Code, JetBrains): adopted under its own source.
+LEGACY_LOCAL_SOURCES = frozenset({'cli', 'tui', 'gui', 'desktop', 'oneshot', 'tool', 'acp'})
# Legacy labels that are not creation sources of their own (session_policy.SURFACES).
LEGACY_CREATION_SOURCES = {'desktop': 'gui'}
diff --git a/tests/acp_adapter/test_acp_reattach_unknown_notice.py b/tests/acp_adapter/test_acp_reattach_unknown_notice.py
index 085b6608636..3f86e7779f1 100644
--- a/tests/acp_adapter/test_acp_reattach_unknown_notice.py
+++ b/tests/acp_adapter/test_acp_reattach_unknown_notice.py
@@ -49,7 +49,8 @@ async def test_reattach_after_restart_posts_the_unknown_recovery_notice(monkeypa
await first.wait_closed()
await asyncio.wait_for(agent._event_task, 5) # the pump records the transport loss
await agent._client()
- (call,) = agent._conn.session_update.await_args_list[before:]
+ (call,) = [call for call in agent._conn.session_update.await_args_list[before:]
+ if call.kwargs["update"].session_update == "agent_message_chunk"]
assert call.kwargs["session_id"] == "s"
assert "/discard lost-1" in call.kwargs["update"].content.text
finally:
diff --git a/tests/acp_adapter/test_gateway_reconnect.py b/tests/acp_adapter/test_gateway_reconnect.py
index c37f2bbeb9a..e56b0a29bdb 100644
--- a/tests/acp_adapter/test_gateway_reconnect.py
+++ b/tests/acp_adapter/test_gateway_reconnect.py
@@ -82,7 +82,8 @@ async def test_editor_reconnects_to_a_restarted_gateway_without_resending(monkey
assert owners[1].calls == ["runtime.describe", "session.resume", "prompt.submit"]
assert owners[0].calls.count("prompt.submit") == 1
assert agent._snapshots["s"]["replay_epoch"] == "second"
- texts = [call.kwargs["update"].content.text for call in agent._conn.session_update.await_args_list]
+ texts = [call.kwargs["update"].content.text for call in agent._conn.session_update.await_args_list
+ if call.kwargs["update"].session_update == "agent_message_chunk"]
assert texts.count("AFTER-RESTART") == 1
finally:
await agent.aclose()
diff --git a/tests/acp_adapter/test_gateway_session_commands.py b/tests/acp_adapter/test_gateway_session_commands.py
new file mode 100644
index 00000000000..3683aa339cd
--- /dev/null
+++ b/tests/acp_adapter/test_gateway_session_commands.py
@@ -0,0 +1,91 @@
+"""``/queue``, ``/steer`` and the edit-policy mode on the gateway path, against a fake owner."""
+import asyncio
+from unittest.mock import AsyncMock
+
+import acp
+import pytest
+
+from acp_adapter.gateway_server import GatewayACPAgent
+from hermes_cli.gateway_client import GatewayClientError
+
+
+def _agent(rpc):
+ agent = GatewayACPAgent()
+ agent._gateway, agent._conn = AsyncMock(), AsyncMock()
+ agent._gateway.rpc.side_effect = rpc
+ agent._snapshots['s'] = {'execution_generation': 7}
+ return agent
+
+
+async def test_queue_submits_its_text_as_the_next_prompt():
+ async def rpc(method, **params):
+ assert method == 'prompt.submit' and params['text'] == 'run the linter', (method, params)
+ await agent._project({'session_id': 's', 'type': 'message.complete', 'admission_id': 'a',
+ 'payload': {'outcome': 'completed', 'text': 'done'}})
+ return {'admission_id': 'a'}
+
+ agent = _agent(rpc)
+ response = await asyncio.wait_for(agent.prompt([acp.text_block('/queue run the linter')], 's'), 5)
+ assert response.stop_reason == 'end_turn'
+
+
+async def test_steer_reaches_this_editors_running_turn():
+ async def rpc(method, **params):
+ assert method == 'session.steer', method
+ assert params == {'session_id': 's', 'text': 'use pytest', 'execution_generation': 7}
+ return {'status': 'queued', 'text': 'use pytest', 'execution_generation': 7, 'authority_epoch': 1}
+
+ agent = _agent(rpc)
+ agent._admissions['s'] = 'running-turn'
+ response = await agent.prompt([acp.text_block('/steer use pytest')], 's')
+ assert response.stop_reason == 'end_turn'
+ assert 'Steer queued for the active turn: use pytest' in \
+ agent._conn.session_update.await_args.kwargs['update'].content.text
+
+
+async def test_a_refused_steer_is_reported_and_never_resent_as_a_prompt():
+ from hermes_cli.gateway_client import GatewayRPCError
+ calls = []
+
+ async def rpc(method, **params):
+ calls.append(method)
+ raise GatewayRPCError('unsupported_control')
+
+ agent = _agent(rpc)
+ agent._admissions['s'] = 'running-turn'
+ with pytest.raises(GatewayRPCError, match='unsupported_control'):
+ await agent.prompt([acp.text_block('/steer use pytest')], 's')
+ assert calls == ['session.steer']
+
+
+async def test_a_steer_for_a_turn_that_just_ended_becomes_the_next_prompt():
+ from hermes_cli.gateway_client import GatewayRPCError
+ calls = []
+
+ async def rpc(method, **params):
+ calls.append(method)
+ if method == 'session.steer':
+ raise GatewayRPCError('stale_generation')
+ assert method == 'prompt.submit' and params['text'] == 'use pytest', (method, params)
+ await agent._project({'session_id': 's', 'type': 'message.complete', 'admission_id': 'a',
+ 'payload': {'outcome': 'completed', 'text': 'done'}})
+ return {'admission_id': 'a'}
+
+ agent = _agent(rpc)
+ agent._admissions['s'] = 'running-turn'
+ response = await asyncio.wait_for(agent.prompt([acp.text_block('/steer use pytest')], 's'), 5)
+ assert response.stop_reason == 'end_turn' and calls == ['session.steer', 'prompt.submit']
+
+
+async def test_only_the_owners_edit_policy_can_be_selected():
+ agent = _agent(AsyncMock())
+ await agent.set_session_mode('default', 's')
+ await agent.set_config_option('edit_approval_policy', 's', 'ask')
+ with pytest.raises(GatewayClientError, match='acp_edit_policy_mutation_unavailable'):
+ await agent.set_session_mode('accept_edits', 's')
+ agent._gateway.rpc.assert_not_awaited()
diff --git a/tests/acp_adapter/test_gateway_session_metadata.py b/tests/acp_adapter/test_gateway_session_metadata.py
new file mode 100644
index 00000000000..a574b006157
--- /dev/null
+++ b/tests/acp_adapter/test_gateway_session_metadata.py
@@ -0,0 +1,107 @@
+"""Editor session metadata and commands on the shipped gateway path (tracker ACP-1/2/3/6/7/11).
+
+An actual ``hermes acp`` stdio process against an ordinary isolated gateway. Main's in-process
+server (``acp_adapter/server.py``, ``acp_adapter/commands.py``) is the reference for each reply.
+"""
+import json
+
+import pytest
+
+from tests.acp_adapter.test_gateway_sessions import editor, viewer
+from tests.waiting import async_wait_until
+
+
+def _updates(acp, sid, kind, start=0):
+ return [frame['params']['update'] for frame in acp.frames[start:]
+ if frame.get('method') == 'session/update' and frame['params'].get('sessionId') == sid
+ and frame['params']['update'].get('sessionUpdate') == kind]
+
+
+async def _reply(acp, sid, text):
+ """The agent text a prompt produced before its response (a command's reply)."""
+ start = len(acp.frames)
+ response = await acp.rpc('session/prompt', sessionId=sid, prompt=[{'type': 'text', 'text': text}])
+ assert response.get('result', {}).get('stopReason') == 'end_turn', (text, response)
+ return ''.join(update['content']['text'] for update in _updates(acp, sid, 'agent_message_chunk', start))
+
+
+async def test_new_session_carries_picker_modes_provenance_and_commands(daemon, tmp_path):
+ async with editor(daemon, tmp_path) as acp:
+ await acp.rpc('initialize', protocolVersion=1, clientCapabilities={})
+ created = await acp.rpc('session/new', cwd=str(tmp_path), mcpServers=[])
+ result = created['result']
+ sid = result['sessionId']
+ assert 'local-wire-stub' in result['models']['currentModelId'], result
+ assert result['modes']['currentModeId'] == 'default', result
+ assert result['_meta']['hermes']['sessionProvenance']['acpSessionId'] == sid, result
+ await async_wait_until(lambda: _updates(acp, sid, 'available_commands_update'))
+ advertised = {c['name'] for c in _updates(acp, sid, 'available_commands_update')[0]['availableCommands']}
+ assert {'help', 'model', 'tools', 'context', 'reset', 'compress', 'steer', 'queue', 'version',
+ 'usage', 'status'} <= advertised
+
+ # Selecting the advertised mode / the owner's own edit policy never fails the editor.
+ assert 'result' in await acp.rpc('session/set_mode', sessionId=sid, modeId='default')
+ assert 'result' in await acp.rpc('session/set_config_option', sessionId=sid,
+ configId='edit_approval_policy', value='ask')
+
+ loaded = await acp.rpc('session/load', sessionId=sid, cwd=str(tmp_path), mcpServers=[])
+ assert loaded['result']['modes']['currentModeId'] == 'default', loaded
+ assert 'local-wire-stub' in loaded['result']['models']['currentModelId'], loaded
+
+
+async def test_editor_commands_reply_and_turns_report_usage_and_title(daemon, tmp_path):
+ async with editor(daemon, tmp_path) as acp:
+ await acp.rpc('initialize', protocolVersion=1, clientCapabilities={})
+ sid = (await acp.rpc('session/new', cwd=str(tmp_path), mcpServers=[]))['result']['sessionId']
+ assert 'Available commands' in await _reply(acp, sid, '/help')
+ assert 'Current model: local-wire-stub' in await _reply(acp, sid, '/model')
+ for read in ('/version', '/status', '/context', '/usage', '/tools'):
+ assert (await _reply(acp, sid, read)).strip(), read
+ assert 'No changes from compression: 0 messages' in await _reply(acp, sid, '/compress')
+
+ start = len(acp.frames)
+ turn = await acp.rpc('session/prompt', sessionId=sid, prompt=[{'type': 'text', 'text': 'WS_SHARED usage'}])
+ assert turn['result']['stopReason'] == 'end_turn', turn
+ # The loopback model reports no token counts; the owner's counters still ride the reply.
+ assert set(turn['result']['usage']) >= {'inputTokens', 'outputTokens', 'totalTokens'}, turn
+ contexts = _updates(acp, sid, 'usage_update', start)
+ assert contexts and contexts[-1]['size'] == 256000, contexts
+
+ async with viewer(daemon) as ws:
+ snapshot = await ws.rpc('session.resume', session_id=sid)
+ await ws.rpc('session.mutate', session_id=sid, request_id='rename-from-ws', operation='rename',
+ expected_revision=snapshot['revision'], payload={'title': 'Renamed elsewhere'})
+ await async_wait_until(lambda: [u for u in _updates(acp, sid, 'session_info_update')
+ if u.get('title') == 'Renamed elsewhere'])
+
+ reset = await _reply(acp, sid, '/reset')
+ assert 'Conversation history cleared' in reset
+ async with viewer(daemon) as ws:
+ assert 'WS_SHARED usage' not in json.dumps((await ws.rpc('session.resume', session_id=sid))['messages'])
+
+
+async def test_thread_main_in_process_acp_wrote_lists_and_loads(daemon, tmp_path):
+ from hermes_state import SessionDB
+ home = daemon[0]
+ # The row main's ``SessionManager.save_session`` wrote: source acp, no gateway route or policy.
+ with SessionDB(db_path=home / 'state.db') as db:
+ db.create_session(session_id='pre-upgrade-acp', source='acp', model='local-wire-stub',
+ model_config={'cwd': str(tmp_path)}, cwd=str(tmp_path))
+ db.append_message('pre-upgrade-acp', 'user', 'LEGACY_EDITOR_QUESTION')
+ db.append_message('pre-upgrade-acp', 'assistant', 'LEGACY_EDITOR_ANSWER')
+ async with editor(daemon, tmp_path) as acp:
+ await acp.rpc('initialize', protocolVersion=1, clientCapabilities={})
+ listed = await acp.rpc('session/list', cwd=str(tmp_path))
+ assert 'pre-upgrade-acp' in [row['sessionId'] for row in listed['result']['sessions']], listed
+ loaded = await acp.rpc('session/load', sessionId='pre-upgrade-acp', cwd=str(tmp_path), mcpServers=[])
+ assert 'result' in loaded, loaded
+ assert 'LEGACY_EDITOR_ANSWER' in json.dumps(acp.frames)
+ turn = await acp.rpc('session/prompt', sessionId='pre-upgrade-acp',
+ prompt=[{'type': 'text', 'text': 'WS_SHARED after upgrade'}])
+ assert turn.get('result', {}).get('stopReason') == 'end_turn', turn
diff --git a/tests/acp_adapter/test_gateway_slash_text.py b/tests/acp_adapter/test_gateway_slash_text.py
index d73017311d7..4a28d1a27b4 100644
--- a/tests/acp_adapter/test_gateway_slash_text.py
+++ b/tests/acp_adapter/test_gateway_slash_text.py
@@ -35,5 +35,5 @@ async def test_registered_command_this_surface_does_not_carry_is_still_refused_l
agent._gateway = AsyncMock()
agent._snapshots["s"] = {}
with pytest.raises(GatewayClientError, match="unsupported_command"):
- await agent.prompt([acp.text_block("/reset")], "s")
+ await agent.prompt([acp.text_block("/rollback")], "s")
agent._gateway.rpc.assert_not_awaited()