Files
claude-config/bin/claude-instances
T

84 lines
2.3 KiB
Python
Executable File

#!/usr/bin/env python3
import os
import sys
import time
CODE = os.path.expanduser("~/code")
HOME = os.path.expanduser("~")
INTERVAL = float(os.environ.get("INTERVAL", "2"))
PLUMBING = ("--bg-pty-host", "--bg-spare", "--json-path", "--spawned-by")
def processes():
found = {}
for pid in os.listdir("/proc"):
if not pid.isdigit():
continue
try:
argv = open(f"/proc/{pid}/cmdline", "rb").read().decode("utf-8", "replace").split("\0")[:-1]
cwd = os.readlink(f"/proc/{pid}/cwd")
ppid = next(int(line.split()[1]) for line in open(f"/proc/{pid}/status") if line.startswith("PPid:"))
except (OSError, StopIteration, ValueError):
continue
if argv:
found[int(pid)] = (argv, ppid, cwd.removesuffix(" (deleted)"))
return found
def shown(cwd):
if cwd == CODE:
return "code"
if cwd.startswith(f"{CODE}/"):
return os.path.relpath(cwd, CODE)
return cwd.replace(HOME, "~", 1)
def is_claude(argv):
return os.path.basename(argv[0]).startswith("claude") and not any(flag in argv for flag in PLUMBING)
def wrappers(found):
parents = set()
for argv, ppid, _ in found.values():
parent = found.get(ppid)
if is_claude(argv) and parent and os.path.basename(parent[0][0]).startswith("python"):
parents.add(ppid)
return parents
def wrapper_row(found, pid):
children = {child for child, (argv, ppid, _) in found.items() if ppid == pid and is_claude(argv)}
status = "Inter" if any("-p" not in found[child][0] for child in children) else "Auto"
return (status, shown(found[pid][2])), children
def rows(found):
listed, claimed = [], set()
for pid in wrappers(found):
row, children = wrapper_row(found, pid)
listed.append(row)
claimed |= children
listed += [("Other", shown(cwd)) for pid, (argv, _, cwd) in found.items() if pid not in claimed and is_claude(argv)]
return sorted(listed, key=lambda row: (row[1], row[0]))
def table(listed):
width = max([len(path) for _, path in listed] + [4])
out = [f"{'STATUS':<6} {'PATH':<{width}}", f"{'-' * 6} {'-' * width}"]
out += [f"{status:<6} {path:<{width}}" for status, path in listed] or ["(none running)"]
return "\n".join(out)
def main():
try:
while True:
sys.stdout.write("\x1b[H\x1b[2J" + table(rows(processes())) + "\n")
sys.stdout.flush()
time.sleep(INTERVAL)
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()