Files
claude-config/bin/loop_claude/cycle/interrupt.py
T

114 lines
5.8 KiB
Python

import dataclasses
import pathlib
import sys
import typing
import uuid
from loop_state.waiting.answers import Answer, answered, claude_ended, ClaudeOpening, Typed
from loop_state.waiting.ask import Ask, Asking, OpenInInbox, OpenOnTerminal
from loop_state.hand_over import claude_args, ClaudeCommand, hand_over
from loop_effects.effects import Effects, POLL_SECONDS, say
from failure import Failure
from claude_code.transcript import human_turns, read_transcript
from loop_state.waiting.listing import listed, shown
from loop_state.waiting.talk import make_way, TALK
from loop_claude.stop import needs_human, needs_terminal, Stop
from model_routing.ladder import Rung
from loop_claude.direct_message import tell
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)
@dataclasses.dataclass(frozen=True)
class Talked:
"""The human typed in the worker's claude session."""
def interrupt(question: str, answer_here: bool, session: WorkerSession, questions: pathlib.Path, effects: Effects) -> str | Talked | Stop:
"""Prints question for the human and returns their answer: where answer_here, the first line typed at loop-claude's terminal or in loop-inbox, stripped, or Talked once they typed in the worker's claude session, which TALK opens; else Talked once they typed in that session, which opens at once on the terminal. loop-inbox lists the question meanwhile. A Stop where loop-claude is off a terminal, or they type no answer, or the input ends."""
say(f"\n{question}", effects)
on_terminal = effects.on_terminal()
if on_terminal:
# 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()
# After the discard, so an answer typed while the DM sends counts; before the terminal check, so a loop that cannot ask still tells the human what it would have asked.
tell(f"loop-claude in {session.root} asks:\n\n{question}", effects)
if stop := needs_terminal(ANSWER_QUESTION, on_terminal):
return stop
ask = Ask(effects.new_id(), str(session.id), session.root, question, effects.now(), Asking(session.claude_command()) if answer_here else OpenOnTerminal())
with listed(questions, ask, effects):
answer = first_answer(ask, questions, effects) if answer_here else OpenOnTerminal()
if isinstance(answer, OpenOnTerminal | OpenInInbox):
return human_typed(session.transcript_path, lambda: claude_open(ask, answer, session, questions, effects)) or Talked()
return answer
def first_answer(ask: Ask, questions: pathlib.Path, effects: Effects) -> str | OpenOnTerminal | OpenInInbox | Stop:
"""The first answer to ask, from loop-claude's terminal or loop-inbox: the line typed, stripped, or where claude is to open for it. A Stop where they type no answer, or the input ends."""
try:
# Annotated since mypy infers input_or's T as object from the lambda.
answer: str | Answer = effects.input_or(ASK_ANSWER, lambda: answered(questions, 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 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 OpenOnTerminal() if text == TALK else text
def claude_open(ask: Ask, where: OpenOnTerminal | OpenInInbox, session: WorkerSession, questions: pathlib.Path, effects: Effects) -> Stop | None:
"""Lists ask in loop-inbox as having claude open where, then returns once that claude has ended: the one it opens on the terminal, or the one loop-inbox opened."""
match where:
case OpenOnTerminal():
shown(questions, dataclasses.replace(ask, state=where), effects)
if unstarted := hand_over(session.claude_command(), effects):
return Stop(1, f"could not start claude for the interrupt: {unstarted.reason}")
case OpenInInbox(pid):
make_way(questions, ask, pid, effects)
say("claude is open for this question in loop-inbox; waiting for it to end", effects)
while not claude_ended(questions, ask) and effects.alive(pid):
effects.sleep(POLL_SECONDS)
case _:
typing.assert_never(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 without anything typed")