Answer architecture round 1: 1 🔴, 6 🟡 (0 misread); open claude through one hand_over, route loop-inbox's /talk through the Talking state, give Ask one state
This commit is contained in:
@@ -1,16 +1,16 @@
|
||||
import dataclasses
|
||||
import os
|
||||
import sys
|
||||
import typing
|
||||
import uuid
|
||||
|
||||
from loop_claude.waiting import alive, answered, Ask, publish, TalkCommand, Talked, Talking, Typed, withdraw
|
||||
from loop_claude.waiting import answered, Ask, Asking, claude_ended, ClaudeCommand, ClaudeOpening, OpenInInbox, OpenOnTerminal, POLL_SECONDS, publish, 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
|
||||
|
||||
@@ -18,13 +18,6 @@ ANSWER_QUESTION = "answer the question above"
|
||||
# TALK and ASK_ANSWER were 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.
|
||||
TALK = "/talk"
|
||||
ASK_ANSWER = f"Answer ({TALK} opens claude, Enter stops the loop): "
|
||||
# Seconds between looks at whether the claude loop-inbox opened has ended.
|
||||
TALK_POLL = 0.5
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Talk:
|
||||
"""The human answers in the worker's claude session, which talk opens on loop-claude's terminal."""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -37,50 +30,50 @@ class WorkerSession:
|
||||
# What the worker's claude adds to its environment, as the claude /talk opens does.
|
||||
env: dict[str, str]
|
||||
|
||||
def talk_command(self) -> TalkCommand:
|
||||
return TalkCommand(claude_args(self.rung, ["--resume", str(self.id)]), self.root, self.env)
|
||||
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 | Talked | Stop:
|
||||
"""Prints question for the human. Where answer_here, shows it in loop-inbox too and returns the first answer: the line they type at loop-claude's terminal, stripped, or Talk where they type TALK; a line typed in loop-inbox; or Talked once the claude loop-inbox opened ends with something typed. Else Talk at once. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends."""
|
||||
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 = Ask(str(uuid.uuid4()), str(session.id), session.root, question, effects.now(), os.getpid(), session.talk_command())
|
||||
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):
|
||||
withdraw(paths.waiting, ask.session)
|
||||
|
||||
|
||||
def first_answer(ask: Ask, paths: Paths, effects: Effects) -> str | Talk | Stop:
|
||||
try:
|
||||
answer = effects.input_or(ASK_ANSWER, lambda: answered(paths.waiting, ask))
|
||||
if isinstance(answer, Talking | Talked):
|
||||
return talked_in_inbox(ask, answer, session.transcript_path, paths, effects)
|
||||
if isinstance(answer, Typed):
|
||||
say(f"Answered in loop-inbox: {answer.text}", effects)
|
||||
answer = answer.text
|
||||
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")
|
||||
finally:
|
||||
withdraw(paths.waiting, ask.session)
|
||||
answer = answer.strip()
|
||||
if not answer:
|
||||
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() if answer == TALK else answer
|
||||
|
||||
|
||||
def talked_in_inbox(ask: Ask, answer: Talking | Talked, transcript_path: str, paths: Paths, effects: Effects) -> Talked | Stop:
|
||||
"""Waits, off the terminal, while the claude that loop-inbox opened on the worker's session runs; the human must type something there."""
|
||||
def waited() -> None:
|
||||
if isinstance(answer, Talked):
|
||||
return
|
||||
# Shows loop-inbox that the loop stopped reading its terminal, so loop-inbox may open claude.
|
||||
shown(paths, dataclasses.replace(ask, talk=None, talking=answer.pid), effects)
|
||||
say("claude is open for this question in loop-inbox; waiting for it to end", effects)
|
||||
while not isinstance(answered(paths.waiting, ask), Talked) and alive(answer.pid):
|
||||
effects.sleep(TALK_POLL)
|
||||
return human_typed(transcript_path, waited) or Talked()
|
||||
return Talk(ask, OpenOnTerminal()) if text == TALK else text
|
||||
|
||||
|
||||
def shown(paths: Paths, ask: Ask, effects: Effects) -> None:
|
||||
@@ -89,19 +82,28 @@ def shown(paths: Paths, ask: Ask, effects: Effects) -> None:
|
||||
say(f"loop-inbox cannot show this question: {unshown.reason}", effects)
|
||||
|
||||
|
||||
def talk(question: str, session: WorkerSession, paths: Paths, effects: Effects) -> Stop | None:
|
||||
"""Resumes the worker's session in claude on the terminal, listed in loop-inbox while it runs; the human must type something there."""
|
||||
ask = Ask(str(uuid.uuid4()), str(session.id), session.root, question, effects.now(), os.getpid(), talk=None)
|
||||
shown(paths, ask, 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, listed in loop-inbox as open where it is; the human must type something there."""
|
||||
try:
|
||||
return human_typed(session.transcript_path, lambda: opened(session, paths, effects))
|
||||
return human_typed(session.transcript_path, lambda: opened(chosen, session, paths, effects))
|
||||
finally:
|
||||
withdraw(paths.waiting, ask.session)
|
||||
withdraw(paths.waiting, chosen.ask.session)
|
||||
|
||||
|
||||
def opened(session: WorkerSession, paths: Paths, effects: Effects) -> Stop | None:
|
||||
if unstarted := hand_over(session.rung, ["--resume", str(session.id)], session.root, paths, session.env, effects):
|
||||
return Stop(1, f"could not start claude for the interrupt: {unstarted.reason}")
|
||||
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."""
|
||||
# For loop-inbox, this shows that the loop has stopped reading its terminal, so it may open claude.
|
||||
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
|
||||
|
||||
|
||||
@@ -119,11 +121,11 @@ def human_typed(transcript_path: str, held_open: typing.Callable[[], Stop | None
|
||||
return None if human_turns(entries) > before else needs_human(ANSWER_QUESTION, "the interrupt ended with nothing typed")
|
||||
|
||||
|
||||
def hand_over(rung: Rung, args: list[str], root: str, paths: Paths, env: dict[str, str], effects: Effects) -> Failure | None:
|
||||
"""Marks the checkout and each of its worktrees trusted, then runs claude on the terminal in root, on rung, with env added to its environment; the failure is why claude could not start."""
|
||||
trust(paths.claude_json, worktrees(root, effects), lambda text: say(text, effects))
|
||||
def hand_over(command: ClaudeCommand, paths: Paths, effects: Effects) -> Failure | None:
|
||||
"""Marks the checkout command runs in, and each of its worktrees, trusted, 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(claude_args(rung, args), root, env)
|
||||
effects.claude_on_terminal(command.args, command.cwd, command.env)
|
||||
except OSError as failure:
|
||||
return Failure(str(failure.strerror))
|
||||
return None
|
||||
|
||||
@@ -2,7 +2,7 @@ import dataclasses
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanTalked, HumanTyped, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, TalkChosen, Talking, transition, TypedAnswer, WorkerRan, Working
|
||||
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanTalked, HumanTyped, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, Talk, TalkChosen, Talking, transition, TypedAnswer, WorkerRan, Working
|
||||
from loop_claude.routing import after_ruling, judge_rung
|
||||
from transcript_archive.write import archive
|
||||
from loop_claude.cycle.worker import AUTO_COMPACT_WINDOW, COMPACT_WINDOW, run_worker, worker_args
|
||||
@@ -14,7 +14,7 @@ from loop_claude.cycle.judge import judge, Rejected
|
||||
from transcript_archive import outcomes
|
||||
from loop_claude.paths import Paths
|
||||
from loop_claude.cycle import prompts
|
||||
from loop_claude.cycle.interrupt import put_question, talk, Talk, Talked, WorkerSession
|
||||
from loop_claude.cycle.interrupt import put_question, talk, WorkerSession
|
||||
from claude_code.transcript import read_transcript
|
||||
from loop_claude.cycle.retry import retried
|
||||
from model_routing.route import Route
|
||||
@@ -99,8 +99,8 @@ def step(cycle: Cycle, state: Active) -> Event | Stop:
|
||||
return rule(cycle, transcript_path)
|
||||
case Interrupting(transcript_path, ruling, _, step_up):
|
||||
return ask(cycle, transcript_path, ruling, step_up)
|
||||
case Talking(transcript_path, question, _):
|
||||
return talk(question, worker_session(cycle, transcript_path), cycle.paths, cycle.effects) or HumanTalked()
|
||||
case Talking(transcript_path, chosen, _):
|
||||
return talk(chosen, worker_session(cycle, transcript_path), cycle.paths, cycle.effects) or HumanTalked()
|
||||
case Closing(transcript_path, verdict):
|
||||
return close(cycle, transcript_path, verdict)
|
||||
case _:
|
||||
@@ -164,7 +164,7 @@ def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> St
|
||||
return None
|
||||
|
||||
|
||||
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, step_up: StepUp | None) -> HumanTyped | TalkChosen | HumanTalked | Stop:
|
||||
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, step_up: StepUp | None) -> HumanTyped | TalkChosen | Stop:
|
||||
question = question_for(ruling)
|
||||
# Archived now, so the transcript the question was asked on is kept with it; the human's answer then grows the transcript.
|
||||
# The interrupt names the rung the worker ran on before it; a step-up archived after it names the stepped rung, so the figures charge each stretch to its own rung.
|
||||
@@ -177,9 +177,7 @@ def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, st
|
||||
case Stop():
|
||||
return answer
|
||||
case Talk():
|
||||
return TalkChosen(question)
|
||||
case Talked():
|
||||
return HumanTalked()
|
||||
return TalkChosen(answer)
|
||||
# The worker gets the question it asked, not the one put to the human past the cap.
|
||||
return HumanTyped(TypedAnswer(ruling.question, answer))
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import dataclasses
|
||||
|
||||
from loop_claude.waiting import Ask, OpenInInbox, OpenOnTerminal
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
|
||||
from loop_claude.escalation_mark import StepUp
|
||||
|
||||
@@ -40,11 +41,17 @@ class Interrupting:
|
||||
step_up: StepUp | None = None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Talk:
|
||||
"""The human answers in the worker's claude session, open on loop-claude's terminal or in loop-inbox, as where says. ask is the question they were asked, which loop-inbox lists as open there."""
|
||||
ask: Ask
|
||||
where: OpenOnTerminal | OpenInInbox
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Talking:
|
||||
"""The human answers in the worker's claude session, on the terminal; question is what they were asked."""
|
||||
transcript_path: str
|
||||
question: str
|
||||
talk: Talk
|
||||
quoted_answers: int = 0
|
||||
|
||||
|
||||
@@ -82,13 +89,13 @@ class HumanTyped:
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class TalkChosen:
|
||||
"""The human typed /talk at loop-claude's terminal, or the interrupt is for a release ready to cut."""
|
||||
question: str
|
||||
"""The human typed /talk, at loop-claude's terminal or in loop-inbox, or the interrupt is for a release ready to cut."""
|
||||
talk: Talk
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class HumanTalked:
|
||||
"""The human typed in the worker's claude session, opened on loop-claude's terminal or in loop-inbox."""
|
||||
"""The human typed in the worker's claude session."""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -113,10 +120,10 @@ def transition(state: State, event: Event) -> State:
|
||||
return Closing(transcript_path, verdict)
|
||||
case Interrupting(_, _, quoted_answers, step_up), HumanTyped(typed):
|
||||
return Working(typed, quoted_answers, step_up)
|
||||
case Interrupting(transcript_path, _, quoted_answers), TalkChosen(question):
|
||||
return Talking(transcript_path, question, quoted_answers)
|
||||
case Interrupting(transcript_path, _, quoted_answers), TalkChosen(talk):
|
||||
return Talking(transcript_path, talk, quoted_answers)
|
||||
# The human worked in the worker's claude session, so the judge rules again on the transcript it leaves.
|
||||
case Talking(transcript_path, _, quoted_answers) | Interrupting(transcript_path, _, quoted_answers), HumanTalked():
|
||||
case Talking(transcript_path, _, quoted_answers), HumanTalked():
|
||||
return Judging(transcript_path, quoted_answers)
|
||||
case Closing(_, verdict), Archived():
|
||||
return Ended(verdict)
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
import dataclasses
|
||||
import os
|
||||
import select
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import termios
|
||||
import time
|
||||
import typing
|
||||
import uuid
|
||||
|
||||
from loop_claude.waiting import Answer, POLL_SECONDS
|
||||
import git_repo
|
||||
from machine_load.memory import Memory, read_memory
|
||||
|
||||
# Seconds between calls input_or makes while nothing is typed.
|
||||
POLL_SECONDS = 0.5
|
||||
# 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
|
||||
|
||||
@@ -26,6 +27,8 @@ class Streaming(typing.Protocol):
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Effects:
|
||||
# Whether the process with this pid still runs.
|
||||
alive: typing.Callable[[int], bool]
|
||||
claude: typing.Callable[[list[str], str, str], subprocess.CompletedProcess[str]]
|
||||
claude_on_terminal: typing.Callable[[list[str], str, dict[str, str]], int]
|
||||
# Drops what was typed on the terminal and not yet read.
|
||||
@@ -33,14 +36,18 @@ class Effects:
|
||||
execv: typing.Callable[[str, list[str]], None]
|
||||
git: git_repo.Git
|
||||
input: typing.Callable[[str], str]
|
||||
# Prints a prompt, then returns the line typed at the terminal, or the first value other than None that the callable returns, called every POLL_SECONDS. Raises EOFError where the input ends.
|
||||
input_or: typing.Callable[[str, typing.Callable[[], typing.Any]], typing.Any]
|
||||
# Prints a prompt, then returns the line typed at the terminal, or the first answer from loop-inbox that the callable returns, called every POLL_SECONDS. Raises EOFError where the input ends.
|
||||
input_or: typing.Callable[[str, typing.Callable[[], Answer | None]], str | Answer]
|
||||
# A date and time in the machine's zone, as `2026-10-28 11:46:01`. lilleman chose this spelling and local time over UTC on 2026-10-28, since the human reads these on their own clock.
|
||||
local_time: typing.Callable[[float], str]
|
||||
# The machine's memory; None where it cannot be read.
|
||||
memory: typing.Callable[[], Memory | None]
|
||||
# A new random id.
|
||||
new_id: typing.Callable[[], str]
|
||||
now: typing.Callable[[], float]
|
||||
on_terminal: typing.Callable[[], bool]
|
||||
# This process's pid.
|
||||
pid: typing.Callable[[], int]
|
||||
# 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]
|
||||
@@ -61,8 +68,9 @@ class StreamingClaude:
|
||||
|
||||
def system_effects() -> Effects:
|
||||
return Effects(
|
||||
alive=alive,
|
||||
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,
|
||||
claude_on_terminal=claude_on_terminal,
|
||||
discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH),
|
||||
execv=os.execv,
|
||||
git=git_repo.git,
|
||||
@@ -70,14 +78,36 @@ def system_effects() -> Effects:
|
||||
input_or=input_or,
|
||||
local_time=lambda seconds: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(seconds)),
|
||||
memory=read_memory,
|
||||
new_id=lambda: str(uuid.uuid4()),
|
||||
now=time.time,
|
||||
on_terminal=lambda: sys.stdin.isatty() and sys.stdout.isatty(),
|
||||
pid=os.getpid,
|
||||
python=lambda args, cwd: run_python(args, cwd, PYTHON_TIMEOUT),
|
||||
sleep=time.sleep,
|
||||
stream_claude=StreamingClaude,
|
||||
)
|
||||
|
||||
|
||||
def claude_on_terminal(args: list[str], cwd: str, env: dict[str, str]) -> int:
|
||||
"""Runs claude on the terminal in cwd, with env added to its environment, and returns its exit code. While claude runs, Ctrl-C belongs to it: this process shares its terminal, and ignores the key."""
|
||||
# A Python handler, unlike SIG_IGN, is reset to the default as claude starts, so Ctrl-C still reaches claude.
|
||||
previous = signal.signal(signal.SIGINT, lambda number, frame: None)
|
||||
try:
|
||||
return subprocess.run(["claude", *args], cwd=cwd, env={**os.environ, **env}).returncode
|
||||
finally:
|
||||
signal.signal(signal.SIGINT, previous)
|
||||
|
||||
|
||||
def alive(pid: int) -> bool:
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
except ProcessLookupError:
|
||||
return False
|
||||
except PermissionError:
|
||||
return True
|
||||
return True
|
||||
|
||||
|
||||
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]
|
||||
@@ -89,7 +119,7 @@ def run_python(args: list[str], cwd: str, timeout: float) -> subprocess.Complete
|
||||
return subprocess.CompletedProcess(command, 1, "", f"stopped after {timeout} s")
|
||||
|
||||
|
||||
def input_or[T](prompt: str, other: typing.Callable[[], T | None]) -> str | T:
|
||||
def input_or(prompt: str, other: typing.Callable[[], Answer | None]) -> str | Answer:
|
||||
# On stderr, where input prints its prompt on a terminal.
|
||||
print(prompt, end="", file=sys.stderr, flush=True)
|
||||
while True:
|
||||
|
||||
@@ -31,7 +31,7 @@ loop on the machine that waits for the human. The first answer counts, from eith
|
||||
- Enter alone, on loop-claude's terminal: stops the loop.
|
||||
A release ready to cut opens that session on the terminal at once, since only the human may cut it;
|
||||
loop-inbox lists it too. Before claude opens, the checkout and each of its worktrees are marked
|
||||
trusted in ~/.claude.json.
|
||||
trusted in ~/.claude.json. While claude is open, Ctrl-C reaches it alone, and the loop goes on.
|
||||
|
||||
As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight (bin/chunk_preflight/),
|
||||
which finds the chunk's facts and makes its worktree; chunk-preflight --help lists them, and
|
||||
|
||||
@@ -3,9 +3,10 @@ import pathlib
|
||||
|
||||
from routing_figures import archive
|
||||
from routing_figures.measure import calls, due, render, totals
|
||||
from loop_claude.cycle.interrupt import claude_args, hand_over
|
||||
from loop_claude.waiting import ClaudeCommand
|
||||
from loop_claude.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.cycle.interrupt import hand_over
|
||||
from loop_claude.paths import Paths
|
||||
from model_routing.ladder import Rung
|
||||
from loop_claude.stop import Stop
|
||||
@@ -50,7 +51,7 @@ def raise_calls(root: pathlib.Path, new: list[str], rung: Rung, paths: Paths, ef
|
||||
say("Not on a terminal: the calls are raised again at the next measurement.", effects)
|
||||
return None
|
||||
prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and change nothing until they answer:\n{listed}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls."
|
||||
if unstarted := hand_over(rung, [prompt], str(paths.claude_dir), paths, {}, effects):
|
||||
if unstarted := hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(paths.claude_dir), {}), paths, effects):
|
||||
return Stop(1, f"could not start claude for the routing calls: {unstarted.reason}")
|
||||
# Raised once the human has seen them, answered or not: an unanswered call reaches the plan through AGENTS.md, so it is not asked twice.
|
||||
if unmarked := archive.mark_raised(root, new, utc(effects.now())):
|
||||
|
||||
@@ -37,7 +37,7 @@ argv = sys.argv[1:]
|
||||
role = "judge" if "--json-schema" in argv else "worker" if "-p" in argv else "interrupt"
|
||||
scenario = pathlib.Path(os.environ["FAKE_CLAUDE_SCENARIO"])
|
||||
steps = json.loads(scenario.read_text())
|
||||
call = {{"argv": argv, "cwd": os.getcwd(), "role": role}}
|
||||
call = {{"argv": argv, "cwd": os.getcwd(), "role": role, "ctrl_c_ignored": signal.getsignal(signal.SIGINT) == signal.SIG_IGN}}
|
||||
if role == "judge":
|
||||
call["stdin"] = sys.stdin.read()
|
||||
with open(os.environ["FAKE_CLAUDE_LOG"], "a") as log:
|
||||
@@ -98,8 +98,13 @@ if role == "worker":
|
||||
elif role == "judge":
|
||||
print(step["stdout"] if "stdout" in step else json.dumps({{"structured_output": step["verdict"]}}))
|
||||
print(step.get("stderr", ""), file=sys.stderr)
|
||||
elif "type" in step:
|
||||
append({{"type": "user", "message": {{"content": step["type"]}}}})
|
||||
else:
|
||||
if step.get("ctrl_c"):
|
||||
# A Ctrl-C on the terminal reaches every process in its foreground, loop-claude too.
|
||||
os.kill(os.getppid(), signal.SIGINT)
|
||||
time.sleep(0.5)
|
||||
if "type" in step:
|
||||
append({{"type": "user", "message": {{"content": step["type"]}}}})
|
||||
if step.get("unreadable"):
|
||||
transcript().chmod(0)
|
||||
if step.get("vanish"):
|
||||
@@ -731,7 +736,7 @@ class Interrupt(unittest.TestCase):
|
||||
checkout = Checkout(self)
|
||||
folder = checkout.home / ".local" / "state" / "loop-claude"
|
||||
def answered_in_inbox():
|
||||
[ask] = waiting.waiting(folder)
|
||||
[ask] = waiting.waiting(folder, lambda pid: True)
|
||||
waiting.send(folder, ask, waiting.Typed("B"))
|
||||
asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]
|
||||
run = checkout.run([*asked, worker(say="Using B."), judge(evidence="Using B.")], terminal_input="", before_typing=("Answer (", answered_in_inbox))
|
||||
@@ -775,6 +780,14 @@ class Interrupt(unittest.TestCase):
|
||||
self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"]))
|
||||
self.assertTrue(run.stderr.strip().endswith("could not start claude for the interrupt: No such file or directory"))
|
||||
|
||||
def test_leaves_ctrl_c_to_the_claude_open_for_talk(self):
|
||||
checkout = Checkout(self)
|
||||
asked = [worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?")]
|
||||
run = checkout.run([*asked, interrupt(type="B", ctrl_c=True), judge(evidence="B")], terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge", "interrupt", "judge", "worker"]))
|
||||
self.assertFalse(run.calls[2]["ctrl_c_ignored"])
|
||||
self.assertIn("[human] B", run.calls[3]["stdin"])
|
||||
|
||||
def test_says_why_the_trust_file_cannot_be_read_and_leaves_it_as_it_was(self):
|
||||
checkout = Checkout(self)
|
||||
asked = [worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?"), interrupt()]
|
||||
|
||||
@@ -51,6 +51,8 @@ NOW = 1790000000
|
||||
STAMP = f"<{NOW}>"
|
||||
# How git answers in a project's checkout it cannot read, such as one that is gone.
|
||||
UNREAD = Failure("not a git repository")
|
||||
# The id FakeEffects gives each new ask, and its pid for loop-claude's process.
|
||||
ASK_ID, PID = "ask-1", 4242
|
||||
|
||||
|
||||
def assistant(*parts):
|
||||
@@ -64,8 +66,10 @@ def human(content):
|
||||
class FakeEffects:
|
||||
"""Effects that record each call and answer from a script, one answer per call."""
|
||||
|
||||
def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=()):
|
||||
def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=(), gone=()):
|
||||
self.calls = []
|
||||
# The pids of processes that no longer run.
|
||||
self.gone = set(gone)
|
||||
self.scripts = {"claude": list(claude), "claude_on_terminal": list(on_terminal_claude), "git": list(git), "input": list(inputs), "python": list(python), "stream_claude": list(streams)}
|
||||
# Without a script, every read finds all memory available.
|
||||
self.free_memory = list(free_memory)
|
||||
@@ -75,6 +79,7 @@ class FakeEffects:
|
||||
|
||||
def effects(self):
|
||||
return Effects(
|
||||
alive=lambda pid: pid not in self.gone,
|
||||
claude=lambda args, cwd, stdin: self.answer("claude", (args, stdin)),
|
||||
claude_on_terminal=self.on_terminal_claude,
|
||||
discard_typed=lambda: self.calls.append(("discard_typed", None)),
|
||||
@@ -84,8 +89,10 @@ class FakeEffects:
|
||||
input_or=self.input_or,
|
||||
local_time=lambda seconds: f"<{seconds}>",
|
||||
memory=self.memory,
|
||||
new_id=lambda: ASK_ID,
|
||||
now=lambda: NOW,
|
||||
on_terminal=lambda: self.terminal,
|
||||
pid=lambda: PID,
|
||||
python=lambda args, cwd: self.answer("python", (args, cwd)),
|
||||
sleep=lambda seconds: self.calls.append(("sleep", seconds)),
|
||||
stream_claude=self.stream,
|
||||
@@ -170,6 +177,8 @@ class Streamed:
|
||||
|
||||
|
||||
TYPED = states.TypedAnswer("Which one?", "Use B.")
|
||||
# The human chose to answer in the worker's claude session.
|
||||
TALKED = states.Talk(waiting.Ask("a1", "s1", "/c", "q", NOW, 7, waiting.OpenOnTerminal()), waiting.OpenOnTerminal())
|
||||
|
||||
|
||||
class Transitions(unittest.TestCase):
|
||||
@@ -187,13 +196,10 @@ class Transitions(unittest.TestCase):
|
||||
(states.Judging("/t", 3), states.Ruled(Finished("e")), states.Closing("/t", Finished("e"))),
|
||||
(states.Judging("/t"), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))),
|
||||
(states.Judging("/t", 3), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))),
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.TalkChosen("q"), states.Talking("/t", "q")),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.TalkChosen("q"), states.Talking("/t", "q", 3)),
|
||||
(states.Talking("/t", "q"), states.HumanTalked(), states.Judging("/t")),
|
||||
(states.Talking("/t", "q", 3), states.HumanTalked(), states.Judging("/t", 3)),
|
||||
# The human talked in the claude loop-inbox opened.
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.HumanTalked(), states.Judging("/t")),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanTalked(), states.Judging("/t", 3)),
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.TalkChosen(TALKED), states.Talking("/t", TALKED)),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.TalkChosen(TALKED), states.Talking("/t", TALKED, 3)),
|
||||
(states.Talking("/t", TALKED), states.HumanTalked(), states.Judging("/t")),
|
||||
(states.Talking("/t", TALKED, 3), states.HumanTalked(), states.Judging("/t", 3)),
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.HumanTyped(TYPED), states.Working(TYPED)),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanTyped(TYPED), states.Working(TYPED, 3)),
|
||||
(states.Working(TYPED, 3), states.WorkerRan("/t"), states.Judging("/t", 3)),
|
||||
@@ -203,8 +209,8 @@ class Transitions(unittest.TestCase):
|
||||
for state, event, after in legal:
|
||||
with self.subTest(state=state, event=event):
|
||||
self.assertEqual(states.transition(state, event), after)
|
||||
every_state = (states.Working(), states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.Working(TYPED, 3), states.Judging("/t"), states.Judging("/t", 3), states.Interrupting("/t", Interrupt("e", "q")), states.Interrupting("/t", Interrupt("e", "q"), 3), states.Talking("/t", "q"), states.Talking("/t", "q", 3), states.Closing("/t", Finished("e")), states.Ended(Finished("e")))
|
||||
every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), answered, states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.TalkChosen("q"), states.HumanTalked(), states.HumanTyped(TYPED), states.Archived())
|
||||
every_state = (states.Working(), states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.Working(TYPED, 3), states.Judging("/t"), states.Judging("/t", 3), states.Interrupting("/t", Interrupt("e", "q")), states.Interrupting("/t", Interrupt("e", "q"), 3), states.Talking("/t", TALKED), states.Talking("/t", TALKED, 3), states.Closing("/t", Finished("e")), states.Ended(Finished("e")))
|
||||
every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), answered, states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.TalkChosen(TALKED), states.HumanTalked(), states.HumanTyped(TYPED), states.Archived())
|
||||
for state in every_state:
|
||||
for event in every_event:
|
||||
if (state, event) not in [(state, event) for state, event, _ in legal]:
|
||||
@@ -219,7 +225,7 @@ class Transitions(unittest.TestCase):
|
||||
(states.Judging("/t", 3), states.Ruled(quoted, step_up), states.Interrupting("/t", quoted, 3, step_up)),
|
||||
(states.Judging("/t"), states.Ruled(interrupt, step_up), states.Interrupting("/t", interrupt, 0, step_up)),
|
||||
(states.Interrupting("/t", interrupt, 0, step_up), states.HumanTyped(TYPED), states.Working(TYPED, 0, step_up)),
|
||||
(states.Interrupting("/t", interrupt, 0, step_up), states.TalkChosen("q"), states.Talking("/t", "q")),
|
||||
(states.Interrupting("/t", interrupt, 0, step_up), states.TalkChosen(TALKED), states.Talking("/t", TALKED)),
|
||||
(states.Working(TYPED, 0, step_up), states.WorkerRan("/t"), states.Judging("/t")),
|
||||
):
|
||||
with self.subTest(state=state, event=event):
|
||||
@@ -664,7 +670,12 @@ class Interrupts(unittest.TestCase):
|
||||
return put, said.getvalue()
|
||||
|
||||
def asked(self):
|
||||
return waiting.waiting(self.paths.waiting)
|
||||
return waiting.waiting(self.paths.waiting, lambda pid: True)
|
||||
|
||||
def ask(self, question="Which one?", state=None):
|
||||
"""The ask put_question makes for question, in state; by default it waits for an answer, and /talk resumes the worker's session."""
|
||||
resumed = waiting.ClaudeCommand(["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions", "--resume", str(self.session.id)], str(self.home), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"})
|
||||
return waiting.Ask(ASK_ID, str(self.session.id), str(self.home), question, NOW, PID, state or waiting.Asking(resumed))
|
||||
|
||||
def test_stops_off_a_terminal_before_asking(self):
|
||||
fake = FakeEffects(on_terminal=False)
|
||||
@@ -680,7 +691,7 @@ class Interrupts(unittest.TestCase):
|
||||
for typed, answer_here in (([" /talk "], True), ([], False)):
|
||||
with self.subTest(typed=typed):
|
||||
fake = FakeEffects(inputs=typed)
|
||||
self.assertEqual(self.put(fake, answer_here)[0], interrupt.Talk())
|
||||
self.assertEqual(self.put(fake, answer_here)[0], states.Talk(self.ask(), waiting.OpenOnTerminal()))
|
||||
self.assertEqual(len(fake.made("input")), len(typed))
|
||||
self.assertEqual(fake.calls[0], ("discard_typed", None))
|
||||
|
||||
@@ -692,9 +703,7 @@ class Interrupts(unittest.TestCase):
|
||||
|
||||
def test_shows_the_question_in_loop_inbox_while_it_waits_and_only_then(self):
|
||||
def typed(_):
|
||||
[ask] = self.asked()
|
||||
self.assertEqual((ask.session, ask.root, ask.question, ask.asked, ask.pid, ask.talking), (str(self.session.id), str(self.home), "Which one?", NOW, os.getpid(), None))
|
||||
self.assertEqual(ask.talk, waiting.TalkCommand(["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions", "--resume", str(self.session.id)], str(self.home), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"}))
|
||||
self.assertEqual(self.asked(), [self.ask()])
|
||||
return "Use B."
|
||||
self.assertEqual(self.put(FakeEffects(inputs=[typed]))[0], "Use B.")
|
||||
self.assertEqual(list(self.paths.waiting.iterdir()), [])
|
||||
@@ -711,56 +720,57 @@ class Interrupts(unittest.TestCase):
|
||||
self.assertEqual(self.put(fake, effects=effects), ("Use C.", f"\n{STAMP} Which one?\n{STAMP} Answered in loop-inbox: Use C. \n"))
|
||||
self.assertEqual(list(self.paths.waiting.iterdir()), [])
|
||||
|
||||
def test_waits_off_the_terminal_while_loop_inbox_has_claude_open_and_goes_on_once_the_human_typed_there(self):
|
||||
inbox = os.getpid()
|
||||
def talking(other):
|
||||
def talk(self, chosen, effects):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
stop = interrupt.talk(chosen, self.session, self.paths, effects)
|
||||
return stop, said.getvalue()
|
||||
|
||||
def test_makes_way_for_the_claude_loop_inbox_opens_and_goes_on_once_the_human_typed_there(self):
|
||||
inbox = 4343
|
||||
def opening(other):
|
||||
[ask] = self.asked()
|
||||
waiting.send(self.paths.waiting, ask, waiting.Talking(inbox))
|
||||
waiting.send(self.paths.waiting, ask, waiting.ClaudeOpening(inbox))
|
||||
return other()
|
||||
fake = FakeEffects(inputs=[opening])
|
||||
self.assertEqual(self.put(fake), (states.Talk(self.ask(), waiting.OpenInInbox(inbox)), f"\n{STAMP} Which one?\n"))
|
||||
def claude_ran(_):
|
||||
[ask] = self.asked()
|
||||
self.assertEqual((ask.talk, ask.talking), (None, inbox))
|
||||
# loop-inbox opens claude only once the loop lists it as open there.
|
||||
self.assertEqual(self.asked(), [self.ask(state=waiting.OpenInInbox(inbox))])
|
||||
with open(self.transcript, "a") as handle:
|
||||
handle.write(json.dumps(human("cut it")) + "\n")
|
||||
waiting.send(self.paths.waiting, ask, waiting.Talked())
|
||||
fake = FakeEffects(inputs=[talking])
|
||||
self.assertEqual(self.put(fake, effects=dataclasses.replace(fake.effects(), sleep=claude_ran)), (interrupt.Talked(), f"\n{STAMP} Which one?\n{STAMP} claude is open for this question in loop-inbox; waiting for it to end\n"))
|
||||
self.assertEqual(list(self.paths.waiting.iterdir()), [])
|
||||
waiting.send(self.paths.waiting, self.ask(), waiting.ClaudeEnded())
|
||||
effects = dataclasses.replace(fake.effects(), sleep=claude_ran)
|
||||
self.assertEqual(self.talk(states.Talk(self.ask(), waiting.OpenInInbox(inbox)), effects), (None, f"{STAMP} claude is open for this question in loop-inbox; waiting for it to end\n"))
|
||||
self.assertEqual((fake.made("claude_on_terminal"), list(self.paths.waiting.iterdir())), ([], []))
|
||||
|
||||
def test_stops_when_loop_inbox_ends_its_claude_or_is_gone_with_nothing_typed(self):
|
||||
gone = subprocess.run([sys.executable, "-c", "import os; print(os.getpid())"], capture_output=True, text=True).stdout.strip()
|
||||
for pid, ended in ((os.getpid(), True), (int(gone), False)):
|
||||
with self.subTest(ended=ended):
|
||||
def talking(other):
|
||||
[ask] = self.asked()
|
||||
waiting.send(self.paths.waiting, ask, waiting.Talking(pid))
|
||||
if ended:
|
||||
waiting.send(self.paths.waiting, ask, waiting.Talked())
|
||||
return other()
|
||||
self.assertEqual(self.put(FakeEffects(inputs=[talking]))[0], Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
inbox = 4343
|
||||
def ended(_):
|
||||
waiting.send(self.paths.waiting, self.ask(), waiting.ClaudeEnded())
|
||||
# loop-inbox's claude ends while the loop waits, or loop-inbox is gone before the loop looks.
|
||||
for gone in ((), (inbox,)):
|
||||
with self.subTest(gone=gone):
|
||||
stop, _ = self.talk(states.Talk(self.ask(), waiting.OpenInInbox(inbox)), dataclasses.replace(FakeEffects(gone=gone).effects(), sleep=ended))
|
||||
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
|
||||
def test_lists_the_claude_open_on_its_terminal_in_loop_inbox_while_it_runs(self):
|
||||
def ran(args):
|
||||
[ask] = self.asked()
|
||||
self.assertEqual((ask.question, ask.talk, ask.talking), ("Cut 0.4.0?", None, None))
|
||||
self.assertEqual(self.asked(), [self.ask("Cut 0.4.0?", waiting.OpenOnTerminal())])
|
||||
return 0
|
||||
fake = FakeEffects(on_terminal_claude=[ran], git=[""])
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
interrupt.talk("Cut 0.4.0?", self.session, self.paths, fake.effects())
|
||||
self.talk(states.Talk(self.ask("Cut 0.4.0?"), waiting.OpenOnTerminal()), fake.effects())
|
||||
self.assertEqual(len(fake.made("claude_on_terminal")), 1)
|
||||
self.assertEqual(list(self.paths.waiting.iterdir()), [])
|
||||
|
||||
def test_stops_when_nothing_was_typed_in_the_session(self):
|
||||
fake = FakeEffects(on_terminal_claude=[0], git=[""])
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
stop = interrupt.talk("Which one?", self.session, self.paths, fake.effects())
|
||||
stop, _ = self.talk(states.Talk(self.ask(), waiting.OpenOnTerminal()), fake.effects())
|
||||
self.assertEqual(fake.made("claude_on_terminal")[0][:4], ["--model", "m", "--effort", "high"])
|
||||
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
|
||||
def test_hands_the_claude_that_takes_the_terminal_the_workers_environment(self):
|
||||
fake = FakeEffects(on_terminal_claude=[0], git=[""])
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
interrupt.talk("Which one?", self.session, self.paths, fake.effects())
|
||||
self.talk(states.Talk(self.ask(), waiting.OpenOnTerminal()), fake.effects())
|
||||
self.assertEqual(fake.terminal_environments, [{"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"}])
|
||||
|
||||
|
||||
|
||||
+95
-33
@@ -1,33 +1,62 @@
|
||||
"""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, <session id>.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 <session id>.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 writes Talking, with its pid.
|
||||
2. The loop stops reading its terminal and republishes its ask with talking set to that pid; loop-inbox opens claude only once it reads that.
|
||||
3. loop-inbox writes Talked once claude exits. The loop also stops waiting if loop-inbox's process is gone.
|
||||
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 os
|
||||
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
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class TalkCommand:
|
||||
"""How loop-inbox runs claude on the worker's session: claude's arguments, its folder and what it adds to the environment."""
|
||||
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.
|
||||
@@ -36,10 +65,7 @@ class Ask:
|
||||
# When the loop asked, in seconds since the epoch.
|
||||
asked: float
|
||||
pid: int
|
||||
# How loop-inbox opens claude for /talk; None while claude is open for this question, which then takes no answer from loop-inbox.
|
||||
talk: TalkCommand | None
|
||||
# The pid of the loop-inbox that has claude open for this question; None while claude is open on the loop's own terminal, or not open.
|
||||
talking: int | None = None
|
||||
state: AskState
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -48,16 +74,19 @@ class Typed:
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Talking:
|
||||
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 Talked:
|
||||
pass
|
||||
class ClaudeEnded:
|
||||
"""The claude loop-inbox opened for the ask has ended."""
|
||||
|
||||
|
||||
Answer = Typed | Talking | Talked
|
||||
# What answers a waiting ask.
|
||||
Answer = Typed | ClaudeOpening
|
||||
Message = Answer | ClaudeEnded
|
||||
|
||||
|
||||
def ask_file(folder: pathlib.Path, session: str) -> pathlib.Path:
|
||||
@@ -73,7 +102,7 @@ def publish(folder: pathlib.Path, ask: Ask) -> Failure | None:
|
||||
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))
|
||||
return replace_json(ask_file(folder, ask.session), dataclasses.asdict(ask) | {"state": tagged(ask.state)})
|
||||
|
||||
|
||||
def withdraw(folder: pathlib.Path, session: str) -> None:
|
||||
@@ -82,7 +111,7 @@ def withdraw(folder: pathlib.Path, session: str) -> None:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def waiting(folder: pathlib.Path) -> list[Ask]:
|
||||
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"))
|
||||
@@ -95,21 +124,45 @@ def waiting(folder: pathlib.Path) -> list[Ask]:
|
||||
def read_ask(path: pathlib.Path) -> Ask | None:
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
talk = data["talk"] and TalkCommand(**data["talk"])
|
||||
ask = Ask(**{**data, "talk": talk})
|
||||
ask = Ask(**{**data, "state": ask_state(data["state"])})
|
||||
except (OSError, ValueError, TypeError, KeyError):
|
||||
return None
|
||||
# A pid of 0 or below would name a process group to alive.
|
||||
return ask if isinstance(ask.asked, int | float) and isinstance(ask.pid, int) and ask.pid > 0 else None
|
||||
|
||||
|
||||
def send(folder: pathlib.Path, ask: Ask, answer: Answer) -> Failure | None:
|
||||
kind = dataclasses.asdict(answer) | {"kind": type(answer).__name__}
|
||||
return replace_json(answer_file(folder, ask.session), {"ask": ask.id, **kind})
|
||||
def ask_state(data: object) -> AskState:
|
||||
match data:
|
||||
case {"kind": "Asking", "talk": {"args": list(args), "cwd": str(cwd), "env": dict(env)}}:
|
||||
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):
|
||||
@@ -119,18 +172,27 @@ def answered(folder: pathlib.Path, ask: Ask) -> Answer | None:
|
||||
match data:
|
||||
case {"kind": "Typed", "text": str(text)}:
|
||||
return Typed(text)
|
||||
case {"kind": "Talking", "pid": int(pid)}:
|
||||
return Talking(pid)
|
||||
case {"kind": "Talked"}:
|
||||
return Talked()
|
||||
case {"kind": "ClaudeOpening", "pid": int(pid)}:
|
||||
return ClaudeOpening(pid)
|
||||
case {"kind": "ClaudeEnded"}:
|
||||
return ClaudeEnded()
|
||||
return None
|
||||
|
||||
|
||||
def alive(pid: int) -> bool:
|
||||
try:
|
||||
os.kill(pid, 0)
|
||||
except ProcessLookupError:
|
||||
return False
|
||||
except PermissionError:
|
||||
return True
|
||||
return True
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user