gateway_chat_view.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  1. """Classic terminal presentation of authority events and fenced controls."""
  2. import asyncio
  3. from contextlib import suppress
  4. import logging
  5. import sys
  6. import uuid
  7. from hermes_cli.gateway_client import GatewayClientError
  8. logger = logging.getLogger(__name__)
  9. _PREVIEW_CHARS = 80
  10. def _pending_preview(text):
  11. """One terminal-safe line of a pending admission's prompt: escape sequences removed, every
  12. other non-printable (C0/C1, bidi and zero-width format chars, newlines) folded to a space,
  13. capped at ``_PREVIEW_CHARS``. Empty when the row carries no text."""
  14. from tools.ansi_strip import strip_ansi
  15. if not isinstance(text, str):
  16. return ""
  17. line = " ".join("".join(ch if ch.isprintable() else " " for ch in strip_ansi(text)).split())
  18. if len(line) > _PREVIEW_CHARS:
  19. line = line[:_PREVIEW_CHARS - 1] + "…"
  20. return line
  21. def _quoted(row, fallback):
  22. """A pending row's own line: its quoted, indented prompt (so it can never start with
  23. ``/discard``), or ``fallback`` naming its id when it carries no text."""
  24. preview = _pending_preview(row.get("text"))
  25. return f' "{preview}"' if preview else f" ({fallback} {row['admission_id']})"
  26. _UNKNOWN_OUTCOME = ("Hermes couldn't confirm how this turn ended (usually because it restarted mid-turn). "
  27. "Resume this session and use the /discard <id> command it shows to drop the turn. "
  28. "Don't send the same message again until you've checked.")
  29. _BLOCKING_CONTROL_EVENTS = frozenset({
  30. "approval.request", "approval.settled", "clarify.request", "clarify.settled",
  31. "session.info",
  32. })
  33. def pending_lines(pending, *, interactive=True):
  34. """The owner's pending admissions as shown on attach (the classic CLI shows them before a turn).
  35. A lost turn is never replayed, so the person must be told what it was and the exact command
  36. that drops it; a queued prompt is not in the transcript yet, so it is quoted too. A one-shot
  37. (``interactive=False``) cannot take ``/discard``, so its caller names the remedy instead."""
  38. lost = [row for row in pending if row["status"] == "unknown"]
  39. queued = [row for row in pending if row["status"] == "queued"]
  40. lines = []
  41. if len(lost) == 1:
  42. lines.append("⏸ This chat is paused. Hermes couldn't confirm how the last turn ended "
  43. "(usually because it restarted mid-turn):")
  44. if _pending_preview(lost[0].get("text")):
  45. lines.append(_quoted(lost[0], "lost turn"))
  46. lines.append(" Hermes won't re-run it by itself, since it may already have done part of the work.")
  47. if interactive:
  48. lines += [" To drop it and continue, type:", f"/discard {lost[0]['admission_id']}"]
  49. elif lost:
  50. lines.append(f"⏸ This chat is paused. Hermes couldn't confirm how {len(lost)} turns ended "
  51. "(usually because it restarted mid-turn):")
  52. lines.append(" Hermes won't re-run them by itself, since they may already have done part of the work.")
  53. if interactive:
  54. lines.append(" To continue, drop each one with the /discard line under it:")
  55. for row in lost:
  56. lines.append(_quoted(row, "lost turn"))
  57. if interactive:
  58. lines.append(f"/discard {row['admission_id']}")
  59. if queued:
  60. count = "1 message is" if len(queued) == 1 else f"{len(queued)} messages are"
  61. after = {0: "to run", 1: "and will run once that turn is dropped"}.get(
  62. len(lost), "and will run once those turns are dropped")
  63. lines.append(f" {count} waiting {after}:")
  64. lines.extend(_quoted(row, "queued message") for row in queued)
  65. return lines
  66. def lost_admission(snapshot, admission_id):
  67. """``/discard``'s row: the resume snapshot is the only source of the generation the authority
  68. stamped on a turn lost across an owner restart."""
  69. lost = next((row for row in snapshot.get("pending", [])
  70. if row["admission_id"] == admission_id and row["status"] == "unknown"), None)
  71. if lost is None:
  72. raise GatewayClientError("No unknown (lost) admission with that id; resume to refresh")
  73. return lost
  74. class GatewayChatView:
  75. def __init__(self, client, snapshot, *, quiet=False, emitter=None, usage_file=None):
  76. self.usage_file = usage_file
  77. self.client = client
  78. self.session_id = snapshot["stored_session_id"]
  79. self.generation = snapshot.get("execution_generation", 0)
  80. self.prompts = {p["prompt_id"]: p for p in snapshot.get("prompts", [])}
  81. self.pending = snapshot.get("pending", [])
  82. self.model = str((snapshot.get("info") or {}).get("model") or "Hermes").split("/")[-1]
  83. # ``--format stream-json``: stdout belongs to the JSONL protocol, so every human line is
  84. # replaced by an emitter event and the terminal record carries the exit code.
  85. self.emitter = emitter
  86. self.quiet = quiet or emitter is not None
  87. self.finite = False
  88. self.unattended = False # `-z`: the classic one-shot auto-approves; `-q` stays single-query
  89. self.resume_footer = False # `chat -q` without -Q: main's "Resume this session with:" block
  90. self.launch_api_key = None # `--api-key` of this terminal's launch; never durable (/new reuses it)
  91. self.finite_admission = None
  92. self._finite_events = []
  93. self.streams = {}
  94. self.completions = {}
  95. # ``gateway_replay_gap``: admission -> the reply segment shown when a gap cut it; own unsettled turns.
  96. self.cut, self.mine, self.gaps, self._attaching = {}, {}, 0, asyncio.Lock()
  97. self.changed = asyncio.Event()
  98. self.failure = None
  99. # Set once with ``failure``: the interactive composer races its line read against it so a
  100. # dead owner ends the REPL immediately instead of on the next keypress.
  101. self.failed = asyncio.Event()
  102. from hermes_cli.gateway_mutations import PreparedMutations
  103. self.mutations = PreparedMutations()
  104. # The interactive composer (set by ``run``); None in one-shot / non-TTY runs, where a
  105. # guarded model switch stays a refusal instead of a prompt.
  106. self._composer = None
  107. # `/undo` puts the removed message back in the composer for the next prompt.
  108. self.prefill = ""
  109. def unknown_admissions(self):
  110. return [row["admission_id"] for row in self.pending if row["status"] == "unknown"]
  111. def show_pending(self):
  112. for line in pending_lines(self.pending, interactive=not self.finite):
  113. print(line, file=sys.stderr)
  114. def show_prompt(self, prompt):
  115. print(f"\n{prompt.get('description') or prompt.get('question') or 'Approval required'}", file=sys.stderr)
  116. if prompt.get("command"):
  117. print(prompt["command"], file=sys.stderr)
  118. command = "/approve" if prompt["kind"] == "approval" else "/answer"
  119. print(f"{command} {prompt['prompt_id']} <{'|'.join(prompt.get('choices', [])) or 'answer'}>", file=sys.stderr)
  120. async def render(self):
  121. while True:
  122. event = await self.client.events.get()
  123. if isinstance(event, Exception):
  124. self._fail(event)
  125. return
  126. params = event.get("params", {})
  127. if params.get("session_id") != self.session_id:
  128. continue
  129. kind, payload = params.get("type"), params.get("payload", {})
  130. self.generation = params.get("execution_generation", self.generation)
  131. if kind == "session.replay_gap":
  132. await self._reattach()
  133. if self.failure:
  134. return
  135. continue
  136. admission = params.get("admission_id") or payload.get("admission_id")
  137. if self.finite and kind in _BLOCKING_CONTROL_EVENTS:
  138. # Gates and unknown executions block the session FIFO, not merely one
  139. # admission's output. Track them even when another admission owns the
  140. # event so a queued one-shot can detach instead of waiting forever.
  141. self._dispatch_event(kind, admission, payload)
  142. self.changed.set()
  143. continue
  144. if self.finite and admission:
  145. if self.finite_admission is None:
  146. # The owner can publish before prompt.submit's receipt reaches this client.
  147. # Hold admission-scoped output until we know which admission this invocation owns.
  148. self._finite_events.append((kind, admission, payload))
  149. continue
  150. if admission != self.finite_admission:
  151. continue
  152. self._dispatch_event(kind, admission, payload)
  153. self.changed.set()
  154. def _fail(self, error):
  155. self.failure = error
  156. self.failed.set()
  157. self.changed.set()
  158. async def _reattach(self):
  159. """The owner retired this view's subscription; its turns run on. Re-attach (a refusal fails the
  160. view as before), show the controls the hole hid, and recover the turns in admission order."""
  161. sid = self.session_id
  162. async with self._attaching: # a submit acked meanwhile recovers against this snapshot, which covers it
  163. self.gaps += 1
  164. try:
  165. snapshot = await self.client.rpc("session.resume", session_id=sid)
  166. except Exception: # health: allow BLE001 -- any failed re-attach ends the wait, never hangs it
  167. if self.session_id == sid:
  168. self._fail(GatewayClientError("session_replay_gap"))
  169. return
  170. if self.session_id != sid:
  171. return # /new or /branch moved this view meanwhile
  172. self.generation = snapshot.get("execution_generation", self.generation)
  173. self.pending, prompts = snapshot.get("pending", self.pending), {p["prompt_id"]: p for p in snapshot.get("prompts", [])}
  174. for prompt_id in prompts.keys() - self.prompts.keys() if not self.finite else ():
  175. self.show_prompt(prompts[prompt_id])
  176. self.prompts = prompts
  177. for admission in dict.fromkeys([*self.streams, *self.mine]): # the running turn first: one FIFO
  178. await self._recover(admission, sid)
  179. self.changed.set() # after its own turn settled: a control it lists may end a one-shot's wait
  180. async def _recover(self, admission, sid):
  181. """Queued: it lost nothing. Running: cut until its live completion. Unknown: its completion was the
  182. one lost, so an own turn settles as unknown now. Unlisted: it ended in the hole."""
  183. from hermes_cli.gateway_replay_gap import pending_status, settled
  184. status = pending_status(self.pending, admission)
  185. if status == "unknown" and admission in self.mine:
  186. self._complete(admission, {"outcome": "unknown", "text": _UNKNOWN_OUTCOME})
  187. self.changed.set()
  188. if not admission or status in ("queued", "unknown") or admission in self.completions:
  189. return
  190. self.cut.setdefault(admission, self.streams.pop(admission, ""))
  191. if status or any(kind == "message.complete" and own == admission for kind, own, _ in self._finite_events):
  192. return # (its completion already arrived, held for the submit ack)
  193. try:
  194. receipt = await self.client.rpc("prompt.receipt", session_id=sid, admission_id=admission, include_result=True)
  195. except Exception: # health: allow BLE001 -- unreadable, like a receipt without its reply
  196. receipt = {"status": "terminal"}
  197. verdict = settled(receipt) if self.session_id == sid and admission not in self.completions else False
  198. if verdict:
  199. outcome = {"interrupted": "cancelled"}.get(receipt.get("outcome"), receipt.get("outcome"))
  200. self._complete(admission, {"outcome": outcome, "_receipt": receipt,
  201. "text": (receipt.get("result") or {}).get("final_response") or ""})
  202. self.changed.set()
  203. elif verdict is None and self.finite: # unreadable: fails as before (interactive: the next gap retries)
  204. self._fail(GatewayClientError("session_replay_gap"))
  205. async def _read_line(self, prompt, symbol):
  206. """The next composer line, or ``""`` once the event stream failed first (``self.failure``
  207. is then set). The pending read is cancelled (prompt_toolkit restores the terminal) so the
  208. caller reports the unknown outcome without waiting for a keypress."""
  209. default, self.prefill = self.prefill, ""
  210. reader = asyncio.ensure_future(prompt.prompt_async(symbol, **({"default": default} if default else {})))
  211. failed = asyncio.ensure_future(self.failed.wait())
  212. try:
  213. await asyncio.wait({reader, failed}, return_when=asyncio.FIRST_COMPLETED)
  214. finally:
  215. failed.cancel()
  216. if reader.done():
  217. return reader.result()
  218. reader.cancel()
  219. with suppress(asyncio.CancelledError):
  220. await reader
  221. return ""
  222. def _dispatch_event(self, kind, admission, payload):
  223. handler = {
  224. "message.delta": self._delta, "message.complete": self._complete,
  225. "tool.start": self._tool_start, "tool.complete": self._tool_complete,
  226. "approval.request": self._request, "clarify.request": self._request,
  227. "approval.settled": self._settled, "clarify.settled": self._settled,
  228. "session.info": self._session_info,
  229. "status.update": self._notice, "notification.show": self._notice,
  230. }.get(kind)
  231. if handler:
  232. handler(admission, payload)
  233. def _session_info(self, admission, payload):
  234. self.pending = payload.get("pending", self.pending)
  235. self.generation = payload.get("execution_generation", self.generation)
  236. def _notice(self, admission, payload):
  237. # The owner already applied display.warning_notifications; it publishes only what shows.
  238. if not self.quiet and str(payload.get("text") or "").strip():
  239. print(str(payload["text"]).strip(), file=sys.stderr, flush=True)
  240. def _tool_start(self, admission, payload):
  241. # Deltas before a tool call are interim commentary the final reply does not repeat;
  242. # close that segment so `_complete` measures only the final's own stream.
  243. if admission in self.cut:
  244. self.cut[admission] = ""
  245. if self.streams.pop(admission, None) and not self.quiet:
  246. print(flush=True)
  247. if self.emitter is not None:
  248. self.emitter.on_tool_progress("tool.started", payload.get("tool_name"), None, payload.get("args"),
  249. tool_call_id=payload.get("tool_call_id") or None)
  250. elif not self.quiet:
  251. # Same line shape the in-process CLI prints: the tool's emoji and its primary argument.
  252. from agent.display import build_tool_preview, get_tool_emoji
  253. name = payload.get("tool_name") or payload.get("name") or "tool"
  254. preview = build_tool_preview(name, payload.get("args") or {}, max_len=0)
  255. print(f"{get_tool_emoji(name)} {name}{f': {preview}' if preview else ''}", flush=True)
  256. def _tool_complete(self, admission, payload):
  257. if self.emitter is not None:
  258. self.emitter.on_tool_progress("tool.completed", payload.get("tool_name"), None, payload.get("args"),
  259. tool_call_id=payload.get("tool_call_id") or None,
  260. result=payload.get("result"), is_error=payload.get("is_error", False))
  261. def _delta(self, admission, payload):
  262. text = payload.get("text") or payload.get("delta") or payload.get("content") or ""
  263. if not isinstance(text, str) or admission in self.cut:
  264. return # cut: live text stopped at the replay gap; the settlement shows the reply once
  265. if self.emitter is not None:
  266. self.emitter.on_text_delta(text)
  267. elif not self.quiet:
  268. self.streams[admission] = self.streams.get(admission, "") + text
  269. # No flush: under the live composer, patch_stdout line-buffers this so a redraw
  270. # (a resize mid-stream) never interleaves with a half-written line. Complete lines
  271. # still appear as they stream; the last one lands with `_complete`.
  272. print(text, end="")
  273. def _complete(self, admission, payload):
  274. text = payload.get("text") or payload.get("content") or ""
  275. streamed, cut = self.streams.pop(admission, ""), self.cut.pop(admission, None)
  276. self.mine.pop(admission, None)
  277. if cut is not None:
  278. from hermes_cli.gateway_replay_gap import owed_reply
  279. payload = {**payload, "replay_gap": True}
  280. if not self.quiet and text:
  281. print(owed_reply(cut, text), flush=True)
  282. elif not self.quiet:
  283. # The final's deltas carry the agent's segment break (leading blank lines after a
  284. # tool call) that the settled text has trimmed; a match modulo that edge whitespace
  285. # is the same reply already on screen.
  286. if not streamed:
  287. print(text, flush=True)
  288. elif text.startswith(streamed):
  289. print(text[len(streamed):], flush=True)
  290. elif text.strip() == streamed.strip():
  291. print(flush=True)
  292. else:
  293. print("\n" + text, flush=True)
  294. # A turn the owner's restart/stop interrupted names that cause (#134889 F1); other
  295. # message.complete warnings stay Ink/Desktop-only as before.
  296. warning = payload.get("warning")
  297. if payload.get("status") == "interrupted" and isinstance(warning, str) and warning.strip():
  298. print(warning.strip(), file=sys.stderr, flush=True)
  299. self.completions[admission] = payload
  300. def _request(self, admission, payload):
  301. self.prompts[payload["prompt_id"]] = payload
  302. # Finite invocations only need the session-blocking state so they can
  303. # detach cleanly; do not print another admission's control details.
  304. if not self.finite:
  305. self.show_prompt(payload)
  306. def _settled(self, admission, payload):
  307. self.prompts.pop(payload["prompt_id"], None)
  308. async def submit(self, text):
  309. self.mutations.retire(self.session_id)
  310. sid, gaps = self.session_id, self.gaps
  311. receipt = await self.client.rpc("prompt.submit", session_id=self.session_id,
  312. input_id=uuid.uuid4().hex, text=text,
  313. **({"finite": True} if self.finite else {}),
  314. **({"unattended": True} if self.finite and self.unattended else {}))
  315. if (receipt or {}).get("voice_stopped") is True:
  316. # TUI-26: a bare stop phrase typed into this LOCAL session's voice chat (another viewer
  317. # turned it on) ended the chat on the owner; nothing was admitted and no turn follows.
  318. if not self.quiet:
  319. from agent.i18n import t
  320. print(t("cli.voice.stop_phrase_typed"), flush=True)
  321. return receipt
  322. admission = (receipt or {}).get("admission_id")
  323. if admission and admission not in self.completions and self.session_id == sid:
  324. self.mine[admission] = None
  325. if self.gaps != gaps: # a re-attach left after this submit: its snapshot covers it
  326. async with self._attaching:
  327. if admission not in self.cut and not self.failure:
  328. await self._recover(admission, sid)
  329. return receipt
  330. async def command(self, text):
  331. command, _, rest = text.partition(" ")
  332. if command in {"/quit", "/exit", "/detach"}:
  333. return False
  334. if command == "/stop":
  335. await self.client.rpc("session.interrupt", session_id=self.session_id,
  336. execution_generation=self.generation)
  337. return True
  338. if command in {"/approve", "/answer"}:
  339. prompt_id, _, answer = rest.partition(" ")
  340. prompt = self.prompts.get(prompt_id)
  341. expected = "approval" if command == "/approve" else "clarify"
  342. if not prompt or prompt["kind"] != expected:
  343. raise GatewayClientError("No matching pending control; resume to refresh")
  344. await self.client.rpc(expected + ".respond", session_id=self.session_id,
  345. execution_generation=prompt["execution_generation"], prompt_id=prompt_id,
  346. **({"choice": answer} if expected == "approval" else {"answer": answer}))
  347. return True
  348. if command == "/discard":
  349. snapshot = await self.client.rpc("session.resume", session_id=self.session_id)
  350. lost = lost_admission(snapshot, rest.strip())
  351. await self.client.rpc("prompt.resolve_unknown", session_id=self.session_id,
  352. admission_id=lost["admission_id"], execution_generation=lost["execution_generation"])
  353. return True
  354. if command in {'/branch', '/model', '/compress'}:
  355. from hermes_cli.gateway_mutations import slash_mutation
  356. operation, payload = slash_mutation(command, rest.strip())
  357. original = self.session_id
  358. confirm = self._confirm_model_switch if operation == 'model' and self._composer is not None else None
  359. result = await self.mutations.apply(self.client, original, operation, payload, confirm=confirm)
  360. if result.get('status') == 'cancelled':
  361. return True
  362. if result.get('status') == 'preview':
  363. self.mutations.acknowledge(original, operation, payload)
  364. print('\n'.join(result['lines']))
  365. return True
  366. if result.get('status') == 'noop':
  367. # Nothing removable (gateway/session_mutation_compress.py), or a `/model reset` already
  368. # on the configured default (its note): main's report, nothing committed.
  369. self.mutations.acknowledge(original, operation, payload)
  370. summary = result.get('summary') or {'note': result.get('note')}
  371. print('\n'.join(filter(None, (summary.get('headline'), summary.get('token_line'), summary.get('note')))))
  372. return True
  373. target = result.get('branched_session_id', original)
  374. await self.adopt(await self.client.rpc('session.resume', session_id=target))
  375. self.mutations.acknowledge(original, operation, payload)
  376. if operation == 'model' and result.get('model'):
  377. self.model = str(result['model']).split('/')[-1]
  378. print(f"{operation}: {target}")
  379. return True
  380. if command == "/yolo":
  381. # This session's approval bypass on the owner (same verb as the TUI's /yolo and Desktop).
  382. word = rest.strip().lower()
  383. if word not in {"", "on", "off"}:
  384. raise GatewayClientError("Usage: /yolo [on|off]")
  385. result = await self.client.rpc("config.set", session_id=self.session_id, key="yolo",
  386. **({"value": "1" if word == "on" else "0"} if word else {}))
  387. print(f"YOLO {'on' if result.get('value') == '1' else 'off'} for this session")
  388. return True
  389. from hermes_cli import gateway_chat_commands
  390. if command == "/help":
  391. print(gateway_chat_commands.help_text())
  392. return True
  393. return await gateway_chat_commands.run_command(self, command, rest)
  394. async def adopt(self, snapshot):
  395. """Attach this view to another session's snapshot (a branch, /new)."""
  396. self.session_id = snapshot['stored_session_id']
  397. self.generation = snapshot['execution_generation']
  398. self.prompts = {p['prompt_id']: p for p in snapshot.get('prompts', [])}
  399. self.pending = snapshot.get('pending', [])
  400. self.model = str((snapshot.get('info') or {}).get('model') or self.model).split('/')[-1]
  401. if not self.finite:
  402. # Bare `hermes -c` in this terminal continues the session it is now on, as the
  403. # in-process CLI re-wrote its breadcrumb on every session switch.
  404. from hermes_cli.terminal_breadcrumbs import write_breadcrumb
  405. await asyncio.to_thread(write_breadcrumb, self.session_id)
  406. async def _confirm_model_switch(self, refusal):
  407. """The owner refused a guarded model target (cost / data policy / large context): ask as
  408. the in-process CLI does (``_confirm_expensive_model_switch``: switch anyway once, or cancel)
  409. on this composer. Only an explicit yes applies; anything else keeps the current model."""
  410. from agent.i18n import t
  411. from hermes_cli.gateway_mutations import confirm_choice, confirmation_title
  412. choices = [("once", t("cli.model.choice_switch_anyway"), t("cli.model.desc_switch_anyway")),
  413. ("cancel", t("cli.model.choice_cancel"), t("cli.model.desc_keep_current_model"))]
  414. print(f"\n!!! {confirmation_title(refusal)} !!!\n{refusal['confirm_message']}\n")
  415. for index, (_, label, detail) in enumerate(choices, 1):
  416. print(f" {index}. {label} \u2014 {detail}")
  417. try:
  418. raw = await self._read_line(self._composer, t("cli.model.confirm_choice_prompt"))
  419. except (KeyboardInterrupt, EOFError):
  420. raw = ""
  421. if not self.failure and confirm_choice(raw, choices) == "once":
  422. return True
  423. print(t("cli.model.switch_cancelled"))
  424. return False
  425. def _detach(self, message):
  426. """One-shot cannot go on without a human: say why on stderr, exit 3, and in stream-json
  427. mode close the protocol with a failed ``result`` (a consumer parsing stdout must never be
  428. left without a terminal record)."""
  429. print(message, file=sys.stderr)
  430. if self.emitter is not None:
  431. return self.emitter.emit_result({"failed": True, "error": message}, session_id=self.session_id, exit_code=3)
  432. return 3
  433. def _finite_block(self, admission):
  434. """Why a finite viewer cannot keep waiting for *admission*, or None. Its own lost turn
  435. settles as the unknown completion would, so the exit code never depends on frame order;
  436. only a still-queued input behind someone else's unknown turn is retained and detached."""
  437. own = next((row["status"] for row in self.pending if row["admission_id"] == admission), None)
  438. if own == "unknown":
  439. self.completions[admission] = {"outcome": "unknown", "text": _UNKNOWN_OUTCOME}
  440. return None
  441. if own == "queued" and self.unknown_admissions():
  442. return ("This chat is paused behind a turn whose ending Hermes couldn't confirm. "
  443. "Your message is saved and will run once you resume this session and /discard "
  444. "that turn; don't send it again.")
  445. if self.prompts and (own or not self.gaps): # a control blocks only a turn still pending
  446. return "Input required; detached without cancelling. Resume this session interactively."
  447. return None
  448. async def _settled_result(self, admission):
  449. """The structured result the owner committed with this admission's settlement — the same
  450. dict the in-process one-shot got from ``run_conversation`` (best-effort, never raises)."""
  451. from websockets.exceptions import WebSocketException
  452. try:
  453. receipt = await self.client.rpc("prompt.receipt", session_id=self.session_id,
  454. admission_id=admission, include_result=True)
  455. return dict(receipt.get("result") or {})
  456. # Transport loss / refusal, or a receipt whose ``result`` is not a mapping.
  457. except (GatewayClientError, OSError, TimeoutError, WebSocketException,
  458. AttributeError, TypeError, ValueError) as exc:
  459. # The exit code and ledger still follow the settled outcome; a missing receipt is not fatal.
  460. logger.debug("settled result for %s unavailable: %s", admission, exc)
  461. return {}
  462. def _print_exit_ids(self):
  463. """The finite run's durable id on stderr (automation wrappers parse it; it names the
  464. physical row a compaction may have advanced) and, for `chat -q`, main's resume block. Main's
  465. `-z` (unattended) printed only the reply: no id line."""
  466. if not self.unattended:
  467. print(f"\nsession_id: {self.session_id}", file=sys.stderr, flush=True)
  468. if self.resume_footer:
  469. print(resume_footer(self.session_id), flush=True)
  470. @staticmethod
  471. def _report_silent_interrupt(text, result):
  472. """A restart or stop drain settles a finite turn interrupted with no reply: say so on stderr
  473. instead of exiting 130 silently. It is never replayed."""
  474. if text or not result.get("interrupted"):
  475. return
  476. reason = result.get("interrupt_message")
  477. print(f"Turn interrupted{f' ({reason})' if isinstance(reason, str) and reason else ''}; "
  478. "it was not retried. Resume this session to continue.", file=sys.stderr)
  479. def _report_no_reply(self, exit_code):
  480. """`-z` exit 1 (a completed turn with no reply text): the in-process one-shot's stderr line."""
  481. if self.unattended and exit_code == 1:
  482. print("hermes -z: no final response was produced; treating the run as failed.", file=sys.stderr)
  483. def _write_usage_file(self, result, outcome):
  484. """``-z --usage-file``: the same JSON ledger the in-process one-shot wrote."""
  485. from hermes_cli.oneshot import _write_usage_file
  486. result = {**result, "session_id": result.get("session_id") or self.session_id}
  487. failure = None if outcome in ("completed", "cancelled") else (result.get("error") or outcome or "failed")
  488. _write_usage_file(self.usage_file, result, failure=failure)
  489. async def run(self, query=None, *, oneshot=False):
  490. self.quiet = self.quiet or oneshot
  491. self.finite = oneshot
  492. self.show_pending()
  493. for prompt in self.prompts.values():
  494. self.show_prompt(prompt)
  495. if oneshot and self.unknown_admissions():
  496. # A new admission would queue behind the unknown row and never run; refuse BEFORE
  497. # submitting so nothing is left queued for the next interactive resume to find.
  498. return self._detach(f"Your message was not sent. To continue, run `hermes sessions discard "
  499. f"{self.session_id} --yes`, or resume this session in an interactive chat "
  500. "and /discard the paused turn there; then send it again.")
  501. renderer = asyncio.create_task(self.render())
  502. try:
  503. receipt = await self.submit(query) if query else None
  504. if oneshot:
  505. admission = _oneshot_admission(receipt)
  506. if admission is None:
  507. return 0 # the voice chat ended; no turn was admitted, so none is awaited
  508. self.finite_admission = admission
  509. for kind, event_admission, payload in self._finite_events:
  510. if event_admission == admission and admission not in self.completions:
  511. self._dispatch_event(kind, event_admission, payload)
  512. self._finite_events.clear()
  513. self.changed.set()
  514. while admission not in self.completions:
  515. self.changed.clear()
  516. if self.failure:
  517. raise self.failure
  518. blocked = self._finite_block(admission)
  519. if blocked:
  520. return self._detach(blocked)
  521. if admission not in self.completions:
  522. await self.changed.wait()
  523. terminal = self.completions[admission]
  524. outcome = terminal.get("outcome")
  525. text = terminal.get("text") or terminal.get("content") or ""
  526. # The outcome only says failed/cancelled; a turn stopped by --max-turns settles
  527. # 'completed' with ``completed: False`` in its committed result. Judge both with the
  528. # in-process exit contracts: `-z` 0/2/130 (1 = no text), `chat -q`/`-Q` 0/1/130.
  529. from hermes_cli.oneshot import _oneshot_exit_code
  530. from hermes_cli.turn_exit import turn_exit_code
  531. recovered = terminal.get("_receipt")
  532. result = dict(recovered.get("result") or {}) if recovered else await self._settled_result(admission)
  533. result.update(failed=bool(result.get("failed")) or outcome not in ("completed", "cancelled"),
  534. interrupted=bool(result.get("interrupted")) or outcome == "cancelled")
  535. exit_code = (_oneshot_exit_code(text, result) if self.unattended
  536. else turn_exit_code(result, kanban_worker=False))
  537. if self.usage_file:
  538. self._write_usage_file(result, outcome)
  539. if self.emitter is not None:
  540. return self.emitter.emit_result({**result, "final_response": text,
  541. "replay_gap": bool(terminal.get("replay_gap"))},
  542. session_id=self.session_id, exit_code=exit_code)
  543. self._report_silent_interrupt(text, result)
  544. print(text, flush=True)
  545. self._report_no_reply(exit_code)
  546. # Same stderr exit contract as the legacy -Q path: automation wrappers read the
  547. # durable id from this line, and it names the physical row (a compaction may have
  548. # advanced it past the row printed at start).
  549. self._print_exit_ids()
  550. return exit_code
  551. from prompt_toolkit import PromptSession
  552. from prompt_toolkit.patch_stdout import patch_stdout
  553. from hermes_cli.skin_engine import get_active_prompt_symbol, get_active_skin
  554. welcome = "Welcome to Hermes Agent! Type your message or /help for commands."
  555. print(get_active_skin().get_branding("welcome", welcome), flush=True)
  556. # The classic status bar's leading segments: model, then the attached session.
  557. prompt = PromptSession(erase_when_done=True,
  558. bottom_toolbar=lambda: f" \u2624 {self.model} \u2502 {self.session_id} ")
  559. prompt_symbol = get_active_prompt_symbol("❯ ")
  560. self._composer = prompt if sys.stdin.isatty() else None
  561. with patch_stdout():
  562. while not self.failure:
  563. try:
  564. # Empty when the stream failed first: the loop guard then raises it.
  565. text = (await self._read_line(prompt, prompt_symbol)).strip()
  566. if not text:
  567. continue
  568. if text.startswith("/"):
  569. if not await self.command(text):
  570. return 0
  571. else:
  572. # Same scrollback shape as the in-process CLI: the typed prompt line is
  573. # erased on submit and the message lands as a `●` preview row.
  574. print(f"\n{'─' * 40}\n● {text}", flush=True)
  575. await self.submit(text)
  576. except KeyboardInterrupt:
  577. print("Use /stop to interrupt execution, /quit to detach.")
  578. except EOFError:
  579. return 0
  580. except GatewayClientError as exc:
  581. print(f"Error: {exc}", file=sys.stderr)
  582. raise self.failure
  583. finally:
  584. renderer.cancel()
  585. with suppress(asyncio.CancelledError):
  586. await renderer
  587. def _oneshot_admission(receipt):
  588. """The one-shot query's admission id; None when the owner admitted nothing because the query was a
  589. bare stop phrase that ended the session's LOCAL voice chat (TUI-26 ``{voice_stopped: true}``)."""
  590. if receipt is None:
  591. raise GatewayClientError("One-shot requires a query")
  592. return None if receipt.get("voice_stopped") is True else receipt["admission_id"]
  593. def resume_footer(session_id):
  594. """The classic single-query exit block (``_print_exit_summary``): how to continue this session.
  595. A non-default profile needs ``-p`` because session ids are profile-scoped."""
  596. from agent.i18n import t
  597. from hermes_cli.profiles import get_active_profile_name
  598. profile = get_active_profile_name()
  599. flag = "" if profile in ("default", "custom") else f" -p {profile}"
  600. return f"\n{t('cli.session.exit_resume_hint')}\n hermes --resume {session_id}{flag}"