import dataclasses import os import subprocess import sys import time import typing 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], int] execv: typing.Callable[[str, list[str]], None] git: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]] input: typing.Callable[[str], str] local_time: typing.Callable[[float], str] now: typing.Callable[[], float] on_terminal: typing.Callable[[], bool] python: typing.Callable[[list[str]], subprocess.CompletedProcess[str]] sleep: typing.Callable[[float], None] stream_claude: typing.Callable[[list[str], str], Streaming] class StreamingClaude: def __init__(self, args: list[str], cwd: str) -> None: self.proc = subprocess.Popen(["claude", *args], cwd=cwd, 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: subprocess.run(["claude", *args], cwd=cwd).returncode, execv=os.execv, git=lambda args, cwd: subprocess.run(["git", *args], capture_output=True, cwd=cwd, text=True), input=input, local_time=lambda seconds: time.strftime("%Y-%m-%d %H:%M %Z", time.localtime(seconds)), now=time.time, on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(), python=lambda args: subprocess.run([sys.executable, *args], capture_output=True, text=True), sleep=time.sleep, stream_claude=StreamingClaude, )