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

177 lines
7.2 KiB
Python

"""Show every loop-claude on this machine that waits for you, oldest first, and answer each one here.
usage: loop-inbox
Each loop-claude that asks you a question lists it 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 its whole question, then answer as on the loop's terminal:
- A line and Enter sends it to that loop, which goes on with it.
- /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, and the judge rules on what was typed there; a
loop whose claude ends with nothing typed 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 whose release is ready to cut, or whose /talk is open, shows that claude
is open, and is answered there. A loop whose process is gone drops off the list. q quits
loop-inbox; the loops keep waiting.
The loops' questions are files in ~/.local/state/loop-claude, read and written as
bin/loop_claude/waiting.py describes.
Exit 2 when stdin or stdout is not a terminal, or on an unknown argument.
"""
import curses
import os
import pathlib
import signal
import subprocess
import sys
import time
from loop_inbox.inbox import Answering, answering_lines, BACKSPACE, ENTER, ESCAPE, fitted, Listing, listing_lines, Open, pressed, Quit, Screen, Send
from loop_claude.waiting import Ask, ask_file, read_ask, send, Talked, Talking, Typed, waiting
from loop_claude.paths import Paths, paths_from
from loop_claude.effects import system_effects
from claude_code.trust import trust
from loop_claude.project.checkout import worktrees
USAGE = "usage: loop-inbox"
# Milliseconds between refreshes of the list while no key is pressed.
REFRESH_MS = 1000
# Seconds loop-inbox waits for a loop to stop reading its terminal before it opens claude for /talk; the loop looks for an answer every half second.
MAKE_WAY_SECONDS = 5
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
try:
curses.wrapper(lambda window: run(window, paths_from(home)))
except KeyboardInterrupt:
pass
return 0
def run(window: curses.window, paths: Paths) -> None:
folder = paths.waiting
window.timeout(REFRESH_MS)
screen: Screen = Listing()
while True:
screen = refreshed(screen, folder)
draw(window, screen)
try:
key = window.get_wch()
except curses.error:
continue # No key within REFRESH_MS.
match pressed(screen, key_name(key)):
case Quit():
return
case Send(ask, text):
screen = Listing(note=sent(folder, ask, text))
case Open(ask):
screen = Listing(note=talked(window, paths, ask))
case Listing() | Answering() as next_screen:
screen = next_screen
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 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)
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) -> None:
height, width = window.getmaxyx()
now = time.time()
lines = listing_lines(screen, now, local_time, width) if isinstance(screen, Listing) else answering_lines(screen, now, local_time, width)
window.erase()
for row, line in enumerate(fitted(lines, height)):
# The last cell of the screen cannot be written without an error, so each line stops one short of it.
window.addnstr(row, 0, line, width - 1)
window.refresh()
def local_time(seconds: float) -> str:
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(seconds))
def still_waits(folder: pathlib.Path, ask: Ask) -> bool:
"""Whether ask 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 now.talk is not None
def no_longer_waits(ask: Ask) -> str:
return f"{ask.root} no longer waits for that answer: it was answered on its terminal, 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 talked(window: curses.window, paths: Paths, ask: Ask) -> str:
"""Opens the worker's claude session on this terminal once the loop has stopped reading its own, and says what came of it."""
folder = paths.waiting
if not still_waits(folder, ask) or ask.talk is None:
return no_longer_waits(ask)
if unsent := send(folder, ask, Talking(os.getpid())):
return f"Could not open claude for {ask.root}: {unsent.reason}"
if not made_way(folder, ask):
return f"{ask.root} did not make way for claude within {MAKE_WAY_SECONDS} s; it was answered on its terminal, or stopped."
curses.def_prog_mode()
curses.endwin()
# As loop-claude's hand_over does before it opens claude on its own terminal.
trust(paths.claude_json, worktrees(ask.talk.cwd, system_effects()), lambda text: print(f"loop-inbox: {text}", file=sys.stderr))
# Ctrl-C belongs to claude while it runs, not to loop-inbox.
interrupt = signal.signal(signal.SIGINT, signal.SIG_IGN)
try:
subprocess.run(["claude", *ask.talk.args], cwd=ask.talk.cwd, env={**os.environ, **ask.talk.env})
said = f"claude for {ask.root} has ended; the loop goes on."
except OSError as failure:
said = f"Could not start claude for {ask.root}: {failure.strerror}"
finally:
signal.signal(signal.SIGINT, interrupt)
unsent = send(folder, ask, Talked())
curses.reset_prog_mode()
window.refresh()
# Without Talked, the loop goes on only once loop-inbox quits.
return f"{said} Could not tell the loop: {unsent.reason}; quit loop-inbox to let it go on." if unsent else said
def made_way(folder: pathlib.Path, ask: Ask) -> bool:
"""Whether the loop shows, within MAKE_WAY_SECONDS, that it has stopped reading its terminal for this loop-inbox."""
deadline = time.monotonic() + MAKE_WAY_SECONDS
while time.monotonic() < deadline:
now = read_ask(ask_file(folder, ask.session))
if now is None or now.id != ask.id:
return False
if now.talking == os.getpid():
return True
time.sleep(0.1)
return False