Files
claude-config/bin/loop_inbox/main.py
T

190 lines
8.7 KiB
Python

"""Show the interrupts of every loop-claude on this machine, oldest first, and answer each one here.
Below them, list every loop-claude that runs and the todo.md items its chunk takes.
usage: loop-inbox
Each loop-claude lists its interrupt here, as well as on its own terminal, until it is answered or
the loop stops. The list shows each loop's checkout, when it asked and how long it has waited, and
the question's first lines; it refreshes every second. Type a loop's number and Enter to see as much
of its question as fits; the loop's terminal shows it whole. Answer as on the loop's terminal:
- A line and Enter sends it to that loop, which goes on with it. Of a pasted answer, only the first
line is sent, and the rest is dropped; a longer answer goes through /talk.
- /talk opens the worker's claude session here, with `claude --resume`, as /talk does on the loop's
terminal. Once that claude ends, the loop goes on if you typed there, and the judge rules on what
you typed; if you typed no answer, the loop stops.
- Enter alone, or Esc, goes back to the list; unlike on the loop's terminal, it doesn't stop the loop.
The loop takes whichever answer comes first, here or on its terminal, so it keeps working with no
loop-inbox running. A loop with claude open, for a release ready to cut, the routing calls or a
/talk, says where, and is answered there. A loop whose process is gone drops off the list. A loop
asking for its project's model, as on a project's first run, asks on its own terminal only. q quits
loop-inbox; the loops keep waiting.
Below the questions, loop-inbox lists each running loop: its checkout, its number in the list
above where it waits for an answer, and a line per todo.md item its chunk takes, with the item's
tagline on the default branch. A loop whose process is gone drops off this list too.
The loops' questions are files in ~/.local/state/loop-claude, read and written as
bin/loop_state/waiting/ describes; the running loops are files beside them, as
bin/loop_state/running_loops.py describes.
Exit 2 when stdin or stdout is not a terminal, or on an unknown argument.
"""
import contextlib
import curses
import dataclasses
import pathlib
import sys
import typing
from loop_inbox.inbox import Answering, answering_lines, BACKSPACE, ENTER, ESCAPE, fitted, Listing, listing_lines, Open, pressed, Quit, Screen, Send
from loop_state.waiting.ask import Ask, Asking, read_ask
from loop_state.waiting.listing import ask_file, drop_ended, waiting
from loop_state.waiting.talk import claim_talk, MAKE_WAY_SECONDS
from loop_state.waiting.answers import ClaudeEnded, send, Typed
from loop_state.running_loops import drop_ended_loops, running_loops
from loop_effects.effects import Effects, system_effects
from failure import Failure
from loop_state.hand_over import hand_over
from loop_state.paths import Paths, paths_from
from loop_state.session_lock import running
USAGE = "usage: loop-inbox"
# Milliseconds between refreshes of the list while no key is pressed.
REFRESH_MS = 1000
KEYS = {"\n": ENTER, "\r": ENTER, curses.KEY_ENTER: ENTER, "\x7f": BACKSPACE, "\b": BACKSPACE, curses.KEY_BACKSPACE: BACKSPACE, "\x1b": ESCAPE}
def main(argv: list[str], home: pathlib.Path) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
if argv:
print(f"loop-inbox: unknown argument {argv[0]}; {USAGE}", file=sys.stderr)
return 2
if not (sys.stdin.isatty() and sys.stdout.isatty()):
print("loop-inbox: stdin or stdout is not a terminal; run it on one", file=sys.stderr)
return 2
# curses may hold keys it has read ahead, which only flushinp drops.
effects = dataclasses.replace(system_effects(), discard_typed=curses.flushinp)
try:
curses.wrapper(lambda window: run(window, lambda: off_screen(window), paths_from(home), effects))
except KeyboardInterrupt:
pass
return 0
def run(window: curses.window, screen_off: typing.Callable[[], typing.ContextManager[None]], paths: Paths, effects: Effects) -> None:
folder = paths.waiting
window.timeout(REFRESH_MS)
screen: Screen = Listing()
while True:
drop_ended(folder)
drop_ended_loops(folder)
screen = entered(screen, refreshed(screen, folder), effects)
draw(window, screen, effects)
try:
key = window.get_wch()
except curses.error:
continue # No key within REFRESH_MS.
after: Screen
match pressed(screen, key_name(key)):
case Quit():
return
case Send(ask, text):
after = Listing(note=sent(folder, ask, text))
case Open(ask):
after = Listing(note=opened(screen_off, paths, ask, effects))
case Listing() | Answering() as next_screen:
after = next_screen
screen = entered(screen, after, effects)
def entered(before: Screen, after: Screen, effects: Effects) -> Screen:
"""after, the screen that follows before. Leaving the answer screen drops the keys typed ahead, since on the list the rest of a pasted answer would pick a loop and answer it."""
if isinstance(before, Answering) and isinstance(after, Listing):
effects.discard_typed()
return after
def key_name(key: str | int) -> str:
"""inbox's name for a key curses read; an empty string for a key loop-inbox has no use for, such as an arrow."""
return KEYS.get(key, key if isinstance(key, str) else "")
def refreshed(screen: Screen, folder: pathlib.Path) -> Screen:
"""screen with the loops as they wait and run now, unless the human is typing a number; a question that no longer waits leaves the answer screen."""
match screen:
case Listing(_, "", note):
return Listing(tuple(waiting(folder)), "", note, tuple(running_loops(folder)))
case Answering(ask) if not still_waits(folder, ask):
return Listing(note=no_longer_waits(ask))
return screen
def draw(window: curses.window, screen: Screen, effects: Effects) -> None:
height, columns = window.getmaxyx()
# The screen's last cell cannot be written without an error, so lines leave the last column empty.
width = columns - 1
now = effects.now()
lines, foot = listing_lines(screen, now, effects.local_time, width) if isinstance(screen, Listing) else answering_lines(screen, now, effects.local_time, width)
window.erase()
for row, line in enumerate(fitted(lines, foot, height)):
# addnstr counts characters, not cells, so a line of wide characters, such as emoji, can still run into the last cell.
with contextlib.suppress(curses.error):
window.addnstr(row, 0, line, width)
window.refresh()
def still_waits(folder: pathlib.Path, ask: Ask) -> bool:
"""Whether ask's loop still runs and still waits for an answer from loop-inbox."""
now = read_ask(ask_file(folder, ask.session))
return now is not None and now.id == ask.id and isinstance(now.state, Asking) and running(folder, ask.session)
def no_longer_waits(ask: Ask) -> str:
return f"{ask.root} no longer waits for that answer: it was answered elsewhere, or stopped."
def sent(folder: pathlib.Path, ask: Ask, text: str) -> str:
"""Sends text to the loop that asked ask, and says what came of it."""
if not still_waits(folder, ask):
return no_longer_waits(ask)
if unsent := send(folder, ask, Typed(text)):
return f"Could not send the answer to {ask.root}: {unsent.reason}"
return f"Sent to {ask.root}."
def opened(screen_off: typing.Callable[[], typing.ContextManager[None]], paths: Paths, ask: Ask, effects: Effects) -> str:
"""Opens the worker's claude session on this terminal, inside screen_off, once the loop has made way for it, and says what came of it."""
folder = paths.waiting
if not (isinstance(ask.state, Asking) and still_waits(folder, ask)):
return no_longer_waits(ask)
claimed = claim_talk(folder, ask, effects.pid(), effects.now, effects.sleep)
if isinstance(claimed, Failure):
return f"Could not open claude for {ask.root}: {claimed.reason}"
if not claimed:
return f"Could not open claude for {ask.root}: the loop was answered elsewhere or stopped, or didn't respond within {MAKE_WAY_SECONDS:g} s. If it is still listed, pick it again."
with screen_off():
try:
unstarted = hand_over(ask.state.talk, effects)
finally:
unsent = send(folder, ask, ClaudeEnded())
# The loop goes on only where the human typed in the worker's session, as interrupt.human_typed checks.
said = f"Could not start claude for {ask.root}: {unstarted.reason}. The loop stops." if unstarted else f"claude for {ask.root} has ended; the loop goes on if you typed there, and stops if you didn't."
# The loop also stops waiting for claude once loop-inbox's process ends.
return f"{said} Could not tell the loop that claude ended: {unsent.reason}; it waits until you quit loop-inbox." if unsent else said
@contextlib.contextmanager
def off_screen(window: curses.window) -> typing.Iterator[None]:
"""Hands the terminal to another program, and draws loop-inbox again once it ends."""
curses.def_prog_mode()
curses.endwin()
try:
yield
finally:
curses.reset_prog_mode()
window.refresh()