from __future__ import annotations import asyncio import os import tempfile from typing import Iterable class TmuxError(RuntimeError): pass async def _run(*args: str) -> tuple[int, str, str]: proc = await asyncio.create_subprocess_exec( *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) out, err = await proc.communicate() return proc.returncode or 0, out.decode("utf-8", "replace"), err.decode("utf-8", "replace") class TmuxSession: def __init__(self, name: str): self.name = name async def exists(self) -> bool: code, _, _ = await _run("tmux", "has-session", "-t", self.name) return code == 0 async def kill(self) -> None: await _run("tmux", "kill-session", "-t", self.name) async def create_window_with_cmd(self, cmd: str, *, width: int = 220, height: int = 60) -> None: if await self.exists(): raise TmuxError(f"session {self.name!r} already exists") code, _, err = await _run( "tmux", "new-session", "-d", "-s", self.name, "-x", str(width), "-y", str(height), cmd, ) if code != 0: raise TmuxError(f"new-session failed: {err}") async def split_pane(self, *, vertical: bool, target_pane: int, cmd: str, percentage: int = 50) -> None: flag = "-v" if vertical else "-h" code, _, err = await _run( "tmux", "split-window", flag, "-p", str(percentage), "-t", f"{self.name}:0.{target_pane}", cmd, ) if code != 0: raise TmuxError(f"split-window failed: {err}") async def select_layout(self, layout: str) -> None: await _run("tmux", "select-layout", "-t", f"{self.name}:0", layout) async def send_keys(self, pane: int, keys: Iterable[str]) -> None: cmd = ["tmux", "send-keys", "-t", f"{self.name}:0.{pane}"] cmd.extend(keys) code, _, err = await _run(*cmd) if code != 0: raise TmuxError(f"send-keys failed: {err}") async def paste_text(self, pane: int, text: str) -> None: """Load text into a tmux buffer and paste it into the pane. Uses a temp file so multiline / special chars / UTF-8 survive intact. """ with tempfile.NamedTemporaryFile("w", encoding="utf-8", delete=False) as f: f.write(text) tmp = f.name try: buf = f"aichess-{os.getpid()}-{pane}" code, _, err = await _run("tmux", "load-buffer", "-b", buf, tmp) if code != 0: raise TmuxError(f"load-buffer failed: {err}") code, _, err = await _run("tmux", "paste-buffer", "-b", buf, "-t", f"{self.name}:0.{pane}") if code != 0: raise TmuxError(f"paste-buffer failed: {err}") await _run("tmux", "delete-buffer", "-b", buf) finally: try: os.unlink(tmp) except OSError: pass async def submit(self, pane: int, text: str) -> None: """Paste text and press Enter to submit.""" await self.paste_text(pane, text) await self.send_keys(pane, ["Enter"]) async def capture_pane(self, pane: int, *, escape: bool = True, history: int = 0) -> str: args = ["tmux", "capture-pane", "-p", "-t", f"{self.name}:0.{pane}"] if escape: args.insert(2, "-e") if history > 0: args.extend(["-S", f"-{history}"]) code, out, err = await _run(*args) if code != 0: raise TmuxError(f"capture-pane failed: {err}") return out