cli_terminal_input.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. """Classic-CLI terminal input helpers: file-drop/attachment path resolution, bracketed-paste patching, extended Enter-key sequences, CPR leak guards and TUI input-height estimation.
  2. Split out of ``cli.py``; ``cli`` re-exports every public name and moved bodies late-bind
  3. cli-level names through ``from cli import ...`` at call time so facade monkeypatch seams hold.
  4. """
  5. from __future__ import annotations
  6. import logging
  7. import os
  8. import re
  9. import shutil
  10. import sys
  11. import time
  12. from contextlib import suppress
  13. from pathlib import Path
  14. from typing import Dict, Any, Optional, Mapping
  15. from urllib.parse import unquote, urlparse
  16. from agent.i18n import t
  17. # Log-record parity with the origin module.
  18. logger = logging.getLogger("cli")
  19. def _cli():
  20. """Late import of the ``cli`` facade: mutable CLI module state (and its test seams) lives there."""
  21. import cli
  22. return cli
  23. _IMAGE_EXTENSIONS = frozenset({
  24. '.png', '.jpg', '.jpeg', '.gif', '.webp',
  25. '.bmp', '.tiff', '.tif', '.svg', '.ico',
  26. })
  27. def _termux_example_image_path(filename: str = "cat.png") -> str:
  28. """Return a realistic example media path for the current Termux setup."""
  29. candidates = [
  30. os.path.expanduser("~/storage/shared"),
  31. "/sdcard",
  32. "/storage/emulated/0",
  33. "/storage/self/primary",
  34. ]
  35. # Literal "/" so the Android hint is right even on Windows.
  36. for root in candidates:
  37. if os.path.isdir(root):
  38. return f"{root}/Pictures/{filename}"
  39. return f"~/storage/shared/Pictures/{filename}"
  40. def _split_path_input(raw: str) -> tuple[str, str]:
  41. r"""Split a leading path token (quoted or with ``\ `` escapes) from trailing free-form text."""
  42. raw = str(raw or "").strip()
  43. if not raw:
  44. return "", ""
  45. if raw[0] in {'"', "'"}:
  46. quote = raw[0]
  47. pos = 1
  48. while pos < len(raw):
  49. ch = raw[pos]
  50. if ch == '\\' and pos + 1 < len(raw):
  51. pos += 2
  52. continue
  53. if ch == quote:
  54. return raw[1:pos], raw[pos + 1 :].strip()
  55. pos += 1
  56. return raw[1:], ""
  57. pos = 0
  58. while pos < len(raw):
  59. ch = raw[pos]
  60. if ch == '\\' and pos + 1 < len(raw) and raw[pos + 1] == ' ':
  61. pos += 2
  62. elif ch == ' ':
  63. break
  64. else:
  65. pos += 1
  66. return raw[:pos].replace('\\ ', ' '), raw[pos:].strip()
  67. def _resolve_attachment_path(raw_path: str) -> Path | None:
  68. """Resolve a user-supplied attachment path (quotes, ``~``, env vars, ``file://``; relative to TERMINAL_CWD).
  69. Returns ``None`` unless it resolves to an existing file.
  70. """
  71. token = str(raw_path or "").strip()
  72. if not token:
  73. return None
  74. if token[0] == token[-1] and token[0] in {'"', "'"}:
  75. token = token[1:-1].strip()
  76. token = token.replace('\\ ', ' ')
  77. if not token:
  78. return None
  79. expanded = token
  80. if token.startswith("file://"):
  81. try:
  82. parsed = urlparse(token)
  83. if parsed.scheme == "file":
  84. expanded = unquote(parsed.path or "")
  85. if parsed.netloc and os.name == "nt":
  86. expanded = f"//{parsed.netloc}{expanded}"
  87. elif os.name == "nt" and len(expanded) >= 3 and expanded[0] == "/" and expanded[1].isalpha() and expanded[2] == ":":
  88. # file:///C:/... parses to path "/C:/..." — drop the leading slash
  89. # so it resolves as a drive-letter path.
  90. expanded = expanded[1:]
  91. except Exception:
  92. expanded = token
  93. expanded = os.path.expandvars(os.path.expanduser(expanded))
  94. if os.name != "nt":
  95. normalized = expanded.replace("\\", "/")
  96. if len(normalized) >= 3 and normalized[1] == ":" and normalized[2] == "/" and normalized[0].isalpha():
  97. expanded = f"/mnt/{normalized[0].lower()}/{normalized[3:]}"
  98. path = Path(expanded)
  99. if not path.is_absolute():
  100. base_dir = Path(os.getenv("TERMINAL_CWD", os.getcwd()))
  101. path = base_dir / path
  102. try:
  103. resolved = path.resolve()
  104. except Exception:
  105. resolved = path
  106. # ENAMETOOLONG for a pasted `/goal <long prose>` that passed the `/` prefilter
  107. # would otherwise reach process_loop and silently lose the input.
  108. try:
  109. if not resolved.exists() or not resolved.is_file():
  110. return None
  111. except OSError:
  112. return None
  113. return resolved
  114. def _file_drop_result(path: Path, remainder: str) -> dict:
  115. from cli import _IMAGE_EXTENSIONS
  116. return {"path": path, "is_image": path.suffix.lower() in _IMAGE_EXTENSIONS, "remainder": remainder}
  117. def _detect_file_drop(user_input: str) -> dict | None:
  118. """Detect a dragged/pasted file path at the start of *user_input* -> ``{path, is_image, remainder}`` or None."""
  119. from cli import _file_drop_result, _resolve_attachment_path, _split_path_input
  120. if not isinstance(user_input, str):
  121. return None
  122. stripped = user_input.strip()
  123. if not stripped:
  124. return None
  125. # Optionally quoted; then /, ~, ./, ../, a Windows drive prefix, or (unquoted) file://.
  126. quoted = stripped[:1] in {"'", '"'}
  127. unquoted = stripped[1:] if quoted else stripped
  128. starts_like_path = (
  129. unquoted.startswith(("/", "~", "./", "../"))
  130. or (not quoted and unquoted.startswith("file://"))
  131. or (len(unquoted) >= 3 and unquoted[1] == ":" and unquoted[2] in {"\\", "/"} and unquoted[0].isalpha())
  132. )
  133. if not starts_like_path:
  134. return None
  135. direct_path = _resolve_attachment_path(stripped)
  136. if direct_path is not None:
  137. return _file_drop_result(direct_path, "")
  138. first_token, remainder = _split_path_input(stripped)
  139. drop_path = _resolve_attachment_path(first_token)
  140. if drop_path is None and " " in stripped and not quoted:
  141. for pos in reversed([idx for idx, ch in enumerate(stripped) if ch == " "]):
  142. drop_path = _resolve_attachment_path(stripped[:pos].rstrip())
  143. if drop_path is not None:
  144. remainder = stripped[pos + 1 :].strip()
  145. break
  146. if drop_path is None:
  147. return None
  148. return _file_drop_result(drop_path, remainder)
  149. def _format_image_attachment_badges(attached_images: list[Path], image_counter: int, width: int | None = None) -> str:
  150. """Attached-image badge row: compact summary on narrow terminals, per-image badges otherwise."""
  151. if not attached_images:
  152. return ""
  153. width = width or shutil.get_terminal_size((80, 24)).columns
  154. def _trunc(name: str, limit: int) -> str:
  155. return name if len(name) <= limit else name[: max(1, limit - 3)] + "..."
  156. if width < 52:
  157. if len(attached_images) == 1:
  158. return f"[📎 {_trunc(attached_images[0].name, 20)}]"
  159. return t("cli.terminal.image_badge_count", count=len(attached_images))
  160. if width < 80:
  161. if len(attached_images) == 1:
  162. return f"[📎 {_trunc(attached_images[0].name, 32)}]"
  163. return f"[📎 {_trunc(attached_images[0].name, 20)}] [+{len(attached_images) - 1}]"
  164. base = image_counter - len(attached_images) + 1
  165. return " ".join(t("cli.terminal.image_badge_numbered", index=base + i) for i in range(len(attached_images)))
  166. def _should_auto_attach_clipboard_image_on_paste(pasted_text: str) -> bool:
  167. """Auto-attach clipboard images only for image-only paste gestures."""
  168. return not pasted_text.strip()
  169. def _hermes_call_output_screen_diff(
  170. orig_osd, app, output, screen, current_pos, color_depth, previous_screen, last_style, is_done, full_screen,
  171. attrs_for_style_string, style_string_has_style, size, previous_width,
  172. ):
  173. """prompt_toolkit ``_output_screen_diff`` with resize guards.
  174. Inflates ``previous_screen.height`` when the new screen is taller so pt skips the
  175. cursor move that stamps chrome into scrollback; on a corrupt previous paint buffer
  176. (tmux re-attach) retries once as a first paint instead of crashing the loop.
  177. 1. 2. On AttributeError/TypeError from a corrupt previous paint buffer (classic after tmux attach with
  178. same width), retry once with ``previous_screen=None`` so pt first-paints cleanly instead of crashing the
  179. event loop with ``'cell' object has no attribute 'char'``. See #26137.
  180. """
  181. try:
  182. if previous_screen is not None and hasattr(previous_screen, "height") and previous_screen.height < screen.height:
  183. previous_screen.height = screen.height
  184. except Exception:
  185. pass
  186. common = (app, output, screen, current_pos, color_depth)
  187. tail = (is_done, full_screen, attrs_for_style_string, style_string_has_style, size)
  188. try:
  189. return orig_osd(*common, previous_screen, last_style, *tail, previous_width)
  190. except (AttributeError, TypeError):
  191. # Corrupt previous_screen / row cells after client reattach: previous_screen=None
  192. # takes the first-paint erase path, previous_width=0 treats the width as changed.
  193. return orig_osd(*common, None, None, *tail, 0)
  194. def _apply_bracketed_paste_timeout_patch() -> None:
  195. """Patch ``Vt100Parser.feed`` to flush a bracketed paste whose ESC[201~ end mark never arrives.
  196. Without it a dropped end mark (SSH glitch, sleep/wake) freezes input forever. Idempotent.
  197. """
  198. try:
  199. import prompt_toolkit.input.vt100_parser as _vt100_mod
  200. from prompt_toolkit.keys import Keys as _PtKeys
  201. from prompt_toolkit.key_binding.key_processor import KeyPress as _PtKeyPress
  202. if getattr(_vt100_mod, "_hermes_bp_timeout_patched", False):
  203. return
  204. _BP_TIMEOUT_S = 2.0
  205. def _patched_vt100_feed(self_parser, data: str) -> None:
  206. if self_parser._in_bracketed_paste:
  207. self_parser._paste_buffer += data
  208. end_mark = "\x1b[201~"
  209. if end_mark in self_parser._paste_buffer:
  210. end_index = self_parser._paste_buffer.index(end_mark)
  211. paste_content = self_parser._paste_buffer[:end_index]
  212. self_parser.feed_key_callback(_PtKeyPress(_PtKeys.BracketedPaste, paste_content))
  213. self_parser._in_bracketed_paste = False
  214. remaining = self_parser._paste_buffer[end_index + len(end_mark):]
  215. self_parser._paste_buffer = ""
  216. self_parser._hermes_bp_start = None
  217. if remaining:
  218. _patched_vt100_feed(self_parser, remaining)
  219. else:
  220. bp_start = getattr(self_parser, "_hermes_bp_start", None)
  221. now = time.monotonic()
  222. if bp_start is None:
  223. self_parser._hermes_bp_start = now
  224. elif now - bp_start > _BP_TIMEOUT_S:
  225. paste_content = self_parser._paste_buffer
  226. self_parser._in_bracketed_paste = False
  227. self_parser._paste_buffer = ""
  228. self_parser._hermes_bp_start = None
  229. if paste_content:
  230. self_parser.feed_key_callback(_PtKeyPress(_PtKeys.BracketedPaste, paste_content))
  231. logger.warning(
  232. "Bracketed-paste timeout (%.1fs) — flushed %d bytes "
  233. "without end mark. Terminal may have dropped ESC[201~ "
  234. "(see #16263).",
  235. now - bp_start, len(paste_content),
  236. )
  237. else:
  238. # Re-inlined: calling the original would double-buffer after entering paste mode.
  239. for i, c in enumerate(data):
  240. if self_parser._in_bracketed_paste:
  241. _patched_vt100_feed(self_parser, data[i:])
  242. break
  243. self_parser._input_parser.send(c)
  244. _vt100_mod.Vt100Parser.feed = _patched_vt100_feed
  245. _vt100_mod._hermes_bp_timeout_patched = True
  246. logger.debug("Applied Vt100Parser bracketed-paste timeout patch (#16263)")
  247. except Exception as exc:
  248. logger.debug("Bracketed-paste timeout patch skipped: %s", exc)
  249. # CPR replies (``ESC[<row>;<col>R``) can race past the input parser under resize storms
  250. # and land as literal text; the ``^[[...R`` form appears when a filter stripped the ESC.
  251. # Cursor Position Report (CPR / DSR) response, format ``ESC[<row>;<col>R``. prompt_toolkit's _on_resize() +
  252. # renderer send ``ESC[6n`` queries to the terminal; under resize storms or tab switches the terminal's reply
  253. # can race past the input parser and end up in the input buffer as literal text (see issue #14692). Also
  254. # matches the visible-form ``^[[<row>;<col>R`` that appears when the ESC byte was stripped by a prior
  255. # filter.
  256. _DSR_CPR_ESC_RE = re.compile(r"\x1b\[\d+;\d+R")
  257. _DSR_CPR_VISIBLE_RE = re.compile(r"\^\[\[\d+;\d+R")
  258. _SGR_MOUSE_ESC_RE = re.compile(r"\x1b\[<\d+;\d+;\d+[Mm]")
  259. _SGR_MOUSE_VISIBLE_RE = re.compile(r"\^\[\[<\d+;\d+;\d+[Mm]")
  260. # Bare "<btn;col;rowM" fragments; deliberately broad, they are almost never intentional input.
  261. _SGR_MOUSE_BARE_RE = re.compile(r"<\d+;\d+;\d+[Mm]")
  262. _TERMINAL_INPUT_MODE_RESET_SEQ = (
  263. "\x1b[?1006l\x1b[?1003l\x1b[?1002l\x1b[?1000l" # mouse: SGR, any-motion, button-motion, click
  264. "\x1b[?1004l" # focus events
  265. "\x1b[?2004l" # bracketed paste
  266. "\x1b[?1049l" # leave alt screen
  267. "\x1b[<u" # pop kitty keyboard mode
  268. "\x1b[>4m" # reset modifyOtherKeys
  269. "\x1b[0m\x1b[?25h" # reset attributes, show cursor
  270. )
  271. _KITTY_KEYBOARD_PUSH_SEQ = "\x1b[>1u"
  272. _MODIFY_OTHER_KEYS_SEQ = "\x1b[>4;2m"
  273. _EXTENDED_ENTER_KEYS_SEQ = _KITTY_KEYBOARD_PUSH_SEQ + _MODIFY_OTHER_KEYS_SEQ
  274. _BACKSLASH_LINE_CONTINUATION_RE = re.compile(r"\\[ \t]*$")
  275. def _is_ghostty_terminal(env: Optional[Mapping[str, str]] = None) -> bool:
  276. """Whether the terminal is Ghostty.
  277. Ghostty gets ONLY modifyOtherKeys: its Kitty disambiguate mode strips Alt from
  278. Backspace (upstream bug), breaking backward-kill-word.
  279. Ghostty implements modifyOtherKeys correctly (it then emits ``\\x1b[27;3;127~``, which the alias table
  280. also maps). See #87630.
  281. """
  282. env = os.environ if env is None else env
  283. return (env.get("TERM_PROGRAM") or "").strip() == "ghostty" or (env.get("TERM") or "").strip().lower() == "xterm-ghostty"
  284. def _terminal_supports_extended_enter_keys(env: Optional[Mapping[str, str]] = None) -> bool:
  285. """Allowlist of terminals where requesting modified-Enter reporting is safe (aligned with the Ink TUI)."""
  286. env = os.environ if env is None else env
  287. term_program = (env.get("TERM_PROGRAM") or "").strip()
  288. term = (env.get("TERM") or "").strip().lower()
  289. return bool(
  290. env.get("WT_SESSION")
  291. or term_program in {"iTerm.app", "WezTerm", "ghostty", "vscode"}
  292. or env.get("KITTY_WINDOW_ID") or "kitty" in term
  293. or term == "xterm-ghostty"
  294. or term.startswith("tmux") or term_program.lower() == "tmux"
  295. )
  296. def _enable_extended_enter_keys(output=None, env: Optional[Mapping[str, str]] = None) -> bool:
  297. """Ask allowlisted terminals to report modified keys distinctly.
  298. Pushes BOTH kitty keyboard protocol and xterm modifyOtherKeys (kitty dropped the
  299. latter; tmux/VS Code only accept it). Both re-encode modified keys as sequences
  300. stock prompt_toolkit barely maps (Ctrl+C once arrived as ``ESC[99;5u``), so
  301. ``install_modify_other_keys_aliases()`` must have run first. Ghostty gets only
  302. modifyOtherKeys. The exit reset pops both modes.
  303. Under either protocol the terminal re-encodes modified keys as escape sequences — Kitty disambiguate
  304. mode as ``ESC[<codepoint>;<mod>u`` (plus the Esc key as ``ESC[27u``), modifyOtherKeys=2 as
  305. ``ESC[27;<mod>;<codepoint>~``. Stock prompt_toolkit 3.x maps almost none of these, which is why the CSI
  306. >1u push was temporarily removed in 87074 (Ctrl+C arrived as ``ESC[99;5u`` and died, #56684).
  307. ``install_modify_other_keys_aliases()`` (called at CLI startup from ``hermes_cli.pt_input_extras``) now
  308. populates ``ANSI_SEQUENCES`` with the full Ctrl/Alt/Shift/multi-modifier and functional-key tables under
  309. BOTH formats, so every existing key binding continues to fire — including Ctrl+C, which is handled by
  310. prompt_toolkit's ``c-c`` binding (raw mode clears ISIG, so the kernel INTR path was never in play for
  311. the CLI).
  312. See #87630.
  313. """
  314. from cli import _EXTENDED_ENTER_KEYS_SEQ, _MODIFY_OTHER_KEYS_SEQ, _is_ghostty_terminal, _terminal_supports_extended_enter_keys
  315. if not _terminal_supports_extended_enter_keys(env):
  316. return False
  317. seq = _MODIFY_OTHER_KEYS_SEQ if _is_ghostty_terminal(env) else _EXTENDED_ENTER_KEYS_SEQ
  318. try:
  319. if output is not None and hasattr(output, "write_raw"):
  320. output.write_raw(seq)
  321. output.flush()
  322. return True
  323. if sys.stdout is not None and sys.stdout.isatty():
  324. sys.stdout.write(seq)
  325. sys.stdout.flush()
  326. return True
  327. except Exception:
  328. pass
  329. return False
  330. def _cli_multiline_shortcuts_enabled(config: Optional[dict[str, Any]] = None) -> bool:
  331. """``display.cli_multiline_shortcuts`` (default on: Ctrl+J = newline; off restores the legacy c-j submit)."""
  332. if config is None:
  333. config = _cli().CLI_CONFIG
  334. display = config.get("display") if isinstance(config, dict) else None
  335. value = display.get("cli_multiline_shortcuts", True) if isinstance(display, dict) else True
  336. if isinstance(value, bool):
  337. return value
  338. return not (isinstance(value, str) and value.strip().lower() in {"0", "false", "no", "off", "disabled"})
  339. def _is_backslash_line_continuation(text: str) -> bool:
  340. """True when Enter should turn a trailing backslash into a newline."""
  341. from cli import _BACKSLASH_LINE_CONTINUATION_RE
  342. return bool(_BACKSLASH_LINE_CONTINUATION_RE.search(text or ""))
  343. def _apply_backslash_line_continuation(text: str) -> str:
  344. """Replace a trailing ``\\`` marker with an actual newline."""
  345. from cli import _BACKSLASH_LINE_CONTINUATION_RE
  346. return _BACKSLASH_LINE_CONTINUATION_RE.sub("", text or "") + "\n"
  347. def _preserve_ctrl_enter_newline() -> bool:
  348. """Environments delivering Ctrl+Enter as bare LF (Windows Terminal, WSL, SSH, Ghostty): c-j must stay newline.
  349. See issue #22379.
  350. """
  351. env = os.environ
  352. if (
  353. sys.platform == "win32"
  354. or any(env.get(v) for v in ("SSH_CONNECTION", "SSH_CLIENT", "SSH_TTY", "WT_SESSION",
  355. "GHOSTTY_RESOURCES_DIR", "GHOSTTY_BIN_DIR"))
  356. or env.get("TERM", "").lower() == "xterm-ghostty" or env.get("TERM_PROGRAM", "").lower() == "ghostty"
  357. or "microsoft" in env.get("WSL_DISTRO_NAME", "").lower()
  358. ):
  359. return True
  360. # WSL env vars can be scrubbed under sudo; also peek /proc.
  361. for p in ("/proc/version", "/proc/sys/kernel/osrelease"):
  362. try:
  363. with open(p, "r", encoding="utf-8-sig", errors="ignore") as f:
  364. if "microsoft" in f.read().lower():
  365. return True
  366. except OSError:
  367. continue
  368. return False
  369. def _bind_prompt_submit_keys(kb, handler, *, multiline_shortcuts_enabled: Optional[bool] = None) -> None:
  370. """Enter always submits; c-j submits only with multiline shortcuts off AND where Ctrl+Enter isn't c-j.
  371. Even when the setting is disabled, environments where Ctrl+Enter is known to arrive as c-j (Windows,
  372. WSL, SSH, Windows Terminal, Ghostty) keep c-j reserved for newline; otherwise Ctrl+Enter submits instead
  373. of composing. See _preserve_ctrl_enter_newline() and issue #22379.
  374. """
  375. from cli import _cli_multiline_shortcuts_enabled, _preserve_ctrl_enter_newline
  376. if multiline_shortcuts_enabled is None:
  377. multiline_shortcuts_enabled = _cli_multiline_shortcuts_enabled()
  378. kb.add("enter")(handler)
  379. if sys.platform != "win32" and not multiline_shortcuts_enabled and not _preserve_ctrl_enter_newline():
  380. kb.add("c-j")(handler)
  381. def _disable_prompt_toolkit_cpr_warning(app) -> None:
  382. """Let prompt_toolkit fall back from CPR without printing into the prompt."""
  383. with suppress(Exception):
  384. app.renderer.cpr_not_supported_callback = None
  385. def _terminal_may_leak_cpr() -> bool:
  386. """Suppress prompt_toolkit CPR queries (delayed replies leak into input); Windows keeps pt's default.
  387. Delayed CPR replies (``ESC[<row>;<col>R`` / visible ``^[[<row>;<col>R``) leak into the status line and
  388. can freeze input when the reply is slow (#13870 on SSH/slow PTYs). The same race hits local POSIX TTYs
  389. under heavy subagent / status-line load — see ``tests/hermes_cli/test_cpr_local_leak.py``.
  390. """
  391. return os.environ.get("PROMPT_TOOLKIT_NO_CPR", "") == "1" or sys.platform != "win32"
  392. def _build_cpr_disabled_output(stdout):
  393. """Vt100_Output with ``enable_cpr=False`` (``from_pty()`` doesn't expose it), or None on failure.
  394. prompt_toolkit's renderer sends ``ESC[6n`` (Device Status Report) to learn the cursor row before
  395. painting in non-fullscreen mode; the terminal replies ``ESC[<row>;<col>R``. When that reply is delayed
  396. it races into the display as raw ``^[[39;1R`` and can stall the renderer's pending-CPR future (#13870;
  397. also local POSIX under heavy subagent load).
  398. """
  399. try:
  400. import io as _io
  401. from prompt_toolkit.output.vt100 import Vt100_Output, _get_size
  402. from prompt_toolkit.data_structures import Size
  403. def _get_term_size():
  404. rows = columns = None
  405. try:
  406. rows, columns = _get_size(stdout.fileno())
  407. except (OSError, _io.UnsupportedOperation, AttributeError, ValueError):
  408. pass
  409. return Size(rows=rows or 24, columns=columns or 80)
  410. return Vt100_Output(stdout, _get_term_size, enable_cpr=False)
  411. except Exception:
  412. return None
  413. def _select_classic_cli_pt_output(stdout):
  414. """CPR-disabled ``Vt100_Output`` when CPR may leak, else None (Application keeps pt's default)."""
  415. from cli import _build_cpr_disabled_output, _terminal_may_leak_cpr
  416. return _build_cpr_disabled_output(stdout) if _terminal_may_leak_cpr() else None
  417. def _strip_leaked_terminal_responses_with_meta(text: str) -> tuple[str, bool]:
  418. """Strip leaked CPR replies and mouse-report fragments -> ``(cleaned, had_mouse_reports)``."""
  419. from cli import _DSR_CPR_ESC_RE, _DSR_CPR_VISIBLE_RE, _SGR_MOUSE_BARE_RE, _SGR_MOUSE_ESC_RE, _SGR_MOUSE_VISIBLE_RE
  420. if not text:
  421. return text, False
  422. had_mouse_reports = False
  423. for present, cpr_re, mouse_re in (
  424. ("\x1b[" in text, _DSR_CPR_ESC_RE, _SGR_MOUSE_ESC_RE),
  425. ("^[" in text, _DSR_CPR_VISIBLE_RE, _SGR_MOUSE_VISIBLE_RE),
  426. ("<" in text and ";" in text and ("M" in text or "m" in text), None, _SGR_MOUSE_BARE_RE),
  427. ):
  428. if not present:
  429. continue
  430. if cpr_re is not None:
  431. text = cpr_re.sub("", text)
  432. text, count = mouse_re.subn("", text)
  433. had_mouse_reports = had_mouse_reports or count > 0
  434. return text, had_mouse_reports
  435. def _estimate_tui_input_height(
  436. lines: list[str] | tuple[str, ...], prompt_text: str, terminal_columns: int, *, max_height: int = 8,
  437. ) -> int:
  438. """Input rows from live terminal cells; the BeforeInput prompt consumes cells only on line 0.
  439. Never substitute a fake wide fallback: a mis-sized TextArea leaves stale cells at the bottom.
  440. """
  441. from cli import _int_or
  442. try:
  443. from prompt_toolkit.utils import get_cwidth
  444. except Exception:
  445. get_cwidth = lambda value: len(value or "") # type: ignore[assignment]
  446. columns = max(1, _int_or(terminal_columns or 0, 0))
  447. prompt_width = max(0, get_cwidth(prompt_text or ""))
  448. visual_lines = 0
  449. for index, line in enumerate(lines or [""]):
  450. display_width = get_cwidth(line or "") + (prompt_width if index == 0 else 0)
  451. visual_lines += max(1, -(-display_width // columns))
  452. return min(max(visual_lines, 1), max(1, int(max_height or 1)))
  453. def _status_bar_visible_from_display_config(display_config: object) -> bool:
  454. """Initial status-bar visibility; both YAML ``off`` (False) and strings like ``"hidden"`` mean off."""
  455. if not isinstance(display_config, dict):
  456. display_config = {}
  457. statusbar_config = display_config.get("statusbar", display_config.get("tui_statusbar", "top"))
  458. if isinstance(statusbar_config, str):
  459. return statusbar_config.strip().lower() not in {"0", "false", "hidden", "no", "off"}
  460. return statusbar_config is not False
  461. def _collect_query_images(query: str | None, image_arg: str | None = None) -> tuple[str, list[Path]]:
  462. """Collect local image attachments for single-query CLI flows."""
  463. from cli import _IMAGE_EXTENSIONS, _detect_file_drop, _resolve_attachment_path
  464. message = query or ""
  465. images: list[Path] = []
  466. if isinstance(message, str):
  467. dropped = _detect_file_drop(message)
  468. if dropped and dropped.get("is_image"):
  469. images.append(dropped["path"])
  470. message = dropped["remainder"] or f"[User attached image: {dropped['path'].name}]"
  471. if image_arg:
  472. explicit_path = _resolve_attachment_path(image_arg)
  473. if explicit_path is None:
  474. raise ValueError(f"Image file not found: {image_arg}")
  475. if explicit_path.suffix.lower() not in _IMAGE_EXTENSIONS:
  476. raise ValueError(f"Not a supported image file: {explicit_path}")
  477. images.append(explicit_path)
  478. return message, list(dict.fromkeys(images))