On a guest's own computer, `claude` in a terminal now asks (arrow-key box, remembered per folder tree): ai-agent Claude — the hub's proxy pair, synced — or the machine's own login, synced later on demand. - worker/claude_launcher.py + the installer's shell hook (bash/zsh/fish): the picker, --ai-agent/--local/--choose, no question for -p / pipes / known --resume, --session-id up front so the start line links the app; ai-agent-worker sync|unsync|claude. - worker/claude-mod: a Claude Code mod — status line (synced · budget left), a toast with the link, /ai-agent [sync|unsync], and Continue on ai-agent Claude when the guest's own plan runs out (the launcher resumes it there). - hub: workers/terminal.py claims a session on its first proxied call (X-Claude-Code-Session-Id) or when /feed lists it as synced; refused for an id known elsewhere; Stop syncing keeps the copy, takes no more. The probe pushes the picker's figures (budget left, paused) to the computer. - portal: My computers → Terminal sessions (Sync / Stop syncing, Ask at start); the Terminal badge; continuing a local one confirms the move to the host's Claude and sends on a fresh context. Form choose-claude-at-terminal-start-sync-to-the-app_n789ku. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
366 lines
14 KiB
Python
366 lines
14 KiB
Python
"""
|
|
Terminal sessions — which of a computer's own ``claude`` sessions the hub may
|
|
mirror, and the choice its ``claude`` launcher remembers per folder.
|
|
|
|
A guest's computer is mirrored for what the guest chose to share, never more
|
|
(backend ``workers/guests.py``): the runs the hub started there, the terminal
|
|
sessions that ran on **ai-agent Claude** (the hub sees their session id on its
|
|
proxy, so the computer never has to say), and the ones the guest **synced**
|
|
afterwards — listed here, in the state dir:
|
|
|
|
terminal-synced.json {sid: {"at": iso, "cwd": "…"}} (0600)
|
|
claude-choice.json {remember: {folder: mode}, last: {folder: mode},
|
|
lastAny: mode} — mode "ai-agent" | "local"
|
|
terminal-sessions.json {sid: mode} which Claude each session ran on
|
|
terminal-status.json what the hub pushed: budget left, paused, its address
|
|
claude-launcher.off present ⇒ ``claude`` runs as it always did
|
|
|
|
``/feed`` carries the synced ids (``synced``); the hub takes them as the
|
|
guest's word for *their own* sessions — a session the hub places anywhere else
|
|
is still refused there. The hub's portal reaches the rest through:
|
|
|
|
GET /terminal/sessions recent sessions here: id, title, folder,
|
|
time, synced — read on demand, never kept
|
|
POST /terminal/sync {sid} sync one (the portal's *Sync*)
|
|
DELETE /terminal/sync/{sid} stop syncing it
|
|
PUT /terminal/launcher {on} the portal's *Choose at start* switch
|
|
PUT /terminal/status {status} the hub's figures for the picker and the
|
|
mod (budget left, paused…), pushed when
|
|
/health's ``terminal.statusHash`` differs
|
|
|
|
The launcher (``worker/claude_launcher.py``), the in-session mod's ``/ai-agent
|
|
sync`` and ``ai-agent-worker sync`` write the same files directly — same user,
|
|
no server needed. Stdlib only at import: the launcher imports this module
|
|
outside the sidecar.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import re
|
|
import time
|
|
|
|
SID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
|
|
MODES = ("ai-agent", "local")
|
|
# What the hub may push into terminal-status.json — nothing else is kept.
|
|
STATUS_KEYS = ("hubUrl", "ownerName", "budgetUsd", "leftUsd", "month", "paused",
|
|
"waiting", "computer")
|
|
# A session's title lives near its end (the latest ``ai-title`` row) and its
|
|
# folder near its start: read that much of each, not whole transcripts.
|
|
_HEAD = 64 * 1024
|
|
_TAIL = 256 * 1024
|
|
|
|
|
|
def state_dir() -> pathlib.Path:
|
|
# pairing.state_dir's twin, without its FastAPI import (the launcher).
|
|
return pathlib.Path(os.path.expanduser(os.environ.get(
|
|
"WORKER_STATE_DIR", "~/.config/ai-agent-worker")))
|
|
|
|
|
|
def _read_json(name: str) -> dict:
|
|
try:
|
|
d = json.loads((state_dir() / name).read_text())
|
|
return d if isinstance(d, dict) else {}
|
|
except (OSError, ValueError):
|
|
return {}
|
|
|
|
|
|
def _write_json(name: str, d: dict) -> None:
|
|
p = state_dir() / name
|
|
p.parent.mkdir(parents=True, exist_ok=True)
|
|
tmp = p.with_name(f"{p.name}.{os.getpid()}.tmp")
|
|
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
with os.fdopen(fd, "w") as f:
|
|
json.dump(d, f, indent=1, sort_keys=True)
|
|
os.replace(tmp, p)
|
|
|
|
|
|
# ── synced sessions ──────────────────────────────────────────────────────────
|
|
def synced() -> dict[str, dict]:
|
|
return {k: v for k, v in _read_json("terminal-synced.json").items()
|
|
if SID_RE.match(k) and isinstance(v, dict)}
|
|
|
|
|
|
def sync(sid: str, cwd: str | None = None) -> bool:
|
|
"""Share session ``sid`` with the hub; False for a malformed id."""
|
|
sid = (sid or "").strip().lower()
|
|
if not SID_RE.match(sid):
|
|
return False
|
|
d = synced()
|
|
d.setdefault(sid, {"at": datetime.datetime.now(datetime.timezone.utc)
|
|
.strftime("%Y-%m-%dT%H:%M:%SZ"), **({"cwd": cwd} if cwd else {})})
|
|
_write_json("terminal-synced.json", d)
|
|
return True
|
|
|
|
|
|
def unsync(sid: str) -> bool:
|
|
d = synced()
|
|
if d.pop((sid or "").strip().lower(), None) is None:
|
|
return False
|
|
_write_json("terminal-synced.json", d)
|
|
return True
|
|
|
|
|
|
# ── the launcher's remembered choice ─────────────────────────────────────────
|
|
def launcher_on() -> bool:
|
|
return not (state_dir() / "claude-launcher.off").exists()
|
|
|
|
|
|
def set_launcher(on: bool) -> None:
|
|
p = state_dir() / "claude-launcher.off"
|
|
if on:
|
|
p.unlink(missing_ok=True)
|
|
else:
|
|
p.parent.mkdir(parents=True, exist_ok=True)
|
|
p.write_text("off\n")
|
|
|
|
|
|
def _choice_file() -> dict:
|
|
d = _read_json("claude-choice.json")
|
|
return {"remember": {k: v for k, v in (d.get("remember") or {}).items() if v in MODES},
|
|
"last": {k: v for k, v in (d.get("last") or {}).items() if v in MODES},
|
|
"lastAny": d.get("lastAny") if d.get("lastAny") in MODES else None}
|
|
|
|
|
|
def choices() -> dict[str, str]:
|
|
"""The folders whose choice is remembered (no question there)."""
|
|
return _choice_file()["remember"]
|
|
|
|
|
|
def remembered(cwd: str) -> tuple[str, str] | None:
|
|
"""``(mode, folder)`` remembered for ``cwd`` or the nearest folder above
|
|
it — a choice covers its subfolders."""
|
|
d = choices()
|
|
p = pathlib.PurePath(os.path.abspath(cwd))
|
|
for folder in (p, *p.parents):
|
|
mode = d.get(str(folder))
|
|
if mode:
|
|
return mode, str(folder)
|
|
return None
|
|
|
|
|
|
def preselect(cwd: str) -> str:
|
|
"""What the picker starts on: the last pick in this folder, else the last
|
|
pick anywhere, else ai-agent Claude."""
|
|
d = _choice_file()
|
|
return d["last"].get(os.path.abspath(cwd)) or d["lastAny"] or "ai-agent"
|
|
|
|
|
|
def note(cwd: str, mode: str, remember: bool = False) -> None:
|
|
"""Record a pick (it pre-selects next time); ``remember`` skips the
|
|
question in this folder and its subfolders from now on."""
|
|
if mode not in MODES:
|
|
raise ValueError(mode)
|
|
d = _choice_file()
|
|
folder = os.path.abspath(cwd)
|
|
d["last"][folder] = mode
|
|
if len(d["last"]) > 200: # the oldest picks go first (dicts keep order)
|
|
d["last"] = dict(list(d["last"].items())[-200:])
|
|
d["last"][folder] = d["last"].pop(folder)
|
|
d["lastAny"] = mode
|
|
if remember:
|
|
d["remember"][folder] = mode
|
|
_write_json("claude-choice.json", d)
|
|
|
|
|
|
def remember(cwd: str, mode: str) -> None:
|
|
note(cwd, mode, remember=True)
|
|
|
|
|
|
def forget(cwd: str | None = None) -> list[str]:
|
|
"""Drop the remembered choice for ``cwd`` and the folders under it (all
|
|
of them when None); returns the folders dropped."""
|
|
d = _choice_file()
|
|
if cwd is None:
|
|
gone = list(d["remember"])
|
|
else:
|
|
root = os.path.abspath(cwd)
|
|
gone = [k for k in d["remember"]
|
|
if k == root or k.startswith(root.rstrip("/") + "/")]
|
|
for k in gone:
|
|
d["remember"].pop(k)
|
|
_write_json("claude-choice.json", d)
|
|
return gone
|
|
|
|
|
|
# ── which Claude each session ran on ─────────────────────────────────────────
|
|
# The launcher knows a new session's id (it passes --session-id) and the mod
|
|
# learns a resumed one's: a later ``claude --resume <id>`` runs where it ran.
|
|
def session_mode(sid: str) -> str | None:
|
|
m = _read_json("terminal-sessions.json").get((sid or "").lower())
|
|
return m if m in MODES else None
|
|
|
|
|
|
def note_session(sid: str, mode: str) -> None:
|
|
sid = (sid or "").strip().lower()
|
|
if not SID_RE.match(sid) or mode not in MODES:
|
|
return
|
|
d = {k: v for k, v in _read_json("terminal-sessions.json").items() if v in MODES}
|
|
d.pop(sid, None)
|
|
d[sid] = mode
|
|
_write_json("terminal-sessions.json", dict(list(d.items())[-500:]))
|
|
|
|
|
|
# ── what the hub says (pushed on its probe) ──────────────────────────────────
|
|
def hub_status() -> dict:
|
|
"""``terminal-status.json``: the guest's budget left, whether the
|
|
computer is paused, the hub's address and owner — what the picker and the
|
|
mod's status line show. {} until the hub pushed it."""
|
|
return _read_json("terminal-status.json")
|
|
|
|
|
|
def set_hub_status(d: dict) -> None:
|
|
_write_json("terminal-status.json", d)
|
|
|
|
|
|
# ── the sessions on this computer ────────────────────────────────────────────
|
|
def _rows(chunk: bytes):
|
|
for line in chunk.splitlines():
|
|
try:
|
|
d = json.loads(line)
|
|
except ValueError:
|
|
continue # a row cut by the head/tail window
|
|
if isinstance(d, dict):
|
|
yield d
|
|
|
|
|
|
def _first_prompt(d: dict) -> str | None:
|
|
if d.get("type") != "user" or d.get("isMeta") or d.get("isSidechain"):
|
|
return None
|
|
content = (d.get("message") or {}).get("content")
|
|
if isinstance(content, list):
|
|
content = " ".join(b.get("text") or "" for b in content
|
|
if isinstance(b, dict) and b.get("type") == "text")
|
|
text = " ".join(str(content or "").split())
|
|
# Slash-command echoes and local-command output aren't what was asked.
|
|
if not text or text.startswith("<"):
|
|
return None
|
|
return text
|
|
|
|
|
|
def describe(path: pathlib.Path) -> dict | None:
|
|
"""One transcript as the portal lists it, from its head and tail only."""
|
|
try:
|
|
st = path.stat()
|
|
with open(path, "rb") as f:
|
|
head = f.read(_HEAD)
|
|
f.seek(max(0, st.st_size - _TAIL))
|
|
tail = f.read(_TAIL) if st.st_size > _HEAD else b""
|
|
except OSError:
|
|
return None
|
|
cwd = prompt = title = None
|
|
for d in (*_rows(head), *_rows(tail)):
|
|
cwd = cwd or d.get("cwd")
|
|
prompt = prompt or _first_prompt(d)
|
|
# the latest title wins, a name the user gave over the generated one
|
|
if d.get("type") in ("ai-title", "custom-title"):
|
|
title = d.get("customTitle") or d.get("aiTitle") or title
|
|
if not (prompt or title):
|
|
return None # nothing was ever asked: a session opened and closed
|
|
return {"id": path.stem, "project": path.parent.name,
|
|
"title": (title or prompt or "")[:120],
|
|
"prompt": (prompt or "")[:240], "cwd": cwd,
|
|
"mtime": st.st_mtime, "size": st.st_size}
|
|
|
|
|
|
def sessions(projects: pathlib.Path, limit: int = 40,
|
|
days: float = 30) -> list[dict]:
|
|
"""The computer's recent top-level sessions, newest first, each with
|
|
``synced``. Subagent transcripts (``<sid>/subagents/``) aren't listed —
|
|
they travel with their session."""
|
|
since = time.time() - days * 86400
|
|
found: list[tuple[float, pathlib.Path]] = []
|
|
try:
|
|
for proj in os.scandir(projects):
|
|
if not proj.is_dir(follow_symlinks=False):
|
|
continue
|
|
for e in os.scandir(proj.path):
|
|
if not e.name.endswith(".jsonl") or not SID_RE.match(e.name[:-6]):
|
|
continue
|
|
try:
|
|
m = e.stat(follow_symlinks=False).st_mtime
|
|
except OSError:
|
|
continue
|
|
if m >= since and e.is_file(follow_symlinks=False):
|
|
found.append((m, pathlib.Path(e.path)))
|
|
except OSError:
|
|
return []
|
|
shared = synced()
|
|
out: list[dict] = []
|
|
for _, p in sorted(found, reverse=True):
|
|
row = describe(p)
|
|
if row:
|
|
out.append({**row, "synced": row["id"] in shared})
|
|
if len(out) >= limit:
|
|
break
|
|
return out
|
|
|
|
|
|
def status_hash(d: dict) -> str:
|
|
"""The hub computes the same from what it would push, and pushes when
|
|
the two differ (backend workers/terminal.py)."""
|
|
import hashlib
|
|
raw = json.dumps(d, sort_keys=True, separators=(",", ":"))
|
|
return hashlib.sha256(raw.encode()).hexdigest()[:16]
|
|
|
|
|
|
def public() -> dict:
|
|
"""What ``/health`` says of it (workers only)."""
|
|
st = hub_status()
|
|
return {"launcher": launcher_on(), "synced": len(synced()),
|
|
"statusHash": status_hash(st) if st else None}
|
|
|
|
|
|
def make_router(auth, projects):
|
|
"""The portal's side (bearer: the hub). ``projects()`` is the default
|
|
account's ``projects/`` dir."""
|
|
from fastapi import APIRouter, Body, Header, HTTPException, Query
|
|
|
|
from config import IS_WORKER
|
|
|
|
router = APIRouter()
|
|
|
|
def _guard(authorization):
|
|
auth(authorization)
|
|
if not IS_WORKER:
|
|
raise HTTPException(409, "the lab's sessions are all the hub's already")
|
|
|
|
@router.get("/terminal/sessions")
|
|
def get_sessions(limit: int = Query(40, ge=1, le=200),
|
|
authorization: str | None = Header(default=None)) -> dict:
|
|
_guard(authorization)
|
|
return {"sessions": sessions(projects(), limit), "launcher": launcher_on()}
|
|
|
|
@router.post("/terminal/sync")
|
|
def post_sync(sid: str = Body(..., embed=True),
|
|
authorization: str | None = Header(default=None)) -> dict:
|
|
_guard(authorization)
|
|
if not sync(sid):
|
|
raise HTTPException(400, "not a session id")
|
|
return {"ok": True, "synced": len(synced())}
|
|
|
|
@router.delete("/terminal/sync/{sid}")
|
|
def delete_sync(sid: str, authorization: str | None = Header(default=None)) -> dict:
|
|
_guard(authorization)
|
|
return {"ok": unsync(sid)}
|
|
|
|
@router.put("/terminal/status")
|
|
def put_status(status: dict = Body(..., embed=True),
|
|
authorization: str | None = Header(default=None)) -> dict:
|
|
_guard(authorization)
|
|
keep = {k: status[k] for k in STATUS_KEYS if k in status}
|
|
set_hub_status(keep)
|
|
return {"statusHash": status_hash(keep)}
|
|
|
|
@router.put("/terminal/launcher")
|
|
def put_launcher(on: bool = Body(..., embed=True),
|
|
authorization: str | None = Header(default=None)) -> dict:
|
|
_guard(authorization)
|
|
set_launcher(on)
|
|
return {"launcher": launcher_on()}
|
|
|
|
return router
|