137 lines
4.4 KiB
Python
137 lines
4.4 KiB
Python
"""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.
|
|
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.
|
|
"""
|
|
import dataclasses
|
|
import json
|
|
import os
|
|
import pathlib
|
|
|
|
from failure import Failure
|
|
from file_writes import make_private, replace_json
|
|
|
|
|
|
@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."""
|
|
args: list[str]
|
|
cwd: str
|
|
env: dict[str, str]
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Ask:
|
|
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
|
|
# 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
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Typed:
|
|
text: str
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Talking:
|
|
pid: int
|
|
|
|
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Talked:
|
|
pass
|
|
|
|
|
|
Answer = Typed | Talking | Talked
|
|
|
|
|
|
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))
|
|
|
|
|
|
def withdraw(folder: pathlib.Path, session: str) -> None:
|
|
"""Removes the session's ask and any answer to it."""
|
|
for path in (ask_file(folder, session), answer_file(folder, session)):
|
|
path.unlink(missing_ok=True)
|
|
|
|
|
|
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, 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:
|
|
try:
|
|
data = json.loads(path.read_text(encoding="utf-8"))
|
|
talk = data["talk"] and TalkCommand(**data["talk"])
|
|
ask = Ask(**{**data, "talk": talk})
|
|
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 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."""
|
|
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": "Talking", "pid": int(pid)}:
|
|
return Talking(pid)
|
|
case {"kind": "Talked"}:
|
|
return Talked()
|
|
return None
|
|
|
|
|
|
def alive(pid: int) -> bool:
|
|
try:
|
|
os.kill(pid, 0)
|
|
except ProcessLookupError:
|
|
return False
|
|
except PermissionError:
|
|
return True
|
|
return True
|