Files

176 lines
7.0 KiB
Python

"""The shells a running claude has started, read from /proc (Linux), and how to stop one.
Claude Code starts each Bash call as `bash -c "source <snapshot> && … && eval '<the command>'"` and writes its output to a file under /tmp/claude-<uid>/.
"""
import dataclasses
import os
import pathlib
import signal
import stat
import typing
# The command names of a shell claude starts for a Bash call.
SHELL_NAMES = frozenset({"bash", "dash", "sh", "zsh"})
COMMAND_CHARS = 300
OUTPUT_BYTES = 2000
# Scripts whose process below a shell shows work that may go quiet for long: run-heavy while it waits for a slot, and chunk-pr, which waits for a merge's approval and checks.
BUSY_TOOLS = frozenset({"chunk-pr", "run-heavy"})
@dataclasses.dataclass(frozen=True)
class Shell:
pid: int
# Epoch seconds at which the shell started.
started: float
# What the shell runs, without the snapshot Claude Code sources before it.
command: str
# Epoch seconds of the last write to the file the shell's output goes to; the shell's start where the output goes to no file, which the check cannot read.
written: float
# Whether a process below the shell runs one of BUSY_TOOLS.
runs_busy_tool: bool
# CPU seconds the shell and every process below it have used.
cpu: float = 0.0
# Each process below the shell, as `<pid> <state> <CPU seconds> s <command line>`, with the state letter /proc gives, such as S for sleeping.
processes: tuple[str, ...] = ()
# The last OUTPUT_BYTES of the file the shell's output goes to; empty where it goes to a pipe or a terminal.
output: str = ""
# Whether a process below the shell holds a heavy slot: a file of slot_folder, which run-heavy leaves open in the command it runs.
holds_slot: bool = False
def stat_of(pid: int) -> tuple[str, list[str]] | None:
"""A process's command name and the fields of /proc/<pid>/stat after it, from the state on; None where it is gone."""
try:
with open(f"/proc/{pid}/stat") as handle:
text = handle.read()
except OSError:
return None
# The name sits in parentheses and may hold spaces or parentheses itself, so split at the last one.
return text[text.index("(") + 1 : text.rindex(")")], text[text.rindex(")") + 2 :].split()
def parent_and_start(pid: int) -> tuple[int, int, str] | None:
"""The parent pid, the start time in clock ticks since boot and the command name of a process; None where it is gone."""
found = stat_of(pid)
return None if found is None else (int(found[1][1]), int(found[1][19]), found[0])
def cpu_and_state(pid: int) -> tuple[float, str]:
"""The CPU seconds a process has used, in user and kernel mode, and its state letter; 0.0 and `gone` where it is gone."""
found = stat_of(pid)
if found is None:
return 0.0, "gone"
fields = found[1]
return (int(fields[11]) + int(fields[12])) / os.sysconf("SC_CLK_TCK"), fields[0]
def children_of(pid: int) -> list[int]:
return [int(entry) for entry in os.listdir("/proc") if entry.isdigit() and (found := parent_and_start(int(entry))) and found[0] == pid]
def argv_of(pid: int) -> list[str]:
try:
with open(f"/proc/{pid}/cmdline", "rb") as handle:
return handle.read().decode(errors="replace").rstrip("\0").split("\0")
except OSError:
return []
def descendants(pid: int) -> list[int]:
"""Every process below pid, each after its parent."""
found = children_of(pid)
for child in list(found):
found += descendants(child)
return found
def boot_time() -> float:
with open("/proc/stat") as handle:
return next(float(line.split()[1]) for line in handle if line.startswith("btime"))
def output_written(pid: int, started: float) -> float:
"""When the file that pid's standard output goes to was last written; started where it goes to a pipe or a terminal."""
try:
info = os.stat(f"/proc/{pid}/fd/1")
except OSError:
return started
return info.st_mtime if stat.S_ISREG(info.st_mode) else started
def output_tail(pid: int) -> str:
"""The last OUTPUT_BYTES of the file that pid's standard output goes to; empty where it goes to a pipe or a terminal."""
path = f"/proc/{pid}/fd/1"
try:
# Before the open, which can block on a pipe.
if not stat.S_ISREG(os.stat(path).st_mode):
return ""
with open(path, "rb") as handle:
handle.seek(max(0, os.fstat(handle.fileno()).st_size - OUTPUT_BYTES))
return handle.read().decode(errors="replace")
except OSError:
return ""
def tree_of(pid: int) -> tuple[float, tuple[str, ...]]:
"""The CPU seconds pid and every process below it have used, and each process below it as `Shell.processes` shows one."""
total = cpu_and_state(pid)[0]
shown = []
for each in descendants(pid):
cpu, state = cpu_and_state(each)
total += cpu
shown.append(f"{each} {state} {cpu:.1f} s {' '.join(argv_of(each))[:COMMAND_CHARS]}")
return total, tuple(shown)
def command_of(shell_argv: list[str]) -> str:
"""What a shell runs: the text of its command line after Claude Code's `eval '`, up to the last ` < /dev/null`, which a call that began in the foreground lacks; the whole line where it holds no `eval`."""
line = " ".join(shell_argv)
_, found, command = line.partition(" && eval ")
return (command.rsplit(" < /dev/null", 1)[0].removeprefix("'").removesuffix("'") if found else line)[:COMMAND_CHARS]
def has_slot(pid: int, slots: pathlib.Path) -> bool:
"""Whether pid has a file of the heavy slots' folder open. run-heavy replaces itself with its command once it holds a slot, and the command keeps the slot's file open."""
try:
return any(os.readlink(f"/proc/{pid}/fd/{fd}").startswith(f"{slots}/") for fd in os.listdir(f"/proc/{pid}/fd"))
except OSError:
return False
def runs_busy_tool(pid: int) -> bool:
"""Whether a process below pid has one of BUSY_TOOLS as its program or its script, as `python3 /x/chunk-pr`. A command line that merely names a tool, such as a `pgrep -f chunk-pr`, doesn't count."""
return any(os.path.basename(name) in BUSY_TOOLS for each in descendants(pid) for name in argv_of(each)[:2])
def holds_slot(pid: int, slots: pathlib.Path) -> bool:
"""Whether a process below pid holds a heavy slot."""
return any(has_slot(each, slots) for each in descendants(pid))
def shells_of(claude_pid: int, slots: pathlib.Path, children: typing.Callable[[int], list[int]]) -> list[Shell]:
"""The shells that are children of claude_pid, which children lists as children_of does, each knowing whether it holds a heavy slot in the folder slots; none where /proc doesn't exist, as off Linux."""
if not os.path.isdir("/proc"):
return []
booted = boot_time()
ticks = os.sysconf("SC_CLK_TCK")
shells = []
for pid in children(claude_pid):
found = parent_and_start(pid)
if found is None or found[2] not in SHELL_NAMES:
continue
started = booted + found[1] / ticks
cpu, processes = tree_of(pid)
shells.append(Shell(pid, started, command_of(argv_of(pid)), output_written(pid, started), runs_busy_tool(pid), cpu, processes, output_tail(pid), holds_slot(pid, slots)))
return shells
def stop(shell: Shell) -> None:
"""Ends the shell and every process below it, so that a loop the shell runs doesn't outlive it."""
for pid in [*reversed(descendants(shell.pid)), shell.pid]:
try:
os.kill(pid, signal.SIGTERM)
except OSError:
pass