cli_modal_mixin.py 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303
  1. """Modal overlays for the interactive CLI: clarify, approval, sudo/secret capture, command palette,
  2. slash-confirm, external editor.
  3. Mixin split out of ``cli.py``; bound onto ``HermesCLI`` via the MRO. cli.py-internal symbols are
  4. imported LAZILY inside each method — the mixin never imports ``cli`` at module load time (cycle).
  5. """
  6. from __future__ import annotations
  7. import json
  8. import queue
  9. import sys
  10. import threading
  11. import time as _time
  12. import webbrowser
  13. from agent.i18n import t
  14. from hermes_cli.callbacks import prompt_for_secret
  15. from typing import Optional
  16. _TIMED_OUT = object() # sentinel returned by _poll_modal_queue when the deadline passes
  17. # Typed answers accepted by the slash-confirm modal, mapped onto the canonical choice values.
  18. _CONFIRM_ALIASES = {
  19. "1": "once", "once": "once", "approve": "once", "yes": "once", "y": "once", "ok": "once",
  20. "2": "always", "always": "always", "remember": "always",
  21. "3": "cancel", "cancel": "cancel", "nevermind": "cancel", "no": "cancel", "n": "cancel"}
  22. # Approval result -> catalog key of the outcome label shown in the persisted prompt summary.
  23. # Resolved at call time (``_approval_outcome_label``) so the active language applies.
  24. _APPROVAL_OUTCOME_KEYS = {
  25. "once": "cli.approval.outcome_once",
  26. "session": "cli.approval.outcome_session",
  27. "always": "cli.approval.outcome_always",
  28. "deny": "cli.approval.outcome_deny"}
  29. def _approval_outcome_label(result) -> str:
  30. key = _APPROVAL_OUTCOME_KEYS.get(result)
  31. return t(key) if key else str(result)
  32. def _approval_gate_on(key: str) -> bool:
  33. """Read ``approvals.<key>`` (default on); any load failure keeps the prompt enabled."""
  34. from cli import load_cli_config
  35. try:
  36. cfg = load_cli_config()
  37. approvals = cfg.get("approvals") if isinstance(cfg, dict) else None
  38. if isinstance(approvals, dict):
  39. return bool(approvals.get(key, True))
  40. except Exception:
  41. pass
  42. return True
  43. def _gated_confirm(self, command, key, *, title, detail, choices, unchanged, always_msg, once_verb=None,
  44. persist_failed_msg=None):
  45. """Shared once/always/cancel confirm behind ``approvals.<key>`` (destructive slash, /reload-mcp).
  46. Returns ``"once"`` without prompting when the gate is off; ``None`` on cancel / no input /
  47. unrecognized answer (already reported to the user). Picking "always" persists the opt-out.
  48. ``persist_failed_msg`` is the full sentence printed when the opt-out could not be saved;
  49. ``once_verb`` is the legacy fragment spliced into the default sentence.
  50. """
  51. from cli import save_config_value
  52. if not _approval_gate_on(key):
  53. return "once"
  54. raw = self._prompt_text_input_modal(title=title, detail=detail, choices=choices)
  55. if raw is None:
  56. print(t("cli.modal.cancelled_no_input", command=command))
  57. return None
  58. choice = self._normalize_slash_confirm_choice(raw, choices)
  59. if choice is None:
  60. print(t("cli.modal.unrecognized_choice", raw=raw, command=command))
  61. return None
  62. if choice == "cancel":
  63. print(t("cli.modal.cancelled", command=command, unchanged=unchanged))
  64. return None
  65. if choice == "always":
  66. if save_config_value(f"approvals.{key}", False):
  67. print(always_msg)
  68. print(t("cli.modal.re_enable_hint", setting=key))
  69. else:
  70. print(persist_failed_msg or t("cli.modal.persist_opt_out_failed", once_verb=once_verb or ""))
  71. return choice
  72. class CLIModalMixin:
  73. """Modal overlays for the interactive CLI: clarify, approval, sudo/secret capture, command
  74. palette, slash-confirm, external editor."""
  75. _connection_state = None
  76. def _open_external_editor(self, buffer=None) -> bool:
  77. """Open the active input buffer in an external editor."""
  78. from cli import _DIM, _RST, _cprint
  79. app = getattr(self, "_app", None)
  80. if not app:
  81. _cprint(f"{_DIM}{t('cli.editor.only_interactive')}{_RST}")
  82. return False
  83. if self._command_running:
  84. _cprint(f"{_DIM}{t('cli.editor.wait_for_command')}{_RST}")
  85. return False
  86. if (self._sudo_state or self._secret_state or self._approval_state
  87. or getattr(self, "_slash_confirm_state", None) or self._clarify_state
  88. or self._connection_state):
  89. _cprint(f"{_DIM}{t('cli.editor.finish_active_prompt')}{_RST}")
  90. return False
  91. target_buffer = buffer or getattr(app, "current_buffer", None)
  92. if target_buffer is None:
  93. _cprint(f"{_DIM}{t('cli.editor.no_input_buffer')}{_RST}")
  94. return False
  95. try:
  96. # Inline pastes so the editor sees real content; set the skip flag unconditionally so
  97. # the editor-close text-change doesn't re-collapse it.
  98. self._inline_pastes(target_buffer)
  99. self._skip_paste_collapse = True
  100. # Submission here is driven by the custom `enter` keybinding, NOT the buffer's
  101. # accept_handler, so validate_and_handle can't route through it; chain a done-callback
  102. # that re-uses the real submit pipeline (TUI Ctrl+G parity: save == send).
  103. task = target_buffer.open_in_editor(validate_and_handle=False)
  104. if task is not None and hasattr(task, "add_done_callback"):
  105. task.add_done_callback(lambda _t, b=target_buffer: self._submit_editor_buffer(b))
  106. return True
  107. except Exception as exc:
  108. _cprint(f"{_DIM}{t('cli.editor.open_failed', error=exc)}{_RST}")
  109. return False
  110. def _submit_editor_buffer(self, buffer) -> None:
  111. """Submit the draft an external editor left in ``buffer`` (Ctrl+G done-callback), mirroring
  112. the `enter` keybinding: empty save ignored, bang/slash dispatched, else queued. Runs on the
  113. prompt_toolkit loop, so it must stay cheap/non-blocking."""
  114. from cli import _DIM, _RST, _cprint, _looks_like_slash_command
  115. try:
  116. text = (getattr(buffer, "text", "") or "").strip()
  117. except Exception:
  118. return
  119. if not text:
  120. return
  121. app = getattr(self, "_app", None)
  122. def _done() -> None:
  123. self._reset_input_buffer(buffer)
  124. if app is not None:
  125. app.invalidate()
  126. # `!<command>` shell mode is checked before slash dispatch, matching the Enter path.
  127. try:
  128. if self.handle_bang_shell(text):
  129. _done()
  130. return
  131. except Exception as exc:
  132. _cprint(f" {_DIM}{t('cli.editor.shell_command_failed', error=exc)}{_RST}")
  133. _done()
  134. return
  135. if _looks_like_slash_command(text):
  136. try:
  137. if not self.process_command(text):
  138. self._should_exit = True
  139. if app is not None and app.is_running:
  140. app.exit()
  141. except Exception as exc:
  142. _cprint(f" {_DIM}{t('cli.editor.command_failed', error=exc)}{_RST}")
  143. finally:
  144. _done()
  145. return
  146. if self._agent_running:
  147. # Agent busy → honour the configured busy-input behaviour (interrupt/steer remain
  148. # reachable via the normal Enter path).
  149. if self.busy_input_mode == "interrupt":
  150. self._interrupt_queue.put(text)
  151. else:
  152. self._pending_input.put(text)
  153. preview = text[:80] + ("..." if len(text) > 80 else "")
  154. _cprint(f" {t('cli.editor.queued_next_turn', preview=preview)}")
  155. else:
  156. self._pending_input.put(text)
  157. _done()
  158. def _inline_pastes(self, buffer) -> None:
  159. """Replace collapsed ``[Pasted text #N -> file]`` placeholders in ``buffer`` with real text.
  160. History recall and the external editor need the content (the file may be gone or on another
  161. machine); inlining before ``reset(append_to_history=True)`` also lets prompt_toolkit persist
  162. it. Sets ``_skip_paste_collapse`` so the ensuing text-change doesn't re-collapse it.
  163. """
  164. from cli import logger
  165. try:
  166. existing = getattr(buffer, "text", "")
  167. expanded = self._expand_paste_references(existing)
  168. if expanded != existing and hasattr(buffer, "text"):
  169. self._skip_paste_collapse = True
  170. buffer.text = expanded
  171. if hasattr(buffer, "cursor_position"):
  172. buffer.cursor_position = len(expanded)
  173. except Exception:
  174. logger.debug("Failed to inline paste placeholders", exc_info=True)
  175. def _reset_input_buffer(self, buffer) -> None:
  176. """Clear an input buffer after a programmatic submit (best-effort)."""
  177. try:
  178. buffer.reset(append_to_history=True)
  179. except Exception:
  180. try:
  181. buffer.text = ""
  182. except Exception:
  183. pass
  184. def _prefill_input_buffer(self, text: str) -> None:
  185. """Place ``text`` in the active prompt_toolkit buffer, editable."""
  186. from cli import logger
  187. app = getattr(self, "_app", None)
  188. if app is None:
  189. return
  190. try:
  191. buf = app.current_buffer
  192. buf.text = text
  193. if hasattr(buf, "cursor_position"):
  194. buf.cursor_position = len(text)
  195. app.invalidate()
  196. except Exception as e:
  197. logger.debug("undo: prefill buffer failed: %s", e)
  198. def _prompt_text_input(self, prompt_text: str) -> str | None:
  199. """Prompt for free-text input safely inside or outside prompt_toolkit.
  200. ``run_in_terminal`` only works on the main-thread loop; on the ``process_loop`` daemon
  201. thread a bare ``input()`` would block forever on loop-owned stdin, so with an app running
  202. off-main we cancel cleanly (None) — mirroring ``_stdin_fallback`` in the modal prompt.
  203. Mirrors the thread-aware guard in ``_run_curses_picker``: ``run_in_terminal`` returns a coroutine
  204. that must be awaited by the prompt_toolkit event loop, which only exists on the main thread. Slash
  205. commands are dispatched from the ``process_loop`` daemon thread (see issue #23185), so calling
  206. ``run_in_terminal`` from there orphans the coroutine — ``_ask`` never runs, and user keystrokes leak
  207. into the composer instead. Fall back to a direct ``input()`` when we're off the main thread.
  208. """
  209. result = [None]
  210. def _ask():
  211. try:
  212. result[0] = input(prompt_text).strip() or None
  213. except (KeyboardInterrupt, EOFError):
  214. pass
  215. in_main_thread = threading.current_thread() is threading.main_thread()
  216. # Slash-worker guard (#23185 / billing auto-reload hang): when a prompt_toolkit app is running but
  217. # we're on a non-main thread (the process_loop / TUI slash-worker daemon thread), stdin is owned by
  218. # the event loop / JSON-RPC pipe. A bare input() there blocks forever until the worker's 45s timeout
  219. # fires. We cannot safely prompt off the main thread, so cancel cleanly (None) instead of hanging —
  220. # mirrors the _stdin_fallback discipline in _prompt_text_input_modal.
  221. if self._app and not in_main_thread:
  222. self._invalidate()
  223. return None
  224. if self._app and in_main_thread:
  225. from prompt_toolkit.application import run_in_terminal
  226. was_visible = self._status_bar_visible
  227. self._status_bar_visible = False
  228. self._app.invalidate()
  229. try:
  230. run_in_terminal(_ask)
  231. except Exception:
  232. # WSL / Warp / some emulators silently drop the scheduled coroutine — fall back to
  233. # a direct input() so keystrokes don't leak into the agent buffer.
  234. try:
  235. _ask()
  236. except Exception:
  237. pass
  238. finally:
  239. self._status_bar_visible = was_visible
  240. self._app.invalidate()
  241. else:
  242. _ask()
  243. return result[0]
  244. def _poll_modal_queue(self, response_queue, deadline_attr, *, refresh=1.0, paint=None):
  245. """Block until a value lands on ``response_queue`` or ``self.<deadline_attr>`` passes
  246. (``None`` deadline = unlimited). Returns the value or ``_TIMED_OUT``.
  247. Repaints every ``refresh`` seconds (``0`` = on every idle tick) so countdown hints stay
  248. live; ``paint`` defaults to ``_paint_now`` — modal prompts must bypass the ``_invalidate``
  249. throttle/resize guard or the panel can be dropped and time out unseen.
  250. """
  251. paint = paint or self._paint_now
  252. last = _time.monotonic()
  253. while True:
  254. try:
  255. return response_queue.get(timeout=1)
  256. except queue.Empty:
  257. deadline = getattr(self, deadline_attr)
  258. if deadline is not None and deadline - _time.monotonic() <= 0:
  259. return _TIMED_OUT
  260. now = _time.monotonic()
  261. if now - last >= refresh:
  262. last = now
  263. paint()
  264. def _prompt_text_input_modal(
  265. self, *, title: str, detail: str, choices: list[tuple[str, str, str]], timeout: float = 120
  266. ) -> str | None:
  267. """Slash-command confirmation through the prompt_toolkit composer (raw input() fought
  268. prompt_toolkit's stdin ownership: prompt above the TUI, Enter read as EOF). All platforms
  269. drive the modal via ``self._app.loop`` + ``call_soon_threadsafe``; raw ``input()`` is kept
  270. only for the safe cases (no app, no loop, scheduling failure) — on Windows a non-main-thread
  271. input() deadlocks against prompt_toolkit, so that case cancels instead.
  272. **Platform note (Windows — issue #33961):** Earlier code bypassed the modal on ``sys.platform ==
  273. "win32"`` and fell back to a raw ``input()`` prompt. When the confirm was triggered from the
  274. ``process_loop`` daemon thread (the normal case) that ``input()`` ran off the main thread and
  275. deadlocked against prompt_toolkit's stdin ownership — the user saw a frozen cursor and Ctrl-C was
  276. swallowed (bare ``/reset`` froze; ``/reset now`` worked only because it skips the prompt entirely).
  277. """
  278. if not choices:
  279. return None
  280. if not getattr(self, "_app", None):
  281. return self._prompt_text_input(t("cli.modal.choice_prompt"))
  282. try:
  283. app_loop = self._app.loop
  284. except Exception:
  285. app_loop = None
  286. in_main_thread = threading.current_thread() is threading.main_thread()
  287. def _stdin_fallback() -> str | None:
  288. # On native Windows a raw input() from a non-main thread deadlocks against prompt_toolkit's
  289. # stdin ownership (#33961). With an app running we cannot safely prompt off the main thread, so
  290. # cancel cleanly (None) rather than hang the terminal.
  291. if sys.platform == "win32" and not in_main_thread:
  292. self._invalidate()
  293. return None
  294. return self._prompt_text_input(t("cli.modal.choice_prompt"))
  295. if not in_main_thread and app_loop is None:
  296. return _stdin_fallback()
  297. response_queue = queue.Queue()
  298. def _setup_modal() -> None:
  299. self._capture_modal_input_snapshot()
  300. self._slash_confirm_state = {
  301. "title": title,
  302. "detail": detail,
  303. "choices": choices,
  304. "selected": 0,
  305. "response_queue": response_queue}
  306. self._slash_confirm_deadline = _time.monotonic() + timeout
  307. self._invalidate()
  308. def _teardown_modal() -> None:
  309. self._slash_confirm_state = None
  310. self._slash_confirm_deadline = 0
  311. self._restore_modal_input_snapshot()
  312. self._invalidate()
  313. def _run_on_app_loop(fn) -> bool:
  314. if in_main_thread or app_loop is None:
  315. fn()
  316. return True
  317. ready = threading.Event()
  318. def _wrapped() -> None:
  319. try:
  320. fn()
  321. finally:
  322. ready.set()
  323. try:
  324. app_loop.call_soon_threadsafe(_wrapped)
  325. except Exception:
  326. return False
  327. return ready.wait(timeout=5)
  328. if not _run_on_app_loop(_setup_modal):
  329. return _stdin_fallback()
  330. try:
  331. result = self._poll_modal_queue(
  332. response_queue, "_slash_confirm_deadline", refresh=5.0, paint=self._invalidate)
  333. if result is not _TIMED_OUT:
  334. _run_on_app_loop(_teardown_modal)
  335. return result
  336. finally:
  337. if self._slash_confirm_state is not None:
  338. _run_on_app_loop(_teardown_modal)
  339. return None
  340. def _submit_slash_confirm_response(self, value: str | None) -> None:
  341. state = self._slash_confirm_state
  342. if not state:
  343. return
  344. state["response_queue"].put(value)
  345. self._slash_confirm_state = None
  346. self._slash_confirm_deadline = 0
  347. self._invalidate()
  348. def _normalize_slash_confirm_choice(
  349. self, raw: str | None, choices: list[tuple[str, str, str]]) -> str | None:
  350. if raw is None:
  351. return None
  352. choice_raw = raw.strip().lower()
  353. if not choice_raw:
  354. return None
  355. allowed = {choice[0] for choice in choices}
  356. normalized = _CONFIRM_ALIASES.get(choice_raw)
  357. if normalized in allowed:
  358. return normalized
  359. if choice_raw in allowed:
  360. return choice_raw
  361. return None
  362. def _build_command_palette_entries(self) -> list:
  363. """Flat (command, category, desc) rows for the Ctrl+P palette: the COMMAND_REGISTRY behind
  364. /help filtered to this surface, plus installed skill commands. Selecting inserts the exact
  365. command string — never a fuzzy resolution."""
  366. from cli import _session_skill_commands
  367. from hermes_cli.commands import COMMANDS_BY_CATEGORY
  368. entries: list[tuple[str, str, str]] = []
  369. for category, commands in COMMANDS_BY_CATEGORY.items():
  370. for cmd, desc in commands.items():
  371. if self._command_available(cmd):
  372. entries.append((cmd, category, desc))
  373. try:
  374. for cmd, info in sorted(_session_skill_commands(self).items()):
  375. entries.append((cmd, t("cli.palette.category_skill"), info.get("description", "")))
  376. except Exception:
  377. pass
  378. return entries
  379. def _open_command_palette(self) -> None:
  380. """Open the Ctrl+P fuzzy command palette modal (never stacked over another modal)."""
  381. if getattr(self, "_command_palette_state", None):
  382. return
  383. if (self._model_picker_state or self._clarify_state or self._approval_state
  384. or self._slash_confirm_state or self._sudo_state or self._secret_state
  385. or self._connection_state):
  386. return
  387. self._capture_modal_input_snapshot()
  388. self._command_palette_state = {
  389. "entries": self._build_command_palette_entries(),
  390. "filter": "",
  391. "selected": 0,
  392. "_scroll_offset": 0}
  393. self._invalidate(min_interval=0.0)
  394. def _close_command_palette(self) -> None:
  395. self._command_palette_state = None
  396. self._restore_modal_input_snapshot()
  397. self._invalidate(min_interval=0.0)
  398. def _command_palette_visible_entries(self) -> list:
  399. """Rows matching the active filter, ranked command-name-first (a bare subsequence over
  400. "cmd category desc" is uselessly permissive — "steer" would match 130+ rows via text):
  401. 0 exact command, 1 command startswith, 2 substring in command, 3 subsequence in command,
  402. 4 substring in description. Non-matches are dropped; ties keep registry order."""
  403. state = self._command_palette_state or {}
  404. entries = state.get("entries") or []
  405. q = (state.get("filter", "") or "").strip().lower()
  406. if not q:
  407. return list(entries)
  408. def _subseq(needle: str, hay: str) -> bool:
  409. it = iter(hay)
  410. return all(ch in it for ch in needle)
  411. qn = q.lstrip("/")
  412. ranked = []
  413. for order, row in enumerate(entries):
  414. cmd, _cat, desc = row
  415. name = cmd.lower().lstrip("/")
  416. desc_l = (desc or "").lower()
  417. if name == qn:
  418. rank = 0
  419. elif name.startswith(qn):
  420. rank = 1
  421. elif qn in name:
  422. rank = 2
  423. elif _subseq(qn, name):
  424. rank = 3
  425. elif q in desc_l:
  426. rank = 4
  427. else:
  428. continue
  429. ranked.append((rank, order, row))
  430. ranked.sort(key=lambda t: (t[0], t[1]))
  431. return [row for (_r, _o, row) in ranked]
  432. def _handle_command_palette_selection(self) -> None:
  433. """Prefill the selected command into the composer — never auto-run (many take args)."""
  434. from cli import logger
  435. state = self._command_palette_state
  436. if not state:
  437. return
  438. rows = self._command_palette_visible_entries()
  439. selected = state.get("selected", 0)
  440. if not (0 <= selected < len(rows)):
  441. self._close_command_palette()
  442. return
  443. cmd = rows[selected][0]
  444. self._close_command_palette()
  445. try:
  446. app = getattr(self, "_app", None)
  447. if app is not None:
  448. buf = app.current_buffer
  449. buf.text = cmd + " "
  450. buf.cursor_position = len(buf.text)
  451. self._invalidate(min_interval=0.0)
  452. except Exception:
  453. logger.debug("command palette prefill failed", exc_info=True)
  454. @classmethod
  455. def _split_destructive_skip(cls, cmd_text: Optional[str]) -> tuple[str, bool]:
  456. """Split inline-skip tokens out of a destructive slash command → ``(remainder, skip)``.
  457. ``remainder`` is the text minus the leading "/cmd" word and any skip tokens; ``skip`` is
  458. True iff one was found: "/reset now" -> ("", True); "/reset --yes My title" ->
  459. ("My title", True); "/new My title" -> ("My title", False).
  460. """
  461. tokens = (cmd_text or "").strip().split()
  462. if not tokens:
  463. return "", False
  464. if tokens[0].startswith("/"):
  465. tokens = tokens[1:]
  466. kept = [tok for tok in tokens if tok.lower() not in cls._DESTRUCTIVE_SKIP_TOKENS]
  467. return " ".join(kept), len(kept) != len(tokens)
  468. def _confirm_destructive_slash(
  469. self, command: str, detail: str, cmd_original: Optional[str] = None) -> Optional[str]:
  470. """Confirm a destructive slash command (``/clear``, ``/new``/``/reset``, ``/undo``): returns
  471. ``"once"``, ``"always"`` (persists the opt-out) or ``None`` (cancelled). Gate off → "once"
  472. silently; ``now`` / ``--yes`` / ``-y`` in ``cmd_original`` bypasses the modal (callers strip
  473. the tokens via :meth:`_split_destructive_skip`).
  474. Inline-skip: if ``cmd_original`` contains ``now``, ``--yes``, or ``-y`` as an argument (e.g.
  475. ``/reset now``, ``/new --yes My title``), the modal is bypassed and ``"once"`` is returned
  476. immediately. This is an escape hatch for non-interactive use and for the degraded path where the
  477. modal can't be marshaled onto the app loop (native Windows itself now drives the modal normally —
  478. see #33961). Callers are responsible for stripping the skip tokens from any remaining argument
  479. parsing (see :meth:`_split_destructive_skip`).
  480. """
  481. if cmd_original and self._split_destructive_skip(cmd_original)[1]:
  482. return "once"
  483. return _gated_confirm(
  484. self, command, "destructive_slash_confirm",
  485. title=t("cli.modal.destructive_title", command=command),
  486. detail=detail,
  487. choices=[
  488. ("once", t("cli.modal.approve_once"), t("cli.modal.approve_once_detail")),
  489. ("always", t("cli.modal.always_approve"), t("cli.modal.always_approve_detail")),
  490. ("cancel", t("cli.modal.cancel"), t("cli.modal.cancel_detail"))],
  491. unchanged=t("cli.modal.conversation_unchanged"),
  492. always_msg=t("cli.modal.destructive_always_msg"),
  493. persist_failed_msg=t("cli.modal.persist_failed_proceeding"))
  494. def _ring_bell(self, prompt: bool = False, context: str = "", detail: str = "") -> None:
  495. """Terminal bell (\\a) gated by ``display.bell_on_prompt`` (``prompt=True``, blocking modals)
  496. or ``display.bell_on_complete`` (end of turn); works over SSH. The same flag also emits the
  497. OSC 9 / Warp OSC 777 desktop notification; ``context`` is the short notification body."""
  498. flag = "bell_on_prompt" if prompt else "bell_on_complete"
  499. if not getattr(self, flag, False) or getattr(self, "_terminal_io_broken", False):
  500. return
  501. from hermes_cli.cli_terminal_mixin import _run_on_app_loop, _write_terminal_sequence
  502. from hermes_cli.terminal_notify import notification_sequence, write_tty
  503. body = context or (t("cli.modal.bell_input_needed") if prompt else t("cli.modal.bell_turn_complete"))
  504. try:
  505. seq = "\a" + notification_sequence(
  506. body, prompt=prompt, session_id=getattr(self, "session_id", "") or "", detail=detail)
  507. except Exception:
  508. return
  509. app = getattr(self, "_app", None)
  510. if app is None or not getattr(app, "_is_running", False):
  511. write_tty(seq)
  512. return
  513. # Agent thread. The loop thread may be mid-write of a 12 KB kitty pet frame that the tty
  514. # drains ~1 KB at a time; a second writer on the same tty (/dev/tty, sys.stdout) splices
  515. # in, the foreign ESC aborts the APC, and the terminal paints the rest of the payload as
  516. # base64 at the input cursor. Serialize behind the renderer instead.
  517. def _emit() -> None:
  518. try:
  519. _write_terminal_sequence(app, seq)
  520. except (OSError, ValueError):
  521. pass # dead tty: same fail-quiet as _pet_flush_kitty_frame
  522. _run_on_app_loop(app, _emit)
  523. def _clarify_teardown(self) -> None:
  524. self._clarify_state = None
  525. self._clarify_freetext = False
  526. self._clarify_deadline = None
  527. self._clarify_multi_base = None
  528. self._paint_now()
  529. # --- Connection setup --------------------------------------------------
  530. # The gateway runs the manage_connections operation; this card renders its connection.request /
  531. # connection.update events (delivered on the agent thread) and answers through the agent's
  532. # connection.respond / connectors.connect calls, never an in-process operation.
  533. def _connection_close(self) -> None:
  534. self._connection_state = None
  535. self._restore_modal_input_snapshot()
  536. self._paint_now()
  537. @staticmethod
  538. def _connection_fields(target) -> list[dict]:
  539. return [dict(field) for field in target.get("required_env") or () if isinstance(field, dict)]
  540. @staticmethod
  541. def _connection_opening_phase(target) -> str:
  542. """The phase a target opens in. A pending install or enable waits for the user's Connect
  543. even with no fields to fill; a pending authorize is the backend still minting the link."""
  544. target_state = target.get("state")
  545. if target_state == "initiated" and target.get("connect_url"):
  546. return "url"
  547. if target_state == "failed":
  548. return "failed"
  549. if target_state == "pending" and target.get("action") != "authorize":
  550. return "form"
  551. return "waiting"
  552. def _connection_show_target(self, payload, index: int) -> None:
  553. targets = payload.get("targets") or []
  554. if not targets:
  555. self._connection_close()
  556. return
  557. index = max(0, min(index, len(targets) - 1))
  558. target = targets[index]
  559. fields = self._connection_fields(target)
  560. previous = self._connection_state or {}
  561. drafts = previous.setdefault("drafts", {})
  562. target_draft = drafts.setdefault(target.get("name", ""), {})
  563. for field in fields:
  564. if "type" not in field:
  565. field["type"] = "secret" if field.get("secret") else "plain"
  566. if field.get("type") != "secret" and field.get("name") not in target_draft:
  567. target_draft[field.get("name")] = str(field.get("default") or "")
  568. self._connection_state = {
  569. **previous,
  570. "payload": payload,
  571. "target_index": index,
  572. "target": target,
  573. "fields": fields,
  574. "field_index": 0,
  575. "selected": 0,
  576. "phase": self._connection_opening_phase(target),
  577. "drafts": drafts,
  578. }
  579. self._connection_sync_input_buffer()
  580. self._paint_now()
  581. def _connection_active_field_is_secret(self) -> bool:
  582. state = self._connection_state
  583. if not state or state.get("phase") not in {"form", "failed"}:
  584. return False
  585. fields = state.get("fields") or []
  586. index = state.get("field_index", 0)
  587. return 0 <= index < len(fields) and fields[index].get("type") == "secret"
  588. def _connection_prefill_text(self) -> str:
  589. state = self._connection_state
  590. if not state or self._connection_active_field_is_secret():
  591. return ""
  592. fields = state.get("fields") or []
  593. index = state.get("field_index", 0)
  594. if not (0 <= index < len(fields)):
  595. return ""
  596. field = fields[index]
  597. target_name = state.get("target", {}).get("name", "")
  598. return str(state.get("drafts", {}).get(target_name, {}).get(field.get("name"), ""))
  599. def _connection_sync_input_buffer(self) -> None:
  600. app = getattr(self, "_app", None)
  601. if app is None:
  602. return
  603. def _apply() -> None:
  604. try:
  605. buf = app.current_buffer
  606. buf.text = self._connection_prefill_text()
  607. buf.cursor_position = len(buf.text)
  608. except Exception:
  609. pass
  610. loop = getattr(app, "loop", None)
  611. if loop is not None and threading.current_thread() is not threading.main_thread():
  612. try:
  613. loop.call_soon_threadsafe(_apply)
  614. return
  615. except Exception:
  616. pass
  617. _apply()
  618. def _connection_callback(self, payload):
  619. if not isinstance(payload, dict):
  620. return
  621. state = self._connection_state
  622. if state is not None and state["payload"].get("op_id") == payload.get("op_id"):
  623. # A replay-gap re-open of the card already shown: apply it as an update so the active
  624. # target, field and unsent input survive; an identical snapshot changes nothing.
  625. if int(payload.get("seq") or 0) > int(state["payload"].get("seq") or 0):
  626. self._connection_on_change(payload)
  627. return
  628. if state is None:
  629. self._capture_modal_input_snapshot()
  630. targets = payload.get("targets") or []
  631. # Open on the first app that still needs the user, not one already connected or skipped.
  632. index = next((i for i, item in enumerate(targets) if item.get("state") not in {"connected", "skipped"}), 0)
  633. self._connection_show_target(payload, index)
  634. state = self._connection_state
  635. if state is not None and state["phase"] != "waiting":
  636. self._ring_bell(prompt=True, context=t("cli.connect.bell_context"))
  637. def _connection_send(self, call, *args) -> None:
  638. """One card answer to the gateway, off the UI thread; its outcome arrives as connection.update."""
  639. state = self._connection_state
  640. agent = getattr(self, "agent", None)
  641. if not state or agent is None:
  642. self._connection_close()
  643. return
  644. op_id = state["payload"].get("op_id")
  645. def _run() -> None:
  646. from hermes_cli.gateway_client import GatewayClientError
  647. try:
  648. getattr(agent, call)(*args)
  649. except GatewayClientError as exc: # the gateway refused or was unreachable: say so on the card
  650. current = self._connection_state
  651. if current and current["payload"].get("op_id") == op_id:
  652. current["target"] = {**current["target"], "detail": str(exc) or t("cli.connect.cannot_restart")}
  653. current["phase"] = "failed"
  654. self._paint_now()
  655. from agent.memory_provider import spawn_context_thread
  656. spawn_context_thread(_run, name="hermes-connection-answer").start()
  657. def _connection_answer(self, *, approve: bool) -> None:
  658. state = self._connection_state
  659. if not state:
  660. return
  661. target = state["target"]
  662. name = str(target.get("name") or "")
  663. answer = {"name": name, "status": "approved" if approve else "skipped"}
  664. if approve:
  665. answer["env"] = dict(state.get("drafts", {}).get(name, {}))
  666. state["phase"] = "waiting"
  667. self._paint_now()
  668. self._connection_send("connection_respond", state["payload"].get("op_id"), {"targets": [answer]})
  669. def _connection_retry(self) -> None:
  670. state = self._connection_state
  671. if not state:
  672. return
  673. target = state["target"]
  674. if not (target.get("kind") == "connector" and target.get("state") in {"failed", "expired"}) \
  675. and target.get("state") in {"pending", "failed", "expired"}:
  676. # Connect on a pending or failed install row is the same attempt with the draft's values.
  677. self._connection_answer(approve=True)
  678. return
  679. # A dead sign-in link (or any other re-run): the gateway re-mints it on the open operation.
  680. state["phase"] = "waiting"
  681. self._paint_now()
  682. self._connection_send("connection_retry", str(target.get("name") or ""))
  683. def _connection_continue(self) -> None:
  684. # Stays open (waiting) until the gateway's settling update closes it, so a refused answer
  685. # shows on the card instead of vanishing with it.
  686. state = self._connection_state
  687. if not state:
  688. return
  689. state["phase"] = "waiting"
  690. self._paint_now()
  691. self._connection_send("connection_respond", state["payload"].get("op_id"), {"settled_by": "continue"})
  692. def _connection_open_url(self) -> None:
  693. state = self._connection_state
  694. if state and state.get("phase") == "url" and state["target"].get("connect_url"):
  695. webbrowser.open(state["target"]["connect_url"])
  696. def _connection_cancel(self) -> None:
  697. self._connection_answer(approve=False)
  698. def _connection_interrupt(self) -> None:
  699. # The turn's interrupt reaches the gateway, which ends the operation; only the card is ours.
  700. self._connection_close()
  701. def _connection_on_change(self, snapshot) -> None:
  702. state = self._connection_state
  703. if not state or not isinstance(snapshot, dict):
  704. return
  705. if "op_id" not in snapshot and snapshot.get("settled"):
  706. self._connection_close() # a replay-gap recovery found no open operation: the card is stale
  707. return
  708. if snapshot.get("op_id") != state["payload"].get("op_id"):
  709. return
  710. if int(snapshot.get("seq") or 0) < int(state["payload"].get("seq") or 0):
  711. return # an older frame than the one the card holds
  712. if snapshot.get("settled") or snapshot.get("settled_at") is not None:
  713. self._connection_close()
  714. return
  715. active_name = state["target"].get("name")
  716. target = next((item for item in snapshot.get("targets") or () if item.get("name") == active_name), None)
  717. if target is None:
  718. return
  719. state["payload"] = snapshot
  720. state["target"] = target
  721. target_state = target.get("state")
  722. if target_state == "initiated" and target.get("connect_url"):
  723. state["phase"] = "url"
  724. elif target_state == "failed":
  725. state["phase"] = "failed"
  726. elif target_state == "pending" and self._connection_fields(target):
  727. if state["phase"] == "form":
  728. state["payload"] = snapshot # still being filled in: keep the field and unsent input
  729. return
  730. # The backend refused the answer because a required field is still empty: reopen the
  731. # form on the first one it named, over the draft the panel kept.
  732. missing = {field.get("name") for field in self._connection_fields(target)}
  733. names = [field.get("name") for field in state.get("fields") or []]
  734. state["field_index"] = next((i for i, name in enumerate(names) if name in missing), 0)
  735. state["phase"] = "form"
  736. self._connection_sync_input_buffer()
  737. elif target_state == "connected" and target.get("discovery_error"):
  738. state["phase"] = "authorized"
  739. elif target_state in {"connected", "skipped"}:
  740. unresolved = [
  741. item for item in snapshot.get("targets") or ()
  742. if item.get("state") not in {"connected", "skipped"}
  743. ]
  744. if unresolved:
  745. self._connection_show_target(snapshot, (snapshot.get("targets") or []).index(unresolved[0]))
  746. return
  747. state["phase"] = "connected"
  748. else:
  749. state["phase"] = "waiting"
  750. self._paint_now()
  751. def _connection_set_field(self, value: str) -> None:
  752. """Save the active input row in the private draft and advance to the next row/action."""
  753. state = self._connection_state
  754. if not state or state.get("phase") not in {"form", "failed"}:
  755. return
  756. fields = state.get("fields") or []
  757. index = state.get("field_index", 0)
  758. if not (0 <= index < len(fields)):
  759. return
  760. field = fields[index]
  761. state["drafts"][state["target"].get("name", "")][field.get("name")] = value
  762. state["field_index"] = min(index + 1, len(fields))
  763. self._connection_sync_input_buffer()
  764. self._paint_now()
  765. def _connection_submit(self) -> None:
  766. """Enter action for prompt_toolkit bindings: URL open, selected action, or field advance."""
  767. state = self._connection_state
  768. if not state:
  769. return
  770. phase = state.get("phase")
  771. if phase == "url":
  772. self._connection_open_url()
  773. elif phase == "authorized":
  774. self._connection_continue()
  775. elif phase in {"form", "failed"} and state.get("field_index", 0) >= len(state.get("fields") or []):
  776. (self._connection_retry if state.get("selected", 0) == 0 else self._connection_cancel)()
  777. def _connection_field_lines(self, state, target) -> list[str]:
  778. draft = state.get("drafts", {}).get(target.get("name", ""), {})
  779. lines = []
  780. for field in state.get("fields") or ():
  781. marker = "*" if field.get("required") else ""
  782. value = t("cli.connect.secret_set") if field.get("type") == "secret" and draft.get(field.get("name")) else draft.get(field.get("name"), "")
  783. lines.append(f"{field.get('prompt') or field.get('name')}{marker}: {value}")
  784. return lines
  785. def _connection_render_lines(self) -> list[str]:
  786. """Panel copy without exposing secret drafts; the prompt_toolkit renderer consumes these rows."""
  787. state = self._connection_state
  788. if not state:
  789. return []
  790. target = state["target"]
  791. phase = state.get("phase")
  792. buttons = f"{t('cli.connect.button_connect')} {t('cli.connect.button_cancel')}"
  793. lines = [t("cli.connect.set_up", name=target.get("name", ""))]
  794. if target.get("instructions"):
  795. lines.append(str(target["instructions"]))
  796. if phase == "form":
  797. lines.extend(self._connection_field_lines(state, target))
  798. lines.append(buttons)
  799. elif phase == "url":
  800. lines.extend([str(target.get("connect_url") or ""), str(target.get("detail") or ""), t("cli.connect.press_enter_open")])
  801. elif phase == "failed":
  802. lines.append(str(target.get("detail") or t("cli.connect.failed")))
  803. lines.extend(self._connection_field_lines(state, target))
  804. lines.append(buttons)
  805. elif phase == "authorized":
  806. # A connected row cannot be re-run inside this operation; the agent retries discovery
  807. # with its next manage_connections call, which needs no new consent.
  808. lines.extend([t("cli.connect.authorized_no_tools"), t("cli.connect.button_continue")])
  809. elif phase == "connected":
  810. lines.append(t("cli.connect.connected"))
  811. if target.get("alias"):
  812. from tools.tool_labels import app_title
  813. lines.append(t("cli.connect.named_account", name=app_title(target.get("name", "")), alias=target["alias"]))
  814. else:
  815. lines.append(str(target.get("detail") or t("cli.connect.waiting")))
  816. return [line for line in lines if line]
  817. # --- Batch clarify (multi-question, issue #18450) -----------------------
  818. def _clarify_batch_set_active(self, state, index) -> None:
  819. """Point the batch clarify panel at question ``index``: mirror it into the flat keys the
  820. keybindings/renderer read so ↑/↓/Space/number keys work unchanged;
  821. open-ended drops into freetext; re-visiting restores the earlier cursor/checkboxes."""
  822. questions_list = state["questions"]
  823. index = max(0, min(index, len(questions_list) - 1))
  824. entry = questions_list[index]
  825. choices = entry["choices"] or []
  826. state["active"] = index
  827. state["question"] = entry["question"]
  828. state["choices"] = choices
  829. state["selected"] = 0
  830. state["multi_select"] = bool(entry["multi_select"])
  831. state["selected_indices"] = set() if entry["multi_select"] else None
  832. self._clarify_freetext = not entry["choices"]
  833. self._clarify_multi_base = None
  834. meta = (state.get("answer_meta") or {}).get(entry["qid"])
  835. if meta is None:
  836. return
  837. kind = meta.get("kind")
  838. if kind == "choice":
  839. answer = state["answers"].get(entry["qid"])
  840. if answer in choices:
  841. state["selected"] = choices.index(answer)
  842. elif kind == "other":
  843. state["selected"] = len(choices)
  844. elif kind == "multi":
  845. checked = {choices.index(c) for c in meta.get("choices") or [] if c in choices}
  846. if meta.get("other_text"):
  847. checked.add(len(choices))
  848. state["selected_indices"] = checked
  849. def _clarify_batch_lock(self, state, answer, meta=None) -> None:
  850. """Lock ``answer`` for the active batch question (overwriting an earlier one) and advance to
  851. the next unanswered; ``meta`` ({"kind": "choice"|"other"|"multi", ...}) lets a re-visit
  852. restore the cursor / prefill an "Other" edit. All answered → resolve the queue, tear down."""
  853. entry = state["questions"][state["active"]]
  854. state["answers"][entry["qid"]] = answer
  855. state.setdefault("answer_meta", {})[entry["qid"]] = meta or {"kind": "choice"}
  856. self._persist_prompt_summary("?", t("cli.clarify.label"), entry["question"], "" if answer is None else str(answer))
  857. total = len(state["questions"])
  858. for offset in range(1, total + 1):
  859. candidate = (state["active"] + offset) % total
  860. if state["questions"][candidate]["qid"] not in state["answers"]:
  861. self._clarify_batch_set_active(state, candidate)
  862. return
  863. try:
  864. state["response_queue"].put(dict(state["answers"]))
  865. except Exception:
  866. pass
  867. self._clarify_state = None
  868. self._clarify_freetext = False
  869. self._clarify_multi_base = None
  870. def _clarify_batch_enter(self, state) -> None:
  871. """Enter in batch choice mode: lock the active selection. Multi-select locks a JSON array of
  872. checked labels (parsed by the tool core); "Other" switches to freetext, prefilled with an
  873. earlier typed answer so Enter on an answered Other edits instead of retyping."""
  874. choices = state.get("choices") or []
  875. selected = state.get("selected", 0)
  876. entry = state["questions"][state["active"]]
  877. meta = (state.get("answer_meta") or {}).get(entry["qid"]) or {}
  878. if state.get("multi_select"):
  879. sorted_idx = sorted(state.get("selected_indices") or set())
  880. selected_choices = [choices[i] for i in sorted_idx if i < len(choices)]
  881. if len(choices) in sorted_idx:
  882. # Stash the checked real choices so the freetext submit appends the typed answer.
  883. self._clarify_multi_base = selected_choices
  884. self._clarify_freetext = True
  885. self._clarify_prefill = meta.get("other_text") or ""
  886. return
  887. self._clarify_batch_lock(
  888. state,
  889. json.dumps(selected_choices, ensure_ascii=False),
  890. meta={"kind": "multi", "choices": selected_choices, "other_text": ""})
  891. return
  892. if selected < len(choices):
  893. self._clarify_batch_lock(state, choices[selected], meta={"kind": "choice"})
  894. return
  895. self._clarify_freetext = True
  896. self._clarify_prefill = meta.get("other_text") or "" if meta.get("kind") == "other" else ""
  897. def _clarify_callback(self, questions):
  898. """Clarify-tool platform callback (agent thread, #18450): the batch panel (A-compact) shows
  899. all questions, one active, and blocks until the key bindings lock every answer. Returns
  900. ``{"answers": {qid: raw | None}, "outcome"}`` (None = skipped): ``submitted`` when every
  901. question is locked, ``timed_out`` when the deadline expires, ``cancelled`` on an interrupt."""
  902. from cli import CLI_CONFIG, _DIM, _RST, _cprint
  903. from tools.clarify_gateway import resolve_clarify_timeout
  904. timeout = resolve_clarify_timeout(CLI_CONFIG)
  905. response_queue = queue.Queue()
  906. state = {
  907. "questions": list(questions),
  908. "answers": {},
  909. "answer_meta": {},
  910. "active": 0,
  911. "response_queue": response_queue,
  912. # Flat keys mirroring the active question — filled by _clarify_batch_set_active.
  913. "question": "",
  914. "choices": [],
  915. "selected": 0,
  916. "multi_select": False,
  917. "selected_indices": None}
  918. self._clarify_state = state
  919. self._clarify_batch_set_active(state, 0)
  920. self._clarify_deadline = None if timeout <= 0 else _time.monotonic() + timeout
  921. self._ring_bell(prompt=True, context=t("cli.clarify.bell_context"))
  922. self._paint_now()
  923. result = self._poll_modal_queue(response_queue, "_clarify_deadline")
  924. if result is not _TIMED_OUT:
  925. self._clarify_deadline = None
  926. outcome = "cancelled" if result is None else "submitted"
  927. return {"answers": dict(state["answers"]), "outcome": outcome}
  928. partial = dict(state["answers"])
  929. self._clarify_teardown()
  930. _cprint(f"\n{_DIM}{t('cli.clarify.timed_out_locked_answers', timeout=timeout)}{_RST}")
  931. return {"answers": partial, "outcome": "timed_out"}
  932. def _withdraw_gateway_modal(self, method) -> None:
  933. """The gateway withdrew the server request this CLI's modal is answering (``request.cancel``:
  934. another viewer completed it, or its wait ended): close that modal as if cancelled locally, so
  935. the blocked agent thread returns. Called from the gateway connection's thread."""
  936. # Each modal's response queue is an unbounded queue.Queue: put() never blocks or raises.
  937. if method == "clarify" and self._clarify_state:
  938. state = self._clarify_state
  939. self._clarify_teardown()
  940. state["response_queue"].put(None)
  941. elif method in ("sudo", "vault.unlock_prompt", "vault.save_login", "vault.code") and self._sudo_state:
  942. # The vault prompts reuse the sudo panel's state and queue; "" ends them as declined.
  943. self._sudo_state["response_queue"].put("")
  944. elif method == "secret" and getattr(self, "_secret_state", None):
  945. self._cancel_secret_capture()
  946. def _sudo_password_callback(self) -> str:
  947. """Prompt for a sudo password through the prompt_toolkit UI (agent thread); clarify-style
  948. state + queue answered by the Enter binding."""
  949. from cli import _DIM, _RST, _cprint
  950. response_queue = queue.Queue()
  951. self._capture_modal_input_snapshot()
  952. self._sudo_state = {"response_queue": response_queue}
  953. self._sudo_deadline = _time.monotonic() + 45
  954. self._ring_bell(prompt=True, context=t("cli.secret.bell_sudo"))
  955. self._paint_now()
  956. result = self._poll_modal_queue(response_queue, "_sudo_deadline", refresh=0)
  957. self._sudo_state = None
  958. self._sudo_deadline = 0
  959. self._restore_modal_input_snapshot()
  960. self._paint_now()
  961. if result is _TIMED_OUT:
  962. _cprint(f"\n{_DIM} {t('cli.secret.sudo_timeout')}{_RST}")
  963. return ""
  964. if result:
  965. _cprint(f"\n{_DIM} {t('cli.secret.sudo_received')}{_RST}")
  966. else:
  967. _cprint(f"\n{_DIM} {t('cli.secret.sudo_skipped')}{_RST}")
  968. return result
  969. def _approval_callback(self, command: str, description: str,
  970. *, allow_permanent: bool = True,
  971. allow_session: bool = True,
  972. smart_denied: bool = False) -> str:
  973. """Dangerous-command approval through the prompt_toolkit UI (agent thread).
  974. Choices: once / session / always / deny (see ``_approval_choices``), plus 'view' for long
  975. commands. ``_approval_lock`` serializes concurrent requests (parallel delegation subtasks)
  976. so the shared ``_approval_state`` / ``_approval_deadline`` aren't clobbered.
  977. """
  978. from cli import CLI_CONFIG, _DIM, _RST, _cprint
  979. with self._approval_lock:
  980. timeout = int(CLI_CONFIG.get("approvals", {}).get("timeout", 300))
  981. response_queue = queue.Queue()
  982. self._approval_state = {
  983. "command": command,
  984. "description": description,
  985. "choices": self._approval_choices(
  986. command,
  987. allow_permanent=allow_permanent,
  988. allow_session=allow_session,
  989. smart_denied=smart_denied),
  990. "selected": 0,
  991. "response_queue": response_queue}
  992. self._approval_deadline = _time.monotonic() + timeout
  993. self._ring_bell(prompt=True, context=t("cli.approval.bell_context"), detail=command)
  994. self._paint_now()
  995. result = self._poll_modal_queue(response_queue, "_approval_deadline")
  996. self._approval_state = None
  997. self._approval_deadline = 0
  998. self._paint_now()
  999. if result is _TIMED_OUT:
  1000. _cprint(f"\n{_DIM} {t('cli.approval.timeout_denying')}{_RST}")
  1001. self._persist_prompt_summary(
  1002. "⚠", t("cli.approval.label"), command, t("cli.approval.timed_out_no_response"))
  1003. return "timeout"
  1004. self._persist_prompt_summary(
  1005. "⚠", t("cli.approval.label"), command, _approval_outcome_label(result))
  1006. return result
  1007. def _approval_choices(self, command: str, *, allow_permanent: bool = True,
  1008. allow_session: bool = True,
  1009. smart_denied: bool = False) -> list[str]:
  1010. """Smart-DENY overrides and re-ask-every-time gates (allow_session=False) show only
  1011. once/deny; ``allow_permanent=False`` for another reason hides only 'always'."""
  1012. if smart_denied or not allow_session:
  1013. choices = ["once", "deny"]
  1014. elif allow_permanent:
  1015. choices = ["once", "session", "always", "deny"]
  1016. else:
  1017. choices = ["once", "session", "deny"]
  1018. if len(command) > 70:
  1019. choices.append("view")
  1020. return choices
  1021. def _handle_approval_selection(self) -> None:
  1022. """Process the currently selected dangerous-command approval choice."""
  1023. state = self._approval_state
  1024. if not state:
  1025. return
  1026. selected = state.get("selected", 0)
  1027. choices = state.get("choices")
  1028. if not isinstance(choices, list):
  1029. choices = []
  1030. if not (0 <= selected < len(choices)):
  1031. return
  1032. chosen = choices[selected]
  1033. if chosen == "view":
  1034. state["show_full"] = True
  1035. state["choices"] = [choice for choice in choices if choice != "view"]
  1036. if state["selected"] >= len(state["choices"]):
  1037. state["selected"] = max(0, len(state["choices"]) - 1)
  1038. self._invalidate()
  1039. return
  1040. state["response_queue"].put(chosen)
  1041. self._approval_state = None
  1042. self._invalidate()
  1043. def _vault_unlock_callback(self, backend_name: str, display_name: str) -> str:
  1044. """Masked master-password prompt for an external password manager (agent thread).
  1045. Reuses the sudo panel state so rendering, Enter/ESC handling and interrupt cleanup are shared."""
  1046. from cli import _DIM, _RST, _cprint
  1047. response_queue = queue.Queue()
  1048. self._capture_modal_input_snapshot()
  1049. self._sudo_state = {"response_queue": response_queue, "vault_backend": display_name}
  1050. self._sudo_deadline = _time.monotonic() + 120
  1051. self._ring_bell(prompt=True, context=t("cli.secret.bell_unlock", name=display_name))
  1052. self._paint_now()
  1053. result = self._poll_modal_queue(response_queue, "_sudo_deadline", refresh=0)
  1054. self._sudo_state = None
  1055. self._sudo_deadline = 0
  1056. self._restore_modal_input_snapshot()
  1057. self._paint_now()
  1058. if result is _TIMED_OUT or not result:
  1059. _cprint(f"\n{_DIM} {t('cli.secret.stays_locked', name=display_name)}{_RST}")
  1060. return ""
  1061. _cprint(f"\n{_DIM} {t('cli.secret.unlocking_for_session', name=display_name)}{_RST}")
  1062. return result
  1063. def _vault_save_login_callback(self, origin: str, site: str):
  1064. """Two-step "save this login" prompt (identifier shown, password masked) on the sudo panel; the
  1065. answer goes to the vault store, never to the model. None = declined."""
  1066. from cli import _DIM, _RST, _cprint
  1067. answer: dict = {}
  1068. for step in ("identifier", "password"):
  1069. response_queue = queue.Queue()
  1070. self._capture_modal_input_snapshot()
  1071. self._sudo_state = {"response_queue": response_queue, "vault_save": {"site": site, "origin": origin,
  1072. "step": step}}
  1073. self._sudo_deadline = _time.monotonic() + 180
  1074. if step == "identifier":
  1075. self._ring_bell(prompt=True, context=t("cli.secret.bell_save_login", site=site))
  1076. self._paint_now()
  1077. result = self._poll_modal_queue(response_queue, "_sudo_deadline", refresh=0)
  1078. self._sudo_state = None
  1079. self._sudo_deadline = 0
  1080. self._restore_modal_input_snapshot()
  1081. self._paint_now()
  1082. if result is _TIMED_OUT or not result:
  1083. _cprint(f"\n{_DIM} {t('cli.secret.login_not_saved', site=site)}{_RST}")
  1084. return None
  1085. answer[step] = result
  1086. _cprint(f"\n{_DIM} {t('cli.secret.login_saved', site=site)}{_RST}")
  1087. return answer
  1088. def _vault_code_callback(self, site: str, hint: str) -> str:
  1089. """One-time-code prompt (shown as typed; a 6-digit code is not a secret worth masking and users
  1090. need to see typos) on the sudo panel. "" = declined/timed out."""
  1091. from cli import _DIM, _RST, _cprint
  1092. response_queue = queue.Queue()
  1093. self._capture_modal_input_snapshot()
  1094. self._sudo_state = {"response_queue": response_queue, "vault_code": {"site": site, "hint": hint}}
  1095. self._sudo_deadline = _time.monotonic() + 180
  1096. self._ring_bell(prompt=True, context=t("cli.secret.bell_verification_code", site=site))
  1097. self._paint_now()
  1098. result = self._poll_modal_queue(response_queue, "_sudo_deadline", refresh=0)
  1099. self._sudo_state = None
  1100. self._sudo_deadline = 0
  1101. self._restore_modal_input_snapshot()
  1102. self._paint_now()
  1103. if result is _TIMED_OUT or not result:
  1104. _cprint(f"\n{_DIM} {t('cli.secret.code_not_entered', site=site)}{_RST}")
  1105. return ""
  1106. _cprint(f"\n{_DIM} {t('cli.secret.code_entered', site=site)}{_RST}")
  1107. return result
  1108. def _secret_capture_callback(self, var_name: str, prompt: str, metadata=None) -> dict:
  1109. self._capture_modal_input_snapshot()
  1110. try:
  1111. return prompt_for_secret(self, var_name, prompt, metadata)
  1112. finally:
  1113. self._restore_modal_input_snapshot()
  1114. self._paint_now()
  1115. def _capture_modal_input_snapshot(self) -> None:
  1116. """Temporarily clear the input buffer and save the user's in-progress draft."""
  1117. if getattr(self, "_modal_input_snapshot", None) is not None or not getattr(self, "_app", None):
  1118. return
  1119. try:
  1120. buf = self._app.current_buffer
  1121. self._modal_input_snapshot = {"text": buf.text, "cursor_position": buf.cursor_position}
  1122. buf.reset()
  1123. except Exception:
  1124. self._modal_input_snapshot = None
  1125. def _restore_modal_input_snapshot(self) -> None:
  1126. """Restore any draft text that was present before a modal prompt opened."""
  1127. snapshot = getattr(self, "_modal_input_snapshot", None)
  1128. self._modal_input_snapshot = None
  1129. if not snapshot or not getattr(self, "_app", None):
  1130. return
  1131. try:
  1132. buf = self._app.current_buffer
  1133. buf.text = snapshot.get("text", "")
  1134. buf.cursor_position = min(snapshot.get("cursor_position", 0), len(buf.text))
  1135. except Exception:
  1136. pass
  1137. def _clear_active_overlays_for_interrupt(self) -> None:
  1138. """Drain and clear every input-blocking overlay left by an interrupted agent: the worker
  1139. thread is gone but the state dict still gates input (frozen terminal until its timeout).
  1140. Push a safe value onto each queue (approval -> "deny", others -> cancel), nil the state,
  1141. restore the draft; each step is wrapped so a dead queue can't block the others."""
  1142. def _put(state, value) -> None:
  1143. try:
  1144. state["response_queue"].put(value)
  1145. except Exception:
  1146. pass
  1147. if self._approval_state:
  1148. _put(self._approval_state, "deny")
  1149. self._approval_state = None
  1150. if self._connection_state:
  1151. self._connection_interrupt()
  1152. if self._clarify_state:
  1153. _put(self._clarify_state, None)
  1154. self._clarify_state = None
  1155. self._clarify_freetext = False
  1156. self._clarify_multi_base = None
  1157. if self._sudo_state:
  1158. _put(self._sudo_state, "")
  1159. self._sudo_state = None
  1160. self._sudo_deadline = 0
  1161. self._restore_modal_input_snapshot()
  1162. if self._secret_state:
  1163. try:
  1164. self._cancel_secret_capture()
  1165. except Exception:
  1166. self._secret_state = None
  1167. def _submit_secret_response(self, value: str) -> None:
  1168. if not self._secret_state:
  1169. return
  1170. self._secret_state["response_queue"].put(value)
  1171. self._secret_state = None
  1172. self._secret_deadline = 0
  1173. self._paint_now() # direct paint so the secret panel clears at once (no throttle)
  1174. def _cancel_secret_capture(self) -> None:
  1175. self._submit_secret_response("")
  1176. def _clear_secret_input_buffer(self) -> None:
  1177. if getattr(self, "_app", None):
  1178. try:
  1179. self._app.current_buffer.reset()
  1180. except Exception:
  1181. pass