Files
claude-config/bin/agent_cycle/tmux.py
T

164 lines
9.1 KiB
Python

"""The tmux commands an entry point runs: each chunk's loop runs in its own window of one tmux session, which loop-claude names for the project and do-epic for the epic (docs/decisions.md → `loop-claude: each chunk runs in its own tmux window`)."""
import dataclasses
import re
import subprocess
import typing
from failure import Failure
# Runs tmux with these arguments and returns what it printed; exit 127 where tmux cannot start.
Tmux = typing.Callable[[list[str]], subprocess.CompletedProcess[str]]
# The oldest tmux that has every command and option used here. Its CHANGES file dates the newest two to 3.2: `remain-on-exit failed` and `new-session -e`.
NEEDED = (3, 2)
# What a window's name ends in while its chunk waits for the human. tmux's status bar shows the name, and `!` after it once the bell rang.
WAITS = " ?"
BELL = "\a"
# What follows a window's name while its chunk is parked, before what its pull request waits on, as in `ABC-34 awaits an approval`. A parked chunk takes no running slot (docs/decisions.md → `do-epic: drives one Jira epic …`, "Long gates").
PARKED = " awaits "
# What a session's name opens with: LOOP for a project's chunks under loop-claude, EPIC for an epic's chunks under do-epic.
LOOP = "loop"
EPIC = "epic"
# The session option that names the checkout whose chunks the session runs, since two checkouts' keys may map to one session name.
OWNER = "@loop-root"
# The window option that names the folder a window's chunk works in, so that loop-claude and every do-epic see the chunks a do-epic runs in a checkout.
ROOT = "@chunk-root"
@dataclasses.dataclass(frozen=True)
class Window:
"""The tmux window a chunk's loop runs in."""
session: str
# Without WAITS.
name: str
# The ID of the loop's pane, which $TMUX_PANE holds. It targets the window whatever its name is.
pane: str
@property
def target(self) -> str:
"""What `tmux attach -t` and `tmux select-window -t` take to reach the window."""
return f"{self.session}:{self.name}"
@dataclasses.dataclass(frozen=True)
class Listed:
"""A window of the project's session, as tmux lists it."""
# Without WAITS, and without PARKED and what follows it.
name: str
# tmux's ID of the window, such as `@3`.
id: str
# Whether its loop has exited: `remain-on-exit failed` keeps the window of a loop that failed, so its last lines stay readable.
dead: bool
# What its name says its parked chunk awaits, as the words after PARKED; empty for a chunk that isn't parked.
awaits: str = ""
# Whether its name ended in WAITS: its loop asks the human something.
asks: bool = False
@property
def parked(self) -> bool:
return bool(self.awaits)
@dataclasses.dataclass(frozen=True)
class Placed:
"""A window of any session, as tmux lists it."""
session: str
window: Listed
# The folder its chunk works in, as ROOT names it; empty for a window started before ROOT was set.
root: str
def unusable(run: Tmux, driver: str) -> str | None:
"""Why driver, the entry point, cannot use this machine's tmux, naming the version found and the one needed; None where it is NEEDED or later."""
found = run(["-V"]).stdout.strip()
version = re.search(r"([0-9]+)\.([0-9]+)", found)
if version and (int(version[1]), int(version[2])) >= NEEDED:
return None
return f"{driver} runs each chunk in a tmux window, and needs tmux {NEEDED[0]}.{NEEDED[1]} or later; it found {found or 'no tmux'}"
def session_name(kind: str, key: str) -> str:
"""The tmux session an entry point runs its chunks in: kind LOOP with a project's key, such as `loop-claude-config`, or kind EPIC with an epic's key, such as `epic-ABC-12`. tmux reads `.` and `:` in a target as separators, so every character of the key but a letter, a digit, `_` and `-` becomes a dash."""
return f"{kind}-" + re.sub(r"[^A-Za-z0-9_-]", "-", key)
def listed(session: str, run: Tmux) -> list[Listed]:
"""The windows of session; none where tmux lists none, as while the session doesn't exist or no tmux server runs."""
done = run(["list-windows", "-t", f"={session}", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"])
rows = [line.split("\t") for line in done.stdout.splitlines()] if done.returncode == 0 else []
return [as_listed(row[0], row[2], row[1]) for row in rows if len(row) == 3]
def as_listed(shown: str, id: str, pane_dead: str) -> Listed:
"""The window tmux shows under the name shown, with the ID id and `#{pane_dead}` as pane_dead."""
name, _, awaits = shown.removesuffix(WAITS).partition(PARKED)
return Listed(name, id, pane_dead == "1", awaits, shown.endswith(WAITS))
def everywhere(run: Tmux) -> list[Placed]:
"""The windows of every session; none where no tmux server runs."""
done = run(["list-windows", "-a", "-F", f"#{{session_name}}\t#{{window_name}}\t#{{pane_dead}}\t#{{window_id}}\t#{{{ROOT}}}"])
rows = [line.split("\t") for line in done.stdout.splitlines()] if done.returncode == 0 else []
return [Placed(row[0], as_listed(row[1], row[3], row[2]), row[4]) for row in rows if len(row) == 5]
def start_window(window: Window, cwd: str, env: typing.Mapping[str, str], command: list[str], first: bool, owned: bool, run: Tmux) -> Failure | None:
"""Starts command in a new window of window's session, in cwd with env added to its environment, and leaves the client where it is. first makes the session too, and owned marks a session it makes as running the chunks of the checkout cwd. A Failure says why tmux started none, or why it could not mark the session."""
make = ["new-session", "-d", "-s", window.session] if first else ["new-window", "-d", "-t", f"={window.session}:"]
variables = [flag for name, value in env.items() for flag in ("-e", f"{name}={value}")]
# tmux reads a `;` that ends an argument as the end of the command, unless a backslash precedes it.
words = [re.sub(r";$", r"\\;", word) for word in command]
done = run([*make, "-n", window.name, "-c", cwd, *variables, "-P", "-F", "#{window_id}", "--", *words])
if done.returncode:
return Failure(f"tmux could not start the window {window.target}: {done.stderr.strip() or f'it exited {done.returncode}'}")
# set-option and show-options read a target as a pane's, so `=session` alone names no session.
marked = run(["set-option", "-t", f"={window.session}:", OWNER, cwd]) if first and owned else None
# A failure leaves the window unseen by loop-claude and by another epic's do-epic, which then may start a chunk beside it; the window still runs.
run(["set-option", "-w", "-t", done.stdout.strip(), ROOT, cwd])
# By the ID, since a window of the same name may still be closing. A failed remain-on-exit doesn't matter: a loop that fails before it is set closes its window, and its stop is still sent as a DM.
run(["set-option", "-w", "-t", done.stdout.strip(), "remain-on-exit", "failed"])
# Without the owner, start_chunks cannot tell this checkout's session from another's, so no further chunk may start in it.
if marked is not None and marked.returncode:
return Failure(f"tmux started the session {window.session} but could not mark it as this checkout's: {marked.stderr.strip() or f'it exited {marked.returncode}'}")
return None
def start_chunk(window: Window, cwd: str, env: typing.Mapping[str, str], command: list[str], windows: list[Listed], owned: bool, run: Tmux) -> list[Listed] | Failure:
"""Starts a chunk's command in window, in place of each dead window of its name among windows, the session's; the session's windows afterwards, or why tmux started none. start_window says what cwd, env and owned do."""
stale = [listed for listed in windows if listed.name == window.name and listed.dead]
for listed in stale:
close(listed, run)
kept = [listed for listed in windows if listed not in stale]
failed = start_window(window, cwd, env, command, not kept, owned, run)
return failed or [*kept, Listed(window.name, "", False)]
def owner(session: str, run: Tmux) -> str:
"""The checkout whose chunks session runs, as OWNER names it; empty where it names none."""
return run(["show-options", "-qv", "-t", f"={session}:", OWNER]).stdout.strip()
def close(window: Listed, run: Tmux) -> None:
run(["kill-window", "-t", window.id])
def mark(window: Window, waits: bool, run: Tmux) -> None:
"""Renames window to end in WAITS while its chunk waits for the human, and back once it doesn't."""
run(["rename-window", "-t", window.pane, window.name + (WAITS if waits else "")])
def park(window: Window, on: str, run: Tmux) -> None:
"""Shows window's chunk as parked. on is what the chunk awaits, such as `an approval` or `a slot`: the name says so, and no checkout counts a window so named as a running chunk."""
run(["rename-window", "-t", window.pane, window.name + PARKED + on])
def unpark(window: Window, root: str, run: Tmux) -> None:
"""Shows window's chunk as running again, in the folder root. The window may name another folder: one started again for a parked chunk starts in the epic's folder."""
run(["rename-window", "-t", window.pane, window.name])
run(["set-option", "-w", "-t", window.pane, ROOT, root])
def show(session: str, inside: bool) -> list[str]:
"""The tmux arguments that put session on the human's terminal: inside tmux the client switches to it, and outside a new client attaches."""
return ["switch-client" if inside else "attach-session", "-t", f"={session}"]