#!/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 always one JSON object on stdout. Exit codes: 0 ok, 1 error, 2 usage. Standard library only, so it runs with the system python3. """ from __future__ import annotations import datetime as dt 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" 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}$") BRANCH_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._/-]{0,99}$") RC_URL_RE = re.compile(r"https://claude\.ai/code/session_[A-Za-z0-9]+") TRUST_PROMPT = "Yes, I trust this folder" REMOTE_VERBS = {"list", "repos", "status", "create", "start", "stop", "health"} DEFAULTS = { "workspace_root": "~/sessions", "max_running": 2, "remote_control_prefix": socket.gethostname(), "repos": {}, "ssh_access": {}, } class UserError(Exception): """A problem the caller can fix (bad name, unknown repo, limit reached…).""" # ---------------------------------------------------------------- config/state def load_config(path: Path = CONFIG_PATH) -> dict: 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.match(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.match(name): raise UserError("name must be 1-32 chars of a-z, 0-9 and '-', starting with a letter or digit") return name def validate_branch(branch: str) -> str: if not BRANCH_RE.match(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.""" rc_name = f"{prefix}-{state['name']}" args = ["claude", "--remote-control", rc_name, "--name", state["name"]] 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"], "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"): state["remote_control_url"] = view["remote_control_url"] = m.group(0) write_state(state) if TRUST_PROMPT in pane: view["needs_attention"] = "stuck on the folder-trust prompt; 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: name, repo, *rest = _arity(args, 2, 3) validate_name(name) 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, "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) state = read_state(validate_name(name)) with lock(): 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_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} # ---------------------------------------------------------------- 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, "health": cmd_health, "delete": cmd_delete, "refresh-access": cmd_refresh_access, "_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:]) 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:]))