"""The files by which a loop-claude that waits for the human shows its question in loop-inbox, and takes an answer typed there. A waiting loop keeps one file per session, .json, in Paths.waiting, and removes it once answered or stopped. Its state says whether it waits for an answer, or has claude open for it, on the loop's own terminal or in loop-inbox. loop-inbox answers by replacing .answer. The answer names the ask it answers by its id, so an answer meant for an earlier question, or sent as the loop took an answer on its terminal, never answers a later one. /talk from loop-inbox goes in three steps, so that only one claude ever holds the worker's session: 1. loop-inbox's claim_talk sends ClaudeOpening, with its pid. 2. The loop stops reading its terminal and republishes its ask as OpenInInbox with that pid. claim_talk returns True once it reads that, and loop-inbox opens claude. 3. loop-inbox sends ClaudeEnded once claude exits, which the loop reads with claude_ended. The loop also stops waiting if loop-inbox's process is gone. """ import dataclasses import json import pathlib import typing from failure import Failure from file_writes import make_private, replace_json # Seconds between a loop's looks for an answer from loop-inbox, and for the end of the claude loop-inbox opened. POLL_SECONDS = 0.5 # Seconds loop-inbox waits for a loop to make way for its claude: ten of the loop's looks, so a loop slow for a moment still makes way. MAKE_WAY_SECONDS = 10 * POLL_SECONDS # What the human types, on the loop's terminal or in loop-inbox, to open claude for the ask; interrupt.py says who picked it. TALK = "/talk" @dataclasses.dataclass(frozen=True) class ClaudeCommand: """How claude opens on a terminal: its arguments, its folder and what it adds to the environment.""" args: list[str] cwd: str env: dict[str, str] @dataclasses.dataclass(frozen=True) class Asking: """The ask waits for an answer; talk opens the worker's claude session for /talk.""" talk: ClaudeCommand @dataclasses.dataclass(frozen=True) class OpenOnTerminal: """claude is open for the ask on the loop's own terminal, and takes no answer from loop-inbox.""" @dataclasses.dataclass(frozen=True) class OpenInInbox: """claude is open for the ask in the loop-inbox whose process is pid.""" pid: int AskState = Asking | OpenOnTerminal | OpenInInbox @dataclasses.dataclass(frozen=True) class Ask: """An interrupt's question, as loop-inbox lists it.""" id: str session: str # The checkout the loop runs in. root: str question: str # When the loop asked, in seconds since the epoch. asked: float pid: int state: AskState @dataclasses.dataclass(frozen=True) class Typed: text: str @dataclasses.dataclass(frozen=True) class ClaudeOpening: """loop-inbox, whose process is pid, asks the loop to make way for the claude it opens for /talk.""" pid: int @dataclasses.dataclass(frozen=True) class ClaudeEnded: """The claude loop-inbox opened for the ask has ended.""" # What answers a waiting ask. Answer = Typed | ClaudeOpening Message = Answer | ClaudeEnded def ask_file(folder: pathlib.Path, session: str) -> pathlib.Path: return folder / f"{session}.json" def answer_file(folder: pathlib.Path, session: str) -> pathlib.Path: return folder / f"{session}.answer" def publish(folder: pathlib.Path, ask: Ask) -> Failure | None: try: make_private(folder) except OSError as failure: return Failure(f"cannot make {folder}: {failure.strerror}") return replace_json(ask_file(folder, ask.session), dataclasses.asdict(ask) | {"state": tagged(ask.state)}) def withdraw(folder: pathlib.Path, session: str) -> Failure | None: """Removes the session's ask and any answer to it.""" for path in (ask_file(folder, session), answer_file(folder, session)): try: path.unlink(missing_ok=True) except OSError as failure: return Failure(f"cannot remove {path}: {failure.strerror}") return None def waiting(folder: pathlib.Path, alive: typing.Callable[[int], bool]) -> list[Ask]: """The asks of loops still running, oldest first. A file that cannot be read or parsed is left out, as is one being replaced.""" try: paths = sorted(folder.glob("*.json")) except OSError: return [] asks = [ask for path in paths if (ask := read_ask(path)) and alive(ask.pid)] return sorted(asks, key=lambda ask: ask.asked) def read_ask(path: pathlib.Path) -> Ask | None: """The ask in path; None where a field has the wrong type, or names another session than path does.""" try: data = json.loads(path.read_text(encoding="utf-8")) ask = Ask(**{**data, "state": ask_state(data["state"])}) except (OSError, ValueError, TypeError, KeyError): return None texts = all(isinstance(text, str) for text in (ask.id, ask.session, ask.root, ask.question)) # A pid of 0 or below would name a process group to alive. return ask if texts and ask.session == path.stem and isinstance(ask.asked, int | float) and isinstance(ask.pid, int) and ask.pid > 0 else None def ask_state(data: object) -> AskState: match data: case {"kind": "Asking", "talk": {"args": list(args), "cwd": str(cwd), "env": dict(env)}} if all(isinstance(text, str) for text in [*args, *env.values()]): return Asking(ClaudeCommand(args, cwd, env)) case {"kind": "OpenOnTerminal"}: return OpenOnTerminal() case {"kind": "OpenInInbox", "pid": int(pid)}: return OpenInInbox(pid) raise ValueError(f"not an ask's state: {data!r}") def send(folder: pathlib.Path, ask: Ask, message: Message) -> Failure | None: return replace_json(answer_file(folder, ask.session), {"ask": ask.id, **tagged(message)}) def tagged(value: AskState | Message) -> dict[str, object]: """value's fields, with its kind, which read_ask and received read it back by.""" return dataclasses.asdict(value) | {"kind": type(value).__name__} def answered(folder: pathlib.Path, ask: Ask) -> Answer | None: """The answer loop-inbox sent to this ask; None for none, or one meant for another ask of the session.""" message = received(folder, ask) return message if isinstance(message, Typed | ClaudeOpening) else None def claude_ended(folder: pathlib.Path, ask: Ask) -> bool: """Whether loop-inbox said the claude it opened for this ask has ended.""" return isinstance(received(folder, ask), ClaudeEnded) def received(folder: pathlib.Path, ask: Ask) -> Message | None: try: data = json.loads(answer_file(folder, ask.session).read_text(encoding="utf-8")) except (OSError, ValueError): return None if not isinstance(data, dict) or data.get("ask") != ask.id: return None match data: case {"kind": "Typed", "text": str(text)}: return Typed(text) case {"kind": "ClaudeOpening", "pid": int(pid)}: return ClaudeOpening(pid) case {"kind": "ClaudeEnded"}: return ClaudeEnded() return None def claim_talk(folder: pathlib.Path, ask: Ask, pid: int, now: typing.Callable[[], float], sleep: typing.Callable[[float], None]) -> bool | Failure: """loop-inbox's side of /talk: asks the loop to make way for a claude that the loop-inbox whose process is pid opens for ask. True once the loop shows it has stopped reading its terminal, within MAKE_WAY_SECONDS; False where it was answered first, or stopped, or didn't make way in time.""" if unsent := send(folder, ask, ClaudeOpening(pid)): return unsent deadline = now() + MAKE_WAY_SECONDS while now() < deadline: current = read_ask(ask_file(folder, ask.session)) if current is None or current.id != ask.id: return False if current.state == OpenInInbox(pid): return True if not isinstance(current.state, Asking): return False sleep(0.1) # Takes the claim back: a loop that reads it late waits for no claude, and one that made way late, or failed to show it had, ends its wait. send(folder, ask, ClaudeEnded()) return False