The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): bring the manage_connections card back to the classic CLI (#142039)
Teknium54455f3ec177
diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.pyindex 15c5702a885..d9ded68de9b 100644--- a/hermes_cli/cli_agent_setup_mixin.py+++ b/hermes_cli/cli_agent_setup_mixin.py@@ -716,6 +716,7 @@ class CLIAgentSetupMixin:openrouter_min_coding_score=self._openrouter_min_coding_score,session_id=self.session_id, platform="cli", session_db=self._session_db,clarify_callback=clarify_callback, connection_callback=connection_callback,+ connection_update_callback=None if single_query_mode else self._connection_on_change,# The gateway's model-guard refusal is asked like main's own guard; -q cannot answer it.model_confirm_callback=None if single_query_mode else self._confirm_owner_model_switch,# Another viewer answering the gateway's clarify/sudo/secret request closes this modal.diff --git a/hermes_cli/cli_modal_mixin.py b/hermes_cli/cli_modal_mixin.pyindex 684d29fc793..d3e0ab82cfa 100644--- a/hermes_cli/cli_modal_mixin.py+++ b/hermes_cli/cli_modal_mixin.py@@ -594,30 +594,11 @@ class CLIModalMixin:self._paint_now()# --- Connection setup --------------------------------------------------- def _connection_operation(self, payload):- from tools.connectors import live-- session_key = getattr(self, "session_id", "") or ""- op_id = str(payload.get("op_id") or "")- return live.get(session_key, op_id) or live.current(session_key)-- def _connection_install_hook(self) -> bool:- from tools.connectors.operation import ConnectionOperation-- if ConnectionOperation.on_change is not None:- return False- ConnectionOperation.on_change = self._connection_on_change- return True-- def _connection_restore_hook(self) -> None:- from tools.connectors.operation import ConnectionOperation-- if ConnectionOperation.on_change == self._connection_on_change:- ConnectionOperation.on_change = None-+ # The gateway runs the manage_connections operation; this card renders its connection.request /+ # connection.update events (delivered on the agent thread) and answers through the agent's+ # connection.respond / connectors.connect calls, never an in-process operation.def _connection_close(self) -> None:self._connection_state = None- self._connection_restore_hook()self._restore_modal_input_snapshot()self._paint_now()@@ -713,78 +694,83 @@ class CLIModalMixin:def _connection_callback(self, payload):if not isinstance(payload, dict):return- self._capture_modal_input_snapshot()- installed = self._connection_install_hook()- self._connection_show_target(payload, 0)state = self._connection_state- if state is None:+ if state is not None and state["payload"].get("op_id") == payload.get("op_id"):+ # A replay-gap re-open of the card already shown: apply it as an update so the active+ # target, field and unsent input survive; an identical snapshot changes nothing.+ if int(payload.get("seq") or 0) > int(state["payload"].get("seq") or 0):+ self._connection_on_change(payload)return- state["owns_hook"] = installed- state["tool_thread_id"] = threading.current_thread().ident- if state["phase"] != "waiting":+ if state is None:+ self._capture_modal_input_snapshot()+ targets = payload.get("targets") or []+ # Open on the first app that still needs the user, not one already connected or skipped.+ index = next((i for i, item in enumerate(targets) if item.get("state") not in {"connected", "skipped"}), 0)+ self._connection_show_target(payload, index)+ state = self._connection_state+ if state is not None and state["phase"] != "waiting":self._ring_bell(prompt=True, context=t("cli.connect.bell_context"))- return++ def _connection_send(self, call, *args) -> None:+ """One card answer to the gateway, off the UI thread; its outcome arrives as connection.update."""+ state = self._connection_state+ agent = getattr(self, "agent", None)+ if not state or agent is None:+ self._connection_close()+ return+ op_id = state["payload"].get("op_id")++ def _run() -> None:+ from hermes_cli.gateway_client import GatewayClientError+ try:+ getattr(agent, call)(*args)+ except GatewayClientError as exc: # the gateway refused or was unreachable: say so on the card+ current = self._connection_state+ if current and current["payload"].get("op_id") == op_id:+ current["target"] = {**current["target"], "detail": str(exc) or t("cli.connect.cannot_restart")}+ current["phase"] = "failed"+ self._paint_now()++ from agent.memory_provider import spawn_context_thread+ spawn_context_thread(_run, name="hermes-connection-answer").start()def _connection_answer(self, *, approve: bool) -> None:state = self._connection_stateif not state:returntarget = state["target"]- operation = self._connection_operation(state["payload"])- if operation is None:- self._connection_close()- returnname = str(target.get("name") or "")answer = {"name": name, "status": "approved" if approve else "skipped"}if approve:answer["env"] = dict(state.get("drafts", {}).get(name, {}))- from tools.connectors.mcp import apply_answer-- # The backend applies the answer on this thread, and its change hook sets the next phase- # (the URL step, the form again for a missing field) before apply_answer returns. Set the- # waiting phase first so it cannot overwrite that.state["phase"] = "waiting"- apply_answer(operation, json.dumps({"targets": [answer]}))self._paint_now()+ self._connection_send("connection_respond", state["payload"].get("op_id"), {"targets": [answer]})def _connection_retry(self) -> None:state = self._connection_stateif not state:return- operation = self._connection_operation(state["payload"])- if operation is None:- self._connection_close()- returntarget = state["target"]- if target.get("kind") == "connector" and target.get("state") in {"failed", "expired"}:- from tools.connectors.run import reissue-- state["phase"] = "waiting"- if reissue(operation, [str(target.get("name") or "")]) is not None:- target["detail"] = t("cli.connect.cannot_restart")- state["phase"] = "failed"- self._paint_now()- return- if target.get("state") in {"pending", "failed", "expired"}:- # Connect on a failed row is the same attempt with the values now in the draft.+ if not (target.get("kind") == "connector" and target.get("state") in {"failed", "expired"}) \+ and target.get("state") in {"pending", "failed", "expired"}:+ # Connect on a pending or failed install row is the same attempt with the draft's values.self._connection_answer(approve=True)return- from tools.connectors.mcp import retry-+ # A dead sign-in link (or any other re-run): the gateway re-mints it on the open operation.state["phase"] = "waiting"- retry(operation, [str(target.get("name") or "")])self._paint_now()+ self._connection_send("connection_retry", str(target.get("name") or ""))def _connection_continue(self) -> None:+ # Stays open (waiting) until the gateway's settling update closes it, so a refused answer+ # shows on the card instead of vanishing with it.state = self._connection_stateif not state:return- operation = self._connection_operation(state["payload"])- if operation is not None:- from tools.connectors.mcp import apply_answer-- apply_answer(operation, json.dumps({"settled_by": "continue"}))- self._connection_close()+ state["phase"] = "waiting"+ self._paint_now()+ self._connection_send("connection_respond", state["payload"].get("op_id"), {"settled_by": "continue"})def _connection_open_url(self) -> None:state = self._connection_state@@ -795,21 +781,21 @@ class CLIModalMixin:self._connection_answer(approve=False)def _connection_interrupt(self) -> None:- state = self._connection_state- if state:- from tools.interrupt import set_interrupt-- operation = self._connection_operation(state["payload"])- set_interrupt(True, thread_id=state.get("tool_thread_id"))- if operation is not None:- operation.wake.set()+ # The turn's interrupt reaches the gateway, which ends the operation; only the card is ours.self._connection_close()- def _connection_on_change(self, operation, _change, snapshot) -> None:+ def _connection_on_change(self, snapshot) -> None:state = self._connection_state- if not state or operation.op_id != state["payload"].get("op_id"):+ if not state or not isinstance(snapshot, dict):+ return+ if "op_id" not in snapshot and snapshot.get("settled"):+ self._connection_close() # a replay-gap recovery found no open operation: the card is stalereturn- if snapshot.get("settled_at") is not None:+ if snapshot.get("op_id") != state["payload"].get("op_id"):+ return+ if int(snapshot.get("seq") or 0) < int(state["payload"].get("seq") or 0):+ return # an older frame than the one the card holds+ if snapshot.get("settled") or snapshot.get("settled_at") is not None:self._connection_close()returnactive_name = state["target"].get("name")@@ -824,6 +810,9 @@ class CLIModalMixin:elif target_state == "failed":state["phase"] = "failed"elif target_state == "pending" and self._connection_fields(target):+ if state["phase"] == "form":+ state["payload"] = snapshot # still being filled in: keep the field and unsent input+ return# The backend refused the answer because a required field is still empty: reopen the# form on the first one it named, over the draft the panel kept.missing = {field.get("name") for field in self._connection_fields(target)}diff --git a/hermes_cli/gateway_agent.py b/hermes_cli/gateway_agent.pyindex 14214673a71..61aa0457283 100644--- a/hermes_cli/gateway_agent.py+++ b/hermes_cli/gateway_agent.py@@ -93,6 +93,7 @@ class GatewayAgent:def __init__(self, *, session_db=None, session_id=None, model=None, provider=None, base_url=None,api_mode=None, max_iterations=90, quiet_mode=True, tool_progress_mode="all",reasoning_config=None, service_tier=None, clarify_callback=None, connection_callback=None,+ connection_update_callback=None,reasoning_callback=None, thinking_callback=None, tool_progress_callback=None,tool_start_callback=None, tool_complete_callback=None, stream_delta_callback=None,tool_gen_callback=None, notice_callback=None, notice_clear_callback=None,@@ -114,7 +115,10 @@ class GatewayAgent:self.quiet_mode = quiet_modeself._service_tier = Noneself.clarify_callback = clarify_callback+ # The manage_connections card: the gateway runs the operation and streams connection.request /+ # connection.update; the card answers through connection_respond / connection_retry.self.connection_callback = connection_callback+ self.connection_update_callback = connection_update_callbackself._reasoning_callback = Noneself._show_reasoning_sent = Noneself.thinking_callback = thinking_callback@@ -894,6 +898,7 @@ class GatewayAgent:if row.get("status") == "unknown":return lost # its completion was the one the hole lost: no other is owedturn.gapped |= row.get("status") != "queued" # one still queued lost nothing+ self._restore_connection_card(snapshot.get("pending_connection"))for prompt in snapshot.get("prompts") or []:if row.get("status") == "started" and prompt.get("execution_generation") == row.get("execution_generation") \and prompt.get("prompt_id") not in turn.answered and not stop():@@ -1103,6 +1108,33 @@ class GatewayAgent:execution_generation=payload.get("execution_generation", self._generation),prompt_id=payload.get("prompt_id"), answer=str(answer))+ def _on_connection_request(self, payload, stream_callback, starts):+ if self.connection_callback is not None:+ self.connection_callback(payload)++ def _on_connection_update(self, payload, stream_callback, starts):+ if self.connection_update_callback is not None:+ self.connection_update_callback(payload)++ def _restore_connection_card(self, pending):+ """After a replay gap, the resume snapshot's open operation: (re)open the card from it, or+ close a stale card when none remains (the gap may have eaten the request or the settle)."""+ if pending:+ if self.connection_callback is not None:+ self.connection_callback(pending)+ elif self.connection_update_callback is not None:+ self.connection_update_callback({"settled": True})++ def connection_respond(self, op_id, result):+ """The card's answer to the gateway's open operation (``connection.respond``); returns its result."""+ return self.connection.call("connection.respond", op_id=op_id, result=result,+ owner={"type": "session", "session_id": self.session_id})++ def connection_retry(self, name):+ """The card's Try again on a failed or expired row: the gateway re-mints it on the open operation."""+ return self.connection.call("connectors.connect", connectors=[name], reconnect=True,+ owner={"type": "session", "session_id": self.session_id})+def _answer_request(self, frame):"""A gateway server→client request (``sudo``, ``secret``, ``clarify``): main's own modalanswers it on this (agent) thread, through the callback HermesCLI registered for the turn; the@@ -1409,4 +1441,6 @@ _HANDLERS = {"review.summary": GatewayAgent._on_review_summary,"approval.request": GatewayAgent._on_approval,"clarify.request": GatewayAgent._on_clarify,+ "connection.request": GatewayAgent._on_connection_request,+ "connection.update": GatewayAgent._on_connection_update,}diff --git a/tests/hermes_cli/test_cli_clarify_batch.py b/tests/hermes_cli/test_cli_clarify_batch.pyindex 21cb624a02a..36c459bdc11 100644--- a/tests/hermes_cli/test_cli_clarify_batch.py+++ b/tests/hermes_cli/test_cli_clarify_batch.py@@ -223,10 +223,12 @@ class TestClarifyBatchPanel:cli._capture_modal_input_snapshot = MagicMock()cli._restore_modal_input_snapshot = MagicMock()cli._ring_bell = MagicMock()- cli.session_id = "session"- operation = MagicMock(op_id="op")+ sent = threading.Event()+ cli.agent = MagicMock()+ cli.agent.connection_respond.side_effect = lambda *a: sent.set()payload = {"op_id": "op",+ "seq": 1,"targets": [{"name": "asana","state": "pending",@@ -237,30 +239,48 @@ class TestClarifyBatchPanel:],}],}- connection_result = {}- with patch.object(cli, "_connection_operation", return_value=operation), patch(- "tools.connectors.mcp.apply_answer"- ) as apply_answer:- connection_thread = threading.Thread(- target=lambda: connection_result.setdefault("value", cli._connection_callback(payload)), daemon=True- )- connection_thread.start()- connection_thread.join(timeout=2)- assert not connection_thread.is_alive()- assert connection_result["value"] is None- state = cli._connection_state- state["drafts"]["asana"]["CLIENT_SECRET"] = "never-render-this"- assert "never-render-this" not in "\n".join(cli._connection_render_lines())- assert f"Client secret*: {t('cli.connect.secret_set')}" in cli._connection_render_lines()- cli._connection_answer(approve=True)-- sent = json.loads(apply_answer.call_args.args[1])- assert sent == {"targets": [{+ cli._connection_callback(payload)+ state = cli._connection_state+ state["drafts"]["asana"]["CLIENT_SECRET"] = "never-render-this"+ assert "never-render-this" not in "\n".join(cli._connection_render_lines())+ assert f"Client secret*: {t('cli.connect.secret_set')}" in cli._connection_render_lines()+ cli._connection_answer(approve=True)+ assert sent.wait(2)++ # The answer goes to the gateway's operation, not an in-process one.+ assert cli.agent.connection_respond.call_args.args == ("op", {"targets": [{"name": "asana","status": "approved","env": {"CLIENT_ID": "default-id", "CLIENT_SECRET": "never-render-this"},- }]}- cli._connection_close()+ }]})+ # The gateway's settling connection.update closes the card.+ cli._connection_on_change({"op_id": "op", "seq": 2, "settled": True, "targets": []})+ assert cli._connection_state is None+++ def test_connection_card_opens_on_the_unfinished_app_and_a_reopen_keeps_its_draft(self):+ cli = _make_cli_stub()+ cli._connection_state = None+ cli._capture_modal_input_snapshot = MagicMock()+ cli._restore_modal_input_snapshot = MagicMock()+ cli._ring_bell = MagicMock()+ form = [{"name": "TOKEN", "prompt": "Token", "required": True}]+ payload = {"op_id": "op", "seq": 4, "targets": [+ {"name": "linear", "state": "connected"},+ {"name": "asana", "state": "pending", "required_env": form},+ ]}+ cli._connection_callback(payload)+ assert cli._connection_state["target"]["name"] == "asana"+ cli._connection_state["drafts"]["asana"]["TOKEN"] = "typed-not-sent"+ cli._connection_callback(dict(payload)) # a replay-gap recovery re-sends the same snapshot+ assert cli._connection_state["target"]["name"] == "asana"+ assert cli._connection_state["drafts"]["asana"]["TOKEN"] == "typed-not-sent"+ cli._connection_sync_input_buffer = MagicMock()+ cli._connection_callback({**payload, "seq": 5}) # ...or a newer one, the form still open+ assert cli._connection_state["phase"] == "form"+ assert cli._connection_state["drafts"]["asana"]["TOKEN"] == "typed-not-sent"+ cli._connection_sync_input_buffer.assert_not_called()+ assert cli._capture_modal_input_snapshot.call_count == 1class TestClarifyBatchNavigation:diff --git a/tests/hermes_cli/test_cli_gateway_model_scope.py b/tests/hermes_cli/test_cli_gateway_model_scope.pyindex 745bffb4560..79ba9b53942 100644--- a/tests/hermes_cli/test_cli_gateway_model_scope.py+++ b/tests/hermes_cli/test_cli_gateway_model_scope.py@@ -110,6 +110,7 @@ def _prepare_for_chat(monkeypatch, cli_mod, stub):stub._single_query_mode = Falsestub._clarify_callback = Nonestub._connection_callback = None+ stub._connection_on_change = Nonestub._confirm_owner_model_switch = lambda refusal: Falsestub._withdraw_gateway_modal = lambda method: Nonestub._current_reasoning_callback = lambda: Nonediff --git a/tests/hermes_cli/test_gateway_agent.py b/tests/hermes_cli/test_gateway_agent.pyindex 76d08218ea0..856689702d6 100644--- a/tests/hermes_cli/test_gateway_agent.py+++ b/tests/hermes_cli/test_gateway_agent.py@@ -144,6 +144,20 @@ def test_approval_request_calls_cli_approval_callback_then_responds(make_agent):assert respond == {"session_id": SID, "execution_generation": 7, "prompt_id": "p1", "choice": "once"}+def test_connection_card_events_reach_the_cli_card(make_agent):+ """The gateway runs manage_connections; its card events must reach the CLI's card callbacks."""+ opened, updates = [], []+ request = {"op_id": "op1", "seq": 1, "deadline_at": 0, "timeout_seconds": 300,+ "targets": [{"name": "linear", "kind": "mcp", "action": "install", "state": "pending"}]}+ update = {**request, "seq": 2, "settled": False}+ agent, _ = make_agent(+ [frame("connection.request", request), frame("connection.update", update),+ frame("message.complete", {"text": "ok", "outcome": "completed"})],+ connection_callback=opened.append, connection_update_callback=updates.append)+ agent.run_conversation("connect linear")+ assert opened == [request] and updates == [update]++def test_interrupt_sends_session_interrupt_and_settles_interrupted(make_agent):agent, client = make_agent([frame("message.delta", {"text": "w001 "})] + ["wait"] * 20,diff --git a/tests/hermes_cli/test_gateway_agent_replay_gap.py b/tests/hermes_cli/test_gateway_agent_replay_gap.pyindex f0c6c8021c9..38bfc047125 100644--- a/tests/hermes_cli/test_gateway_agent_replay_gap.py+++ b/tests/hermes_cli/test_gateway_agent_replay_gap.py@@ -158,3 +158,23 @@ def test_gap_completes_the_voice_stream_without_terminal_streaming(agents):result = agent.run_conversation("q", stream_callback=spoken.append)assert not result["failed"] and result["final_response"] == finalassert "".join(spoken) == final++[email protected]("pending", [{"op_id": "op1", "seq": 3, "targets": [{"name": "linear", "state": "initiated"}]}, None])+def test_gap_recovery_restores_or_clears_the_connection_card(agents, monkeypatch, pending):+ """A gap can eat the card's connection.request or its settling update: the resume snapshot's+ pending_connection re-opens the card, and its absence closes a stale one."""+ opened, updates, final = [], [], "done"+ agent, client = agents([GAP], result={"final_response": final, "completed": True},+ connection_callback=opened.append, connection_update_callback=updates.append)+ original = client.rpc++ async def rpc(method, **params):+ if method == "session.resume":+ await client.events.put(frame("message.complete", {"text": final, "outcome": "completed"}))+ return {"pending": [{"admission_id": "adm-1", "status": "started"}], "pending_connection": pending}+ return await original(method, **params)++ monkeypatch.setattr(client, "rpc", rpc)+ assert run_turn(agent, "connect linear", 5) is not None+ assert (opened, updates) == (([pending], []) if pending else ([], [{"settled": True}]))