"""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 utc_stamp import seconds 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, as utc_stamp.utc writes it: an ISO UTC datetime. asked: str state: AskState def read_ask(path: pathlib.Path) -> Ask | None: """The ask in path; None where a field has the wrong type, asked is no stamp utc_stamp.utc writes, or the ask names another session than path does.""" try: data = json.loads(path.read_text(encoding="utf-8")) ask = Ask(**{**data, "state": ask_state(data["state"])}) if not all(isinstance(text, str) for text in (ask.id, ask.session, ask.root, ask.question, ask.asked)) or ask.session != path.stem: return None seconds(ask.asked) except (OSError, ValueError, TypeError, KeyError): return None return ask 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}")