terminal_notify.py 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. """Terminal-native desktop notifications: OSC 9 and Warp's OSC 777 CLI-agent protocol.
  2. OSC 9 (``ESC ] 9 ; <body> BEL``): Ghostty, iTerm2, Kitty and WezTerm raise an OS notification;
  3. others drop it. OSC 777 (``ESC ] 777 ; notify ; warp://cli-agent ; <json> BEL``): Warp's
  4. structured CLI-agent protocol (tab status + notification mailbox).
  5. Inside the running CLI, ``HermesCLI._ring_bell`` sends ``notification_sequence()`` through the
  6. prompt_toolkit output on the app loop (a second writer on the tty would splice into an in-flight kitty
  7. pet frame). ``write_tty`` is the no-app path: ``/dev/tty`` because ``patch_stdout``'s wrapper strips raw
  8. escapes, falling back to ``sys.stdout`` when ``/dev/tty`` can't be opened (Windows, no controlling
  9. terminal). Never raises.
  10. """
  11. from __future__ import annotations
  12. import json
  13. import os
  14. import re
  15. import sys
  16. _C0_AND_DEL = re.compile(r"[\x00-\x1f\x7f]")
  17. _WARP_PROTOCOL_VERSION = 1
  18. # Last Warp release per channel that set WARP_CLI_AGENT_PROTOCOL_VERSION but could not render
  19. # structured payloads (Warp's should-use-structured.sh). Bash compares lexicographically; so do we.
  20. _WARP_LAST_BROKEN = {"stable": "v0.2026.03.25.08.24.stable_05", "preview": "v0.2026.03.25.08.24.preview_05"}
  21. def write_tty(seq: str) -> None:
  22. """Write raw escapes to /dev/tty, falling back to sys.stdout. Never raises."""
  23. try:
  24. with open("/dev/tty", "w", encoding="utf-8") as tty:
  25. tty.write(seq)
  26. return
  27. except OSError:
  28. pass
  29. try:
  30. sys.stdout.write(seq)
  31. sys.stdout.flush()
  32. except Exception:
  33. pass
  34. def osc9(body: str) -> str:
  35. """OSC 9 sequence with C0 controls and DEL stripped from the body."""
  36. return f"\x1b]9;{_C0_AND_DEL.sub('', body)}\x07"
  37. def warp_supported(env=None) -> bool:
  38. """True when running in a Warp build that can render OSC 777 agent payloads."""
  39. env = os.environ if env is None else env
  40. client = env.get("WARP_CLIENT_VERSION", "")
  41. if env.get("TERM_PROGRAM") != "WarpTerminal" or not env.get("WARP_CLI_AGENT_PROTOCOL_VERSION") or not client:
  42. return False
  43. return not any(channel in client and client <= last_broken for channel, last_broken in _WARP_LAST_BROKEN.items())
  44. def warp_osc777(event: str, detail: str, session_id: str = "") -> str:
  45. """OSC 777 ``warp://cli-agent`` notification; ``event`` is ``stop`` or ``permission_request``."""
  46. try:
  47. advertised = int(os.environ.get("WARP_CLI_AGENT_PROTOCOL_VERSION", "1"))
  48. except ValueError:
  49. advertised = 1
  50. cwd = os.getcwd()
  51. payload = {"v": min(advertised, _WARP_PROTOCOL_VERSION), "agent": "hermes", "event": event,
  52. "session_id": session_id, "cwd": cwd, "project": os.path.basename(cwd)}
  53. payload["summary" if event == "permission_request" else "response"] = detail[:200]
  54. return f"\x1b]777;notify;warp://cli-agent;{json.dumps(payload, separators=(',', ':'))}\x07"
  55. def notification_sequence(context: str, *, prompt: bool, session_id: str = "", detail: str = "") -> str:
  56. """OSC 9 (plus Warp OSC 777 when supported) for a blocking prompt or turn end."""
  57. seq = osc9(f"Hermes: {context}")
  58. if warp_supported():
  59. event = "permission_request" if prompt else "stop"
  60. seq += warp_osc777(event, detail or context, session_id)
  61. return seq