"""An interrupt's question as loop-inbox lists it, and how its file is read; `tagged` writes the kind that `ask_state` reads. 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.""" import dataclasses import json import pathlib import typing from loop_claude.hand_over import ClaudeCommand from records.utc_stamp import seconds, utc if typing.TYPE_CHECKING: from _typeshed import DataclassInstance @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 def tagged(value: "DataclassInstance") -> dict[str, object]: """value's fields, with its kind, which ask_state and answers.received read it back by.""" return dataclasses.asdict(value) | {"kind": type(value).__name__} @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; its file holds it as an ISO UTC datetime, as ask_fields writes it. asked: float state: AskState def ask_fields(ask: Ask) -> dict[str, object]: """ask as its file holds it, which read_ask reads back to the second.""" return dataclasses.asdict(ask) | {"asked": utc(ask.asked), "state": tagged(ask.state)} def read_ask(path: pathlib.Path) -> Ask | None: """The ask in path. None where a field has the wrong type, where utc_stamp.seconds cannot read asked, or where the ask names another session than path does.""" try: data = json.loads(path.read_text(encoding="utf-8")) ask = Ask(**{**data, "asked": seconds(data["asked"]), "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 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}")