The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): send the slash worker's queued next-turn prompt instead of dropping it
Brooklyn Nicholson59ddb98c03cc
diff --git a/tests/tui_gateway/test_protocol.py b/tests/tui_gateway/test_protocol.pyindex 0c88de84781..fc710e1d8a5 100644--- a/tests/tui_gateway/test_protocol.py+++ b/tests/tui_gateway/test_protocol.py@@ -1397,7 +1397,7 @@ class _BannerWorker:def run(self, command):self.calls.append(command)- return "⚡ Loading skill: grilling"+ return "⚡ Loading skill: grilling", ""def close(self):self.closed = True@@ -1511,7 +1511,7 @@ def test_slash_exec_skill_scan_raise_still_runs_registry_commands(server):def run(self, command):self.calls.append(command)- return "verbose ok"+ return "verbose ok", ""def close(self):passdiff --git a/tests/tui_gateway/test_slash_prompt_compose_seed.py b/tests/tui_gateway/test_slash_prompt_compose_seed.pynew file mode 100644index 00000000000..18bb215194a--- /dev/null+++ b/tests/tui_gateway/test_slash_prompt_compose_seed.py@@ -0,0 +1,113 @@+"""Worker-routed slash commands that queue a next-turn prompt must actually send it.++The persistent slash worker runs ``HermesCLI.process_command`` headlessly. Commands+like ``/prompt``/``/compose`` (and ``/blueprint``) park the composed prompt on the+one-shot ``_pending_agent_seed`` for the interactive REPL loop to run — but the worker+has no REPL loop, so the seed was silently dropped: Desktop/TUI ``/prompt`` returned+``(no output)`` and the composed prompt vanished (#107800). The worker must harvest the+seed and the gateway must route it back as a ``{type: "send"}`` dispatch, which both the+Desktop and TUI clients already handle.+"""++from __future__ import annotations++import threading++from tui_gateway import server+++class _FakeCLI:+ """Records the command; simulates /prompt parking the composed text on the seed."""+ console = None++ def __init__(self, seed=None):+ self._pending_agent_seed = seed+ self.commands = []++ def process_command(self, cmd):+ self.commands.append(cmd)+++def _live_session():+ return {"session_key": "seed-key", "running": False, "history": [],+ "history_lock": threading.Lock(), "agent": None, "cwd": ""}+++def test_run_harvests_pending_agent_seed():+ from tui_gateway import slash_worker++ cli = _FakeCLI(seed="Composed in $EDITOR")+ result = slash_worker._run(cli, "/prompt")+ assert result["output"] == ""+ assert result["seed"] == "Composed in $EDITOR"+ # one-shot: the seed is consumed, a second command must not re-send it+ assert cli._pending_agent_seed is None+ result2 = slash_worker._run(cli, "/status")+ assert result2["seed"] == ""+++def test_run_without_seed_returns_empty_seed():+ from tui_gateway import slash_worker++ result = slash_worker._run(_FakeCLI(), "/status")+ assert result == {"output": "", "seed": ""} or (result["output"] and result["seed"] == "")+++def test_empty_command_returns_empty_output_and_seed():+ from tui_gateway import slash_worker++ result = slash_worker._run(_FakeCLI(), "")+ assert result == {"output": "", "seed": ""}+++def test_slash_exec_routes_seed_as_send_dispatch(monkeypatch):+ """slash.exec must return {type: "send", message: <seed>} when the worker harvested one."""+ sid = "seed-sid"+ session = _live_session()+ server._sessions[sid] = session++ class _SeedingWorker:+ def __init__(self, *a, **kw):+ pass++ def run(self, command):+ return ("", "Composed in $EDITOR")++ def close(self):+ pass++ monkeypatch.setattr(server, "_SlashWorker", _SeedingWorker)+ try:+ resp = server._methods["slash.exec"](1, {"session_id": sid, "command": "/prompt"})+ finally:+ server._sessions.pop(sid, None)++ assert "error" not in resp, resp+ assert resp["result"]["type"] == "send"+ assert resp["result"]["message"] == "Composed in $EDITOR"+++def test_slash_exec_plain_output_unchanged_when_no_seed(monkeypatch):+ sid = "seed-sid-plain"+ session = _live_session()+ server._sessions[sid] = session++ class _PlainWorker:+ def __init__(self, *a, **kw):+ pass++ def run(self, command):+ return ("worker says hi", "")++ def close(self):+ pass++ monkeypatch.setattr(server, "_SlashWorker", _PlainWorker)+ try:+ resp = server._methods["slash.exec"](1, {"session_id": sid, "command": "/journey"})+ finally:+ server._sessions.pop(sid, None)++ assert "error" not in resp, resp+ assert resp["result"]["output"] == "worker says hi"+ assert "type" not in resp["result"]diff --git a/tests/tui_gateway/test_slash_worker_ansi.py b/tests/tui_gateway/test_slash_worker_ansi.pyindex 3c061c4d756..410d365e0b6 100644--- a/tests/tui_gateway/test_slash_worker_ansi.py+++ b/tests/tui_gateway/test_slash_worker_ansi.py@@ -7,6 +7,7 @@ from __future__ import annotationsclass _FakeCLI:console = None+ _pending_agent_seed = Nonedef process_command(self, cmd: str) -> None:import sys@@ -19,5 +20,6 @@ def test_run_strips_ansi_from_output():out = slash_worker._run(_FakeCLI(), "/anything")- assert "\x1b[" not in out- assert out == "colored plain"+ assert "\x1b[" not in out["output"]+ assert out["output"] == "colored plain"+ assert out["seed"] == ""diff --git a/tests/tui_gateway/test_slash_worker_provider.py b/tests/tui_gateway/test_slash_worker_provider.pyindex 8b1409f3f62..7fe89fb51a1 100644--- a/tests/tui_gateway/test_slash_worker_provider.py+++ b/tests/tui_gateway/test_slash_worker_provider.py@@ -63,7 +63,7 @@ def test_slash_exec_spawns_with_the_live_agent_provider(monkeypatch):self.stderr_tail = []def run(self, command):- return "ok"+ return "ok", ""def close(self):passdiff --git a/tui_gateway/methods_slash.py b/tui_gateway/methods_slash.pyindex 132b57a8fb9..db81dc231aa 100644--- a/tui_gateway/methods_slash.py+++ b/tui_gateway/methods_slash.py@@ -117,19 +117,6 @@ def _format_live_history_output(sid: str, session: dict, arg: str) -> str:return "\n".join(lines)-def _format_live_prompt_output(sid: str, session: dict, arg: str) -> str:- agent = session.get("agent")- mirror = _metadata_mirror(session)- if agent is None and "system_prompt" not in mirror:- return _NO_AGENT- prompt = (- mirror.get("system_prompt") or getattr(agent, "ephemeral_system_prompt", None)- or getattr(agent, "_cached_system_prompt", None) or "")- if not prompt:- return "Current system prompt is not built yet; send a message first."- return f"Current system prompt:\n{prompt}"--def _format_live_context_output(sid: str, session: dict, arg: str) -> str:from collections import Countertry:@@ -217,7 +204,6 @@ _LIVE_SLASH_OUTPUT = {"usage": (_NO_AGENT_USAGE, _format_live_usage_output),"review": (None, _format_live_review_output),"history": ("No conversation history yet.", _format_live_history_output),- "prompt": (_NO_AGENT, _format_live_prompt_output),"status": (None, _format_live_status_output),"context": ("Conversation is empty (no messages yet).", _format_live_context_output),"tools": ("No tools available.", _format_live_tools_output),@@ -250,7 +236,7 @@ def _live_slash_command_output(sid: str, session: Optional[dict], name: str, arg# Read-then-mutate live agent/session state that a running turn is using; rejected# while running (parity with session.compress / session.undo and the gateway's# running-agent /model guard).-_MUTATES_WHILE_RUNNING = frozenset({"model", "personality", "prompt", "compress"})+_MUTATES_WHILE_RUNNING = frozenset({"model", "personality", "compress"})def _compress_live_with_feedback(sid: str, session: dict, agent, arg: str, *, snapshot_kwargs: bool) -> str:@@ -316,13 +302,6 @@ def _mirror_personality(sid, session, agent, arg) -> None:_apply_personality_to_session(sid, session, new_prompt, pname)-def _mirror_prompt(sid, session, agent, arg) -> None:- if agent:- cfg = _load_cfg()- agent.ephemeral_system_prompt = _prompt_text((cfg.get("agent") or {}).get("system_prompt", "")) or None- agent._cached_system_prompt = None--_FAST_TIERS = {"fast": "priority", "on": "priority", "normal": None, "off": None, "auto": "auto", "cold": "cold","ultrafast": "ultrafast"}@@ -350,7 +329,7 @@ def _mirror_stop(sid, session, agent, arg) -> None:_SLASH_MIRRORS = {"model": lambda sid, session, agent, arg: (_apply_model_switch(sid, session, arg).get("warning", "") if arg and agent else ""),- "approvals": _mirror_approvals, "personality": _mirror_personality, "prompt": _mirror_prompt,+ "approvals": _mirror_approvals, "personality": _mirror_personality,"compress": lambda sid, session, agent, arg: (_compress_live_with_feedback(sid, session, agent, arg, snapshot_kwargs=False) if agent else ""),"fast": _mirror_fast,diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.pyindex 902327a015e..cd1a13464b1 100644--- a/tui_gateway/methods_tools.py+++ b/tui_gateway/methods_tools.py@@ -1061,7 +1061,12 @@ def _(rid, params: dict) -> dict:except Exception as e:return _err(rid, 5030, f"slash worker start failed: {e}")try:- payload = {"output": worker.run(cmd) or "(no output)"}+ output, seed = worker.run(cmd)+ if seed:+ # /prompt//blueprint composed a next-turn prompt in the worker; route it as a+ # send dispatch (both Desktop and TUI clients already handle {type:"send"}).+ return _ok(rid, {"type": "send", "message": seed})+ payload = {"output": output or "(no output)"}if warning := _mirror_slash_side_effects(sid, session, cmd):payload["warning"] = warningif base in _SESSION_CONTROL_SLASHES:diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex be53df3c0f5..66e1b5724d4 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -299,7 +299,12 @@ class _SlashWorker:if text := line.rstrip("\n"):self.stderr_tail = (self.stderr_tail + [text])[-80:]- def run(self, command: str) -> str:+ def run(self, command: str) -> tuple[str, str]:+ """Run one command → ``(output, seed)``.++ ``seed`` is a next-turn prompt a command like /prompt parked on the worker's+ CLI (``_pending_agent_seed``); empty for old workers that don't reply one.+ """if self.proc.poll() is not None:raise RuntimeError("slash worker exited")with self._lock:@@ -318,7 +323,7 @@ class _SlashWorker:continueif not msg.get("ok"):raise RuntimeError(msg.get("error", "slash worker failed"))- return str(msg.get("output", "")).rstrip()+ return str(msg.get("output", "")).rstrip(), str(msg.get("seed", "") or "")raise RuntimeError(f"slash worker closed pipe{': ' + chr(10).join(self.stderr_tail[-8:]) if self.stderr_tail else ''}")diff --git a/tui_gateway/slash_worker.py b/tui_gateway/slash_worker.pyindex 9383b351284..aaff46ef34c 100644--- a/tui_gateway/slash_worker.py+++ b/tui_gateway/slash_worker.py@@ -97,10 +97,17 @@ def _refuse_skill_slash(command: str) -> None:raise SkillSlashRefused(base)-def _run(cli: HermesCLI, command: str) -> str:+def _run(cli: HermesCLI, command: str) -> dict:+ """Run one command; return ``{"output", "seed"}``.++ ``seed`` is the one-shot ``_pending_agent_seed`` a command like /prompt or+ /blueprint parks for "run this as the next agent turn". The interactive REPL+ loop consumes it (cli.py); this worker has no REPL, so the seed is harvested+ here and routed back to the gateway, which sends it as the next turn (#107800).+ """cmd = (command or "").strip()if not cmd:- return ""+ return {"output": "", "seed": ""}_refuse_skill_slash(cmd)buf = io.StringIO()# Rich Console captures its file handle at construction, so redirect_stdout won't affect it; swap@@ -118,7 +125,9 @@ def _run(cli: HermesCLI, command: str) -> str:# Desktop chat bubbles render plain text, not ANSI. A command that emits Rich color (e.g. /journey# under the gateway's inherited COLORTERM) would leak raw escapes; strip at this single choke point.from tools.ansi_strip import strip_ansi- return strip_ansi(buf.getvalue().rstrip())+ output = strip_ansi(buf.getvalue().rstrip())+ seed, cli._pending_agent_seed = getattr(cli, "_pending_agent_seed", None) or "", None+ return {"output": output, "seed": seed}def _sw_log(reason: str) -> None:@@ -167,7 +176,8 @@ def main():try:req = json.loads(line)rid = req.get("id")- _reply(id=rid, ok=True, output=_run(cli, req.get("command", "")))+ result = _run(cli, req.get("command", ""))+ _reply(id=rid, ok=True, output=result["output"], seed=result["seed"])except Exception as e:_reply(id=rid, ok=False, error=str(e))finally: