import dataclasses import sys import typing import uuid from loop_claude.waiting import answered, Ask, Asking, claude_ended, ClaudeCommand, ClaudeOpening, OpenInInbox, OpenOnTerminal, POLL_SECONDS, publish, TALK, Typed, withdraw from loop_claude.effects import Effects, say from failure import Failure from claude_code.transcript import human_turns, read_transcript from loop_claude.stop import needs_human, needs_terminal, Stop from loop_claude.paths import Paths from model_routing.ladder import Rung from loop_claude.cycle.states import Talk from claude_code.trust import trust from loop_claude.project.checkout import worktrees ANSWER_QUESTION = "answer the question above" # ASK_ANSWER was picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it. ASK_ANSWER = f"Answer ({TALK} opens claude, Enter stops the loop): " @dataclasses.dataclass(frozen=True) class WorkerSession: """The worker's claude session, which /talk opens on loop-claude's terminal or in loop-inbox.""" root: str id: uuid.UUID rung: Rung transcript_path: str # Added to the environment of the worker's claude, and of the claude /talk opens. env: dict[str, str] def claude_command(self) -> ClaudeCommand: return ClaudeCommand(claude_args(self.rung, ["--resume", str(self.id)]), self.root, self.env) def put_question(question: str, answer_here: bool, session: WorkerSession, paths: Paths, effects: Effects) -> str | Talk | Stop: """Prints question for the human. Where answer_here, shows it in loop-inbox too and returns the first answer, typed at loop-claude's terminal or in loop-inbox: the line, stripped, or a Talk where they type TALK. Else a Talk at once, on the terminal. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends.""" say(f"\n{question}", effects) if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()): return stop # Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, the first line answers; the rest wait, and the next question drops them. A longer answer goes through TALK. effects.discard_typed() ask = Ask(effects.new_id(), str(session.id), session.root, question, effects.now(), effects.pid(), Asking(session.claude_command())) if not answer_here: return Talk(ask, OpenOnTerminal()) shown(paths, ask, effects) answer: str | Talk | Stop | None = None try: answer = first_answer(ask, paths, effects) return answer finally: # A Talk keeps ask listed, under its id, for talk to show loop-inbox where claude opens. if not isinstance(answer, Talk): withdrawn(paths, ask, effects) def first_answer(ask: Ask, paths: Paths, effects: Effects) -> str | Talk | Stop: try: answer = effects.input_or(ASK_ANSWER, lambda: answered(paths.waiting, ask)) except EOFError: print(file=sys.stderr) # Ends the prompt's line. It isn't a message, so it gets no time. return needs_human(ANSWER_QUESTION, "the input ended") match answer: case ClaudeOpening(pid): return Talk(ask, OpenInInbox(pid)) case Typed(text): say(f"Answered in loop-inbox: {text}", effects) case str(text): pass case _: typing.assert_never(answer) text = text.strip() if not text: return needs_human(ANSWER_QUESTION, "nothing was typed") return Talk(ask, OpenOnTerminal()) if text == TALK else text def shown(paths: Paths, ask: Ask, effects: Effects) -> None: """Shows ask in loop-inbox. A failure only warns. The question is then still answered on the terminal, unless claude was to open in loop-inbox: loop-inbox then gives up, and the loop stops.""" if unshown := publish(paths.waiting, ask): say(f"loop-inbox cannot show this question: {unshown.reason}", effects) def withdrawn(paths: Paths, ask: Ask, effects: Effects) -> None: """Takes ask out of loop-inbox. A failure only warns: loop-inbox drops the ask once the loop's process ends.""" if unwithdrawn := withdraw(paths.waiting, ask.session): say(f"loop-inbox may still list this question: {unwithdrawn.reason}", effects) def talk(chosen: Talk, session: WorkerSession, paths: Paths, effects: Effects) -> Stop | None: """Holds the loop while the human answers in the worker's claude session, which loop-inbox lists as open on loop-claude's terminal or in loop-inbox. A Stop where they type nothing there.""" try: return human_typed(session.transcript_path, lambda: opened(chosen, session, paths, effects)) finally: withdrawn(paths, chosen.ask, effects) def opened(chosen: Talk, session: WorkerSession, paths: Paths, effects: Effects) -> Stop | None: """Returns once the claude the human answers in has ended: the one it opens on the terminal, or the one loop-inbox opened.""" # Tells loop-inbox where claude is open; for OpenInInbox, it is the go-ahead claim_talk waits for. shown(paths, dataclasses.replace(chosen.ask, state=chosen.where), effects) match chosen.where: case OpenOnTerminal(): if unstarted := hand_over(session.claude_command(), paths, effects): return Stop(1, f"could not start claude for the interrupt: {unstarted.reason}") case OpenInInbox(pid): say("claude is open for this question in loop-inbox; waiting for it to end", effects) while not claude_ended(paths.waiting, chosen.ask) and effects.alive(pid): effects.sleep(POLL_SECONDS) case _: typing.assert_never(chosen.where) return None def human_typed(transcript_path: str, held_open: typing.Callable[[], Stop | None]) -> Stop | None: """Runs held_open, which returns once the claude the human answers in has ended, then checks that the human typed something there.""" entries = read_transcript(transcript_path) if isinstance(entries, Failure): return Stop(1, entries.reason) before = human_turns(entries) if stop := held_open(): return stop entries = read_transcript(transcript_path) if isinstance(entries, Failure): return Stop(1, f"could not tell whether you typed anything: {entries.reason}") return None if human_turns(entries) > before else needs_human(ANSWER_QUESTION, "the interrupt ended with nothing typed") def hand_over(command: ClaudeCommand, paths: Paths, effects: Effects) -> Failure | None: """Marks trusted the checkout that command runs in, and each of its worktrees, then runs claude on the terminal as command says; the failure is why claude could not start.""" trust(paths.claude_json, worktrees(command.cwd, effects), lambda text: say(text, effects)) try: effects.claude_on_terminal(command.args, command.cwd, command.env) except OSError as failure: return Failure(str(failure.strerror)) return None def claude_args(rung: Rung, args: list[str]) -> list[str]: return [*rung.flags(), "--permission-mode", "bypassPermissions", *args]