Files
claude-config/bin/loop_claude/effects.py
T

73 lines
2.9 KiB
Python

import dataclasses
import os
import subprocess
import sys
import time
import typing
# 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 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]
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]
# 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,
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, 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")