#!/usr/bin/env python3 """sessions-ctl — create, list, start and stop Claude Code sessions on this box. Two ways in: * Locally: sessions-ctl [args] (all verbs) * Over SSH: sessions-ctl --remote (forced command in authorized_keys) The requested command is read from $SSH_ORIGINAL_COMMAND and only REMOTE_VERBS are accepted. Nothing sent over SSH is ever passed to a shell or to Claude as a prompt — see README "Security model". Each session is: * a git checkout in / on branch session/ * a state file ~/.local/state/sessions/.json (repo, uuid, …) * a systemd user unit claude-session@.service that runs `claude` with Remote Control inside its own tmux server (socket: tmux -L claude-). systemd is the source of truth for "should this run": a session that is enabled starts at boot (the user has linger on) and is restarted if it dies. Output is one JSON object on stdout (except `keygen`, which prints an env block to copy). Exit codes: 0 ok, 1 error, 2 usage. Standard library only, so it runs with the system python3. """ from __future__ import annotations import base64 import datetime as dt import getpass import fcntl import json import os import re import shlex import shutil import socket import subprocess import sys import tempfile import tomllib import uuid from contextlib import contextmanager from pathlib import Path HOME = Path.home() CONFIG_PATH = Path(os.environ.get("SESSIONS_CONFIG", HOME / ".config/sessions/config.toml")) STATE_DIR = Path(os.environ.get("SESSIONS_STATE_DIR", HOME / ".local/state/sessions")) CLAUDE_JSON = Path(os.environ.get("SESSIONS_CLAUDE_JSON", HOME / ".claude.json")) CLAUDE_PROJECTS = HOME / ".claude/projects" AUTHORIZED_KEYS = Path(os.environ.get("SESSIONS_AUTHORIZED_KEYS", HOME / ".ssh/authorized_keys")) SELF_PATH = HOME / ".local/bin/sessions-ctl" HOST_KEY_PATH = os.environ.get("SESSIONS_HOST_KEY", "/etc/ssh/ssh_host_ed25519_key.pub") UNIT = "claude-session@{}.service" KEY_MARKER = "sessions-manager" # comment that tags the one line we own in authorized_keys NAME_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,31}$") # What the user typed as the name: letters, digits, single spaces and '-'. The # session's NAME (directory, branch, unit, tmux socket) is derived from it. TITLE_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]| (?! )){0,47}(? dict: path = path or CONFIG_PATH # looked up at call time, so tests can repoint it cfg = dict(DEFAULTS) if path.exists(): with path.open("rb") as f: cfg.update(tomllib.load(f)) cfg["workspace_root"] = Path(os.path.expanduser(cfg["workspace_root"])) cfg["max_running"] = int(cfg["max_running"]) for key, url in cfg["repos"].items(): if not NAME_RE.fullmatch(key) or not isinstance(url, str): raise UserError(f"config: bad repo entry {key!r}") return cfg def validate_name(name: str) -> str: if not NAME_RE.fullmatch(name): raise UserError("name must be 1-32 chars of a-z, 0-9 and '-', starting with a letter or digit") return name def name_from_title(title: str) -> tuple[str, str]: """'Fix login bug' -> ('fix-login-bug', 'Fix login bug'). A plain NAME maps to itself.""" if not TITLE_RE.fullmatch(title): raise UserError("name must be 1-48 chars of letters, digits, '-' and single spaces") name = re.sub(r"[^a-z0-9]+", "-", title.lower()).strip("-")[:32].rstrip("-") return validate_name(name), title def validate_branch(branch: str) -> str: if not BRANCH_RE.fullmatch(branch) or ".." in branch or branch.endswith((".lock", "/", ".")): raise UserError("invalid branch name") return branch def state_path(name: str) -> Path: return STATE_DIR / f"{name}.json" def read_state(name: str) -> dict: p = state_path(name) if not p.exists(): raise UserError(f"no session named {name!r}") return json.loads(p.read_text()) def atomic_write(path: Path, text: str, mode: int = 0o600) -> None: path.parent.mkdir(parents=True, exist_ok=True) fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=f".{path.name}.") try: with os.fdopen(fd, "w") as f: f.write(text) os.chmod(tmp, mode) os.replace(tmp, path) except BaseException: Path(tmp).unlink(missing_ok=True) raise def write_state(state: dict) -> None: atomic_write(state_path(state["name"]), json.dumps(state, indent=2) + "\n") def all_states() -> list[dict]: if not STATE_DIR.exists(): return [] return [json.loads(p.read_text()) for p in sorted(STATE_DIR.glob("*.json"))] @contextmanager def lock(): """Serialise create/start so two requests can't both slip under max_running.""" STATE_DIR.mkdir(parents=True, exist_ok=True) with open(STATE_DIR / ".lock", "w") as f: fcntl.flock(f, fcntl.LOCK_EX) yield # ---------------------------------------------------------------- systemd/tmux def _user_env() -> dict: """systemctl --user needs XDG_RUNTIME_DIR; an SSH forced command may lack it.""" env = dict(os.environ) env.setdefault("XDG_RUNTIME_DIR", f"/run/user/{os.getuid()}") return env def systemctl(*args: str, check: bool = True) -> subprocess.CompletedProcess: r = subprocess.run(["systemctl", "--user", *args], capture_output=True, text=True, env=_user_env(), timeout=60) if check and r.returncode != 0: raise RuntimeError(f"systemctl {' '.join(args)}: {r.stderr.strip()}") return r def unit_state(name: str) -> dict: r = systemctl("show", UNIT.format(name), "-p", "ActiveState", "-p", "SubState", "-p", "UnitFileState", "-p", "NRestarts", check=False) props = dict(line.split("=", 1) for line in r.stdout.splitlines() if "=" in line) return { "active": props.get("ActiveState", "unknown"), "sub": props.get("SubState", "unknown"), "enabled": props.get("UnitFileState") == "enabled", "restarts": int(props.get("NRestarts") or 0), } def tmux_socket(name: str) -> str: return f"claude-{name}" def capture_pane(name: str) -> str: r = subprocess.run( ["tmux", "-L", tmux_socket(name), "capture-pane", "-p", "-S", "-300", "-t", f"={name}:"], capture_output=True, text=True, timeout=10, ) return r.stdout if r.returncode == 0 else "" def running_count() -> int: return sum(1 for s in all_states() if unit_state(s["name"])["active"] in ("active", "activating", "reloading")) # ---------------------------------------------------------------- claude trust def trust_workspace(path: Path, claude_json: Path = CLAUDE_JSON) -> None: """Pre-accept Claude Code's "do you trust this folder?" prompt for `path`. An unattended session would otherwise sit on that prompt forever. The repo allowlist in config.toml *is* the trust decision, so recording it here is equivalent to the admin clicking "Yes". The file is shared with running claude processes, so the update is a fast read-modify-rename. """ data = json.loads(claude_json.read_text()) if claude_json.exists() else {} projects = data.setdefault("projects", {}) entry = projects.setdefault(str(path), {}) if entry.get("hasTrustDialogAccepted") is True: return entry["hasTrustDialogAccepted"] = True mode = claude_json.stat().st_mode & 0o777 if claude_json.exists() else 0o600 atomic_write(claude_json, json.dumps(data, indent=2), mode) def untrust_workspace(path: Path, claude_json: Path = CLAUDE_JSON) -> None: if not claude_json.exists(): return data = json.loads(claude_json.read_text()) if data.get("projects", {}).pop(str(path), None) is not None: atomic_write(claude_json, json.dumps(data, indent=2), claude_json.stat().st_mode & 0o777) def claude_args(state: dict, prefix: str, projects_dir: Path = CLAUDE_PROJECTS) -> list[str]: """First launch pins the conversation id; every later launch resumes it. Sessions run with --dangerously-skip-permissions: no tool call waits for approval. See README "Security model" for why that is acceptable here. """ rc_name = f"{prefix}-{state['name']}" title = state.get("title") or state["name"] args = ["claude", "--dangerously-skip-permissions", "--remote-control", rc_name, "--name", title] if any(projects_dir.glob(f"*/{state['uuid']}.jsonl")): return args + ["--resume", state["uuid"]] return args + ["--session-id", state["uuid"]] # ---------------------------------------------------------------- verbs def session_view(state: dict, with_pane: bool = True) -> dict: u = unit_state(state["name"]) view = { "name": state["name"], "title": state.get("title") or state["name"], "archived": bool(state.get("archived")), "repo": state["repo"], "branch": state["branch"], "created_at": state["created_at"], "state": u["active"], "enabled": u["enabled"], "restarts": u["restarts"], "remote_control_url": state.get("remote_control_url"), "needs_attention": None, } if with_pane and u["active"] == "active": pane = capture_pane(state["name"]) m = RC_URL_RE.search(pane) if m and m.group(0) != state.get("remote_control_url"): view["remote_control_url"] = m.group(0) with lock(): # re-read so this can't undo a concurrent archive/unarchive fresh = read_state(state["name"]) fresh["remote_control_url"] = m.group(0) write_state(fresh) if TRUST_PROMPT in pane: view["needs_attention"] = "stuck on the folder-trust prompt; attach with tmux to accept" elif BYPASS_PROMPT in pane: view["needs_attention"] = "stuck on the bypass-permissions warning; attach with tmux to accept" return view def cmd_list(cfg: dict, args: list[str]) -> dict: _arity(args, 0, 0) return {"sessions": [session_view(s) for s in all_states()], "max_running": cfg["max_running"]} def cmd_repos(cfg: dict, args: list[str]) -> dict: _arity(args, 0, 0) return {"repos": sorted(cfg["repos"])} def cmd_status(cfg: dict, args: list[str]) -> dict: (name,) = _arity(args, 1, 1) return {"session": session_view(read_state(validate_name(name)))} def cmd_create(cfg: dict, args: list[str]) -> dict: title, repo, *rest = _arity(args, 2, 3) name, title = name_from_title(title) if repo not in cfg["repos"]: raise UserError(f"repo {repo!r} is not in the allowlist") base = validate_branch(rest[0]) if rest else None workspace = cfg["workspace_root"] / name with lock(): if state_path(name).exists() or workspace.exists(): raise UserError(f"session {name!r} already exists") if running_count() >= cfg["max_running"]: raise UserError(f"limit reached: {cfg['max_running']} sessions already running") workspace.parent.mkdir(parents=True, exist_ok=True) clone = ["git", "clone", "--quiet"] + (["--branch", base] if base else []) + ["--", cfg["repos"][repo], str(workspace)] try: _run(clone, timeout=300) _run(["git", "-C", str(workspace), "switch", "--quiet", "-c", f"session/{name}"]) except Exception: # Only ever removes the directory this call just created. shutil.rmtree(workspace, ignore_errors=True) raise trust_workspace(workspace) state = { "name": name, "title": title, "repo": repo, "base": base, "branch": f"session/{name}", "workspace": str(workspace), "uuid": str(uuid.uuid4()), "created_at": dt.datetime.now(dt.UTC).isoformat(timespec="seconds"), } write_state(state) systemctl("enable", "--now", UNIT.format(name)) return {"session": session_view(state, with_pane=False)} def cmd_start(cfg: dict, args: list[str]) -> dict: (name,) = _arity(args, 1, 1) validate_name(name) with lock(): state = read_state(name) if state.get("archived"): raise UserError(f"{name} is archived; unarchive it first") if unit_state(name)["active"] != "active" and running_count() >= cfg["max_running"]: raise UserError(f"limit reached: {cfg['max_running']} sessions already running") systemctl("enable", "--now", UNIT.format(name)) return {"session": session_view(state, with_pane=False)} def cmd_stop(cfg: dict, args: list[str]) -> dict: (name,) = _arity(args, 1, 1) state = read_state(validate_name(name)) systemctl("disable", "--now", UNIT.format(name)) return {"session": session_view(state, with_pane=False)} def cmd_archive(cfg: dict, args: list[str]) -> dict: """Stop the session and move it to the archive. Keeps its checkout and conversation.""" (name,) = _arity(args, 1, 1) with lock(): # so a concurrent `start` can't slip in between the stop and the flag state = read_state(validate_name(name)) systemctl("disable", "--now", UNIT.format(name)) state["archived"] = True write_state(state) return {"session": session_view(state, with_pane=False)} def cmd_unarchive(cfg: dict, args: list[str]) -> dict: """Back to the normal list, still stopped.""" (name,) = _arity(args, 1, 1) with lock(): state = read_state(validate_name(name)) state.pop("archived", None) write_state(state) return {"session": session_view(state, with_pane=False)} def cmd_health(cfg: dict, args: list[str]) -> dict: _arity(args, 0, 0) mem = {} for line in Path("/proc/meminfo").read_text().splitlines(): k, v = line.split(":", 1) if k in ("MemTotal", "MemAvailable"): mem[k] = int(v.split()[0]) // 1024 return { "host": socket.gethostname(), "running": running_count(), "max_running": cfg["max_running"], "load": round(os.getloadavg()[0], 2), "mem_total_mb": mem.get("MemTotal"), "mem_available_mb": mem.get("MemAvailable"), } def cmd_delete(cfg: dict, args: list[str]) -> dict: """Local only. Removes a stopped session's checkout. Refuses to lose work.""" force = "--force" in args names = [a for a in args if a not in ("--force", "--yes")] if "--yes" not in args or len(names) != 1: raise UserError("usage: sessions-ctl delete NAME --yes [--force]") state = read_state(validate_name(names[0])) if unit_state(state["name"])["active"] == "active": raise UserError("stop the session first") ws = Path(state["workspace"]) if ws.exists() and not force: dirty = _run(["git", "-C", str(ws), "status", "--porcelain"]).stdout.strip() unpushed = _run(["git", "-C", str(ws), "log", "--oneline", "--branches", "--not", "--remotes"]).stdout.strip() if dirty or unpushed: raise UserError("checkout has uncommitted or unpushed work; push it or pass --force") systemctl("disable", UNIT.format(state["name"]), check=False) if ws.exists(): shutil.rmtree(ws) untrust_workspace(ws) state_path(state["name"]).unlink() return {"deleted": state["name"]} def cmd_launch(cfg: dict, args: list[str]) -> dict: """ExecStart of claude-session@.service — not callable remotely.""" (name,) = _arity(args, 1, 1) state = read_state(validate_name(name)) ws = Path(state["workspace"]) if not ws.is_dir(): raise UserError(f"workspace {ws} is missing") trust_workspace(ws) # re-assert: cheap, and survives a reset ~/.claude.json sock = tmux_socket(name) cmd = shlex.join(claude_args(state, cfg["remote_control_prefix"])) _run(["tmux", "-L", sock, "new-session", "-d", "-s", name, "-x", "200", "-y", "50", "-c", str(ws), cmd]) pid = _run(["tmux", "-L", sock, "display-message", "-p", "#{pid}"]).stdout.strip() runtime = Path(_user_env()["XDG_RUNTIME_DIR"]) / "claude-session" runtime.mkdir(parents=True, exist_ok=True) (runtime / f"{name}.pid").write_text(pid + "\n") return {"launched": name, "tmux_pid": int(pid)} def cmd_refresh_access(cfg: dict, args: list[str]) -> dict: """Re-resolve ssh_access.allow_from_host and rewrite our authorized_keys line.""" _arity(args, 0, 0) access = cfg["ssh_access"] host, pubkey = access.get("allow_from_host"), access.get("public_key") if not host or not pubkey: raise UserError("config: ssh_access.allow_from_host and ssh_access.public_key are required") ips = resolve(host) if not ips: # Never write an empty from= (that would lock prod out) — keep the old line. raise UserError(f"could not resolve {host}; authorized_keys left unchanged") line = authorized_line(pubkey, ips, str(SELF_PATH)) old = AUTHORIZED_KEYS.read_text() if AUTHORIZED_KEYS.exists() else "" new = replace_marked_line(old, line) changed = new != old if changed: atomic_write(AUTHORIZED_KEYS, new, 0o600) return {"changed": changed, "from": ips} def cmd_keygen(cfg: dict, args: list[str]) -> dict: """Local only. Make the key prod uses and print its env block once. The pair is generated in RAM (XDG_RUNTIME_DIR). The public half goes into config.toml and authorized_keys; the private half is printed as one base64 line for the container's environment and then deleted, so it exists only where you paste it. """ if [a for a in args if a != "--rotate"]: raise UserError("usage: sessions-ctl keygen [--rotate]") if cfg["ssh_access"].get("public_key", "").startswith("ssh-") and "--rotate" not in args: raise UserError("a key is already configured; `keygen --rotate` replaces it " "(prod stops working until its environment is updated)") if not cfg["ssh_access"].get("allow_from_host"): raise UserError("config: set ssh_access.allow_from_host first") tmp = Path(tempfile.mkdtemp(dir=_user_env()["XDG_RUNTIME_DIR"], prefix="sessions-keygen-")) try: _run(["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-C", "sessions-web", "-f", str(tmp / "id")]) public = (tmp / "id.pub").read_text().strip() private_b64 = base64.b64encode((tmp / "id").read_bytes()).decode() finally: shutil.rmtree(tmp, ignore_errors=True) text = CONFIG_PATH.read_text() if CONFIG_PATH.exists() else "" atomic_write(CONFIG_PATH, set_toml_string(text, "ssh_access", "public_key", public), 0o600) access = cmd_refresh_access(load_config(), []) host_key = " ".join(Path(HOST_KEY_PATH).read_text().split()[:2]) env_block = "\n".join([ f"SESSIONS_DEV_HOST={cfg['ssh_access'].get('advertise_host') or public_address()}", f"SESSIONS_DEV_PORT={cfg['ssh_access'].get('port', 14922)}", f"SESSIONS_DEV_USER={getpass.getuser()}", f"SESSIONS_DEV_HOST_KEY={host_key}", f"SESSIONS_SSH_KEY_B64={private_b64}", ]) note = ("Paste these lines into the sessions app's environment on prod (panel -> app -> Environment).\n" "The private key exists nowhere else now. Clear this screen afterwards (`clear`, and your\n" "terminal's scrollback). The key only works from: " + ", ".join(access["from"])) return {"text": env_block, "note": note, "from": access["from"]} def set_toml_string(text: str, section: str, key: str, value: str) -> str: """Set `key = "value"` inside [section] of a simple TOML file, keeping the rest.""" if '"' in value or "\\" in value or "\n" in value: raise UserError("refusing to write an unusual value into config.toml") lines, out, in_section, done = text.splitlines(), [], False, False for line in lines: stripped = line.strip() if stripped.startswith("["): if in_section and not done: out.append(f'{key} = "{value}"') done = True in_section = stripped == f"[{section}]" elif in_section and re.match(rf"^{re.escape(key)}\s*=", stripped): if not done: out.append(f'{key} = "{value}"') done = True continue out.append(line) if not done: if not in_section: out += ["", f"[{section}]"] out.append(f'{key} = "{value}"') return "\n".join(out) + "\n" def public_address() -> str: """The source address this box uses to reach the internet (no packet is sent).""" with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: s.connect(("192.0.2.1", 9)) # TEST-NET-1; UDP connect only picks a route return s.getsockname()[0] # ---------------------------------------------------------------- helpers def resolve(host: str) -> list[str]: try: infos = socket.getaddrinfo(host, None, type=socket.SOCK_STREAM) except socket.gaierror: return [] return sorted({i[4][0] for i in infos}) def authorized_line(pubkey: str, ips: list[str], command: str) -> str: parts = pubkey.split() if len(parts) < 2 or not parts[0].startswith("ssh-") or not re.fullmatch(r"[A-Za-z0-9+/=]+", parts[1]): raise UserError("config: ssh_access.public_key is not an OpenSSH public key") for ip in ips: if not re.fullmatch(r"[0-9a-fA-F:.]+", ip): raise UserError(f"refusing odd address {ip!r}") return f'from="{",".join(ips)}",restrict,command="{command} --remote" {parts[0]} {parts[1]} {KEY_MARKER}' def replace_marked_line(text: str, line: str) -> str: """Replace the line tagged KEY_MARKER (or append one); leave every other line alone.""" kept = [l for l in text.splitlines() if not l.rstrip().endswith(" " + KEY_MARKER)] return "\n".join(kept + [line]) + "\n" def _arity(args: list[str], lo: int, hi: int) -> list[str]: if not lo <= len(args) <= hi: raise UserError("wrong number of arguments") return args def _run(cmd: list[str], timeout: int = 60) -> subprocess.CompletedProcess: r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout) if r.returncode != 0: raise RuntimeError(f"{cmd[0]} failed: {r.stderr.strip()[:500]}") return r VERBS = { "list": cmd_list, "repos": cmd_repos, "status": cmd_status, "create": cmd_create, "start": cmd_start, "stop": cmd_stop, "archive": cmd_archive, "unarchive": cmd_unarchive, "health": cmd_health, "delete": cmd_delete, "refresh-access": cmd_refresh_access, "keygen": cmd_keygen, "_launch": cmd_launch, } def parse_remote(original: str | None) -> list[str]: """Turn $SSH_ORIGINAL_COMMAND into argv, allowing only REMOTE_VERBS.""" if not original: raise UserError("interactive login is not allowed; send a command") try: argv = shlex.split(original) except ValueError: raise UserError("could not parse command") if not argv or argv[0] not in REMOTE_VERBS: raise UserError(f"verb not allowed; use one of: {', '.join(sorted(REMOTE_VERBS))}") return argv def log(msg: str) -> None: try: import syslog syslog.openlog("sessions-ctl") syslog.syslog(msg) except Exception: pass def main(argv: list[str]) -> int: remote = argv[:1] == ["--remote"] try: if remote: argv = parse_remote(os.environ.get("SSH_ORIGINAL_COMMAND")) log(f"remote from {os.environ.get('SSH_CLIENT', '?').split(' ')[0]}: {shlex.join(argv)}") if not argv or argv[0] not in VERBS: raise UserError(f"usage: sessions-ctl {{{'|'.join(v for v in VERBS if not v.startswith('_'))}}} …") result = VERBS[argv[0]](load_config(), argv[1:]) if "text" in result and not remote: print(result["text"]) # keygen: KEY=VALUE lines only, safe to paste as-is if result.get("note"): print(result["note"], file=sys.stderr) else: print(json.dumps({"ok": True, **result})) return 0 except UserError as e: print(json.dumps({"ok": False, "error": str(e)})) if remote: log(f"remote rejected: {e}") return 2 if "usage" in str(e) else 1 except Exception as e: # keep the one-JSON-object contract even on bugs log(f"error: {e!r}") print(json.dumps({"ok": False, "error": f"internal error: {e}"})) return 1 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))