242 lines
9.7 KiB
Python
242 lines
9.7 KiB
Python
"""The files by which a loop-claude shows its interrupt in loop-inbox, and takes an answer typed there.
|
|
|
|
A waiting loop keeps its ask in <session>.json in Paths.waiting: the question, with an id new for each question.
|
|
<session> is the worker's session id, so a loop lists one question at a time. The loop holds the session's lock, as
|
|
session_lock.py describes, while it lists the ask, and removes the ask once the question is answered or the loop stops.
|
|
loop-inbox lists an ask only while its lock is held, and removes one whose lock is free. The ask's state says whether
|
|
the loop 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>.answer, which names the ask's 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 its make_way lists the 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 contextlib
|
|
import dataclasses
|
|
import json
|
|
import pathlib
|
|
import typing
|
|
|
|
from loop_claude.hand_over import ClaudeCommand
|
|
from loop_claude.effects import Effects, POLL_SECONDS, say
|
|
from failure import Failure
|
|
from loop_claude.session_lock import locked, running
|
|
from file_writes import make_private, replace_json
|
|
|
|
# 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; picked on 2026-10-17 by a bench of three readers seated as the README's audience.
|
|
TALK = "/talk"
|
|
|
|
|
|
@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; the loop 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
|
|
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 shown(folder: pathlib.Path, ask: Ask, effects: Effects) -> None:
|
|
"""Lists ask in loop-inbox, in its state. A failure only warns: the question is still answered on the loop's terminal."""
|
|
if unshown := publish(folder, ask):
|
|
say(f"loop-inbox cannot show this question: {unshown.reason}", effects)
|
|
|
|
|
|
@contextlib.contextmanager
|
|
def listed(folder: pathlib.Path, ask: Ask, effects: Effects) -> typing.Iterator[None]:
|
|
"""Lists ask in loop-inbox while the with block runs, then takes it out, with any answer. A failure only warns: the question is still answered on the loop's terminal, and loop-inbox drops the ask once the loop's process ends."""
|
|
with locked(folder, ask.session) as unlocked:
|
|
if unlocked:
|
|
say(f"loop-inbox cannot show this question: {unlocked.reason}", effects)
|
|
yield
|
|
return
|
|
shown(folder, ask, effects)
|
|
try:
|
|
yield
|
|
finally:
|
|
if unwithdrawn := withdraw(folder, ask.session):
|
|
say(f"loop-inbox may still list this question: {unwithdrawn.reason}", effects)
|
|
|
|
|
|
def waiting(folder: pathlib.Path) -> list[Ask]:
|
|
"""The asks of loops still running, oldest first. A file that cannot be read or parsed is left out."""
|
|
try:
|
|
paths = sorted(folder.glob("*.json"))
|
|
except OSError:
|
|
return []
|
|
asks = [ask for path in paths if (ask := read_ask(path)) and running(folder, ask.session)]
|
|
return sorted(asks, key=lambda ask: ask.asked)
|
|
|
|
|
|
def drop_ended(folder: pathlib.Path) -> None:
|
|
"""Removes each ask, with any answer, whose session's lock no loop holds: a loop that was killed leaves its ask behind. It removes one while holding the lock, so a loop that lists a new ask meanwhile keeps it. An ask it cannot remove stays on disk, and waiting leaves it out all the same."""
|
|
try:
|
|
paths = list(folder.glob("*.json"))
|
|
except OSError:
|
|
return
|
|
for path in paths:
|
|
with locked(folder, path.stem) as unlocked:
|
|
if not unlocked:
|
|
withdraw(folder, path.stem)
|
|
|
|
|
|
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))
|
|
return ask if texts and ask.session == path.stem and isinstance(ask.asked, int | float) 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)
|
|
# A pid of 0 or below would name a process group to the loop's alive.
|
|
case {"kind": "ClaudeOpening", "pid": int(pid)} if pid > 0:
|
|
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, where pid is loop-inbox's process: asks the loop to make way for the claude loop-inbox opens for ask. True once the loop shows it has stopped reading its terminal, within MAKE_WAY_SECONDS; False where it was answered first, stopped, made way for another loop-inbox, 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
|
|
|
|
|
|
def make_way(folder: pathlib.Path, ask: Ask, pid: int, effects: Effects) -> None:
|
|
"""The loop's side of /talk from loop-inbox, once it has stopped reading its terminal: lists ask as having claude open in the loop-inbox whose process is pid, which claim_talk waits for. A failure only warns: claim_talk then gives up, and the loop stops."""
|
|
shown(folder, dataclasses.replace(ask, state=OpenInInbox(pid)), effects)
|