import dataclasses import os import subprocess import sys import termios import time import typing from failure import Failure import git_repo from machine_load.memory import Memory, read_memory # Seconds before a Python script loop-claude runs is stopped, so a hung one, such as chunk-preflight, cannot hold the loop. PYTHON_TIMEOUT = 600 class Git(typing.Protocol): """Runs git in cwd, as git_repo.git does.""" def __call__(self, *args: str, cwd: str) -> str | Failure: ... class Streaming(typing.Protocol): """A started claude whose stream-json lines arrive as it works.""" def lines(self) -> typing.Iterable[str]: ... def wait(self) -> int: ... @dataclasses.dataclass(frozen=True) class Effects: claude: typing.Callable[[list[str], str, str], subprocess.CompletedProcess[str]] claude_on_terminal: typing.Callable[[list[str], str, dict[str, str]], int] # Drops what was typed on the terminal and not yet read. discard_typed: typing.Callable[[], None] execv: typing.Callable[[str, list[str]], None] git: Git input: typing.Callable[[str], str] local_time: typing.Callable[[float], str] # The machine's memory; None where it cannot be read. memory: typing.Callable[[], Memory | None] now: typing.Callable[[], float] on_terminal: typing.Callable[[], bool] # Runs a Python script in a directory, as run_python does. python: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]] sleep: typing.Callable[[float], None] stream_claude: typing.Callable[[list[str], str, dict[str, str]], Streaming] class StreamingClaude: def __init__(self, args: list[str], cwd: str, env: dict[str, str]) -> None: self.proc = subprocess.Popen(["claude", *args], cwd=cwd, env={**os.environ, **env}, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, stdout=subprocess.PIPE) def lines(self) -> typing.Iterable[str]: with self.proc: yield from self.proc.stdout or () def wait(self) -> int: return self.proc.wait() def system_effects() -> Effects: return Effects( claude=lambda args, cwd, stdin: subprocess.run(["claude", *args], capture_output=True, cwd=cwd, input=stdin, text=True), claude_on_terminal=lambda args, cwd, env: subprocess.run(["claude", *args], cwd=cwd, env={**os.environ, **env}).returncode, discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH), execv=os.execv, git=git_repo.git, input=input, local_time=lambda seconds: time.strftime("%Y-%m-%d %H:%M %Z", time.localtime(seconds)), memory=read_memory, now=time.time, on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(), python=lambda args, cwd: run_python(args, cwd, PYTHON_TIMEOUT), sleep=time.sleep, stream_claude=StreamingClaude, ) def run_python(args: list[str], cwd: str, timeout: float) -> subprocess.CompletedProcess[str]: """Runs a Python script in cwd. One that cannot start, or still runs after timeout seconds and is stopped, reads as exit 1, saying why on stderr.""" command = [sys.executable, *args] try: return subprocess.run(command, capture_output=True, cwd=cwd, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, timeout=timeout) except OSError as failure: return subprocess.CompletedProcess(command, 1, "", f"could not start: {failure}") except subprocess.TimeoutExpired: return subprocess.CompletedProcess(command, 1, "", f"stopped after {timeout} s")