"""One `claude -p --output-format stream-json` run, as loop-claude's judge and the replays start it.""" import dataclasses import subprocess import typing from failure import Failure from claude_code.entries import hit_limit, json_object, limit_said # Effects.claude: claude's arguments, its working directory and the prompt it reads on stdin. Claude = typing.Callable[[list[str], str, str], subprocess.CompletedProcess[str]] @dataclasses.dataclass(frozen=True) class Limited: """claude hit a usage limit; said is claude's message about it, and resets_at is when the limit resets, in seconds since the epoch, or None when unknown.""" resets_at: int | None said: str # No persistence, so these runs stay out of the session picker; Claude Code then writes no transcript, so stream-json, which prints one, lets a caller keep it. claude_reply reads the reply from the stream's last line. -p needs --verbose with stream-json. No permission prompt, as no one answers it. HEADLESS = ["--no-session-persistence", "--output-format", "stream-json", "--verbose", "--permission-mode", "bypassPermissions"] def claude_reply(claude: Claude, args: list[str], cwd: str, prompt: str, who: str) -> dict | Failure | Limited: """claude's reply to `claude -p ` and HEADLESS, the result event that ends its stream, or why there is none; who, such as "the judge", names the run in the message for a non-zero exit or a last line that isn't a json object.""" try: proc = claude(["-p", *args, *HEADLESS], cwd, prompt) except OSError as failure: return Failure(f"could not start claude: {failure.strerror}") last = proc.stdout.strip().rpartition("\n")[2] reply = json_object(last) # The result event names the reset only in prose, such as "resets 7:40pm (Europe/Stockholm)", so its limit carries no reset time; the stream's rate_limit_event holds it as a time, which nothing reads here yet. if reply is not None and hit_limit(reply): return Limited(None, limit_said(reply)) if proc.returncode != 0: return Failure(proc.stderr.strip() or f"{who} exited {proc.returncode}") if reply is None: return Failure(f"{who} printed no json reply; its last line was: {last or 'nothing'}") return reply