Monitor ran shell commands the guard never saw; the owner CLI, docker and ssh rules fell to ordinary spellings (the CLI now refuses under AIA_GUEST); a guard exception let the call through; chat-level runs still had the owner's gitea.lab and gh credential helpers. Scoped lab runs: --setting-sources user, --strict-mcp-config, hooks under python -I, the project CLAUDE.md appended as text, scope.noBash. 3d-render uploads carry data: URIs only; a guest's video URL resolves to public addresses through a vetting proxy; git on a guest repo runs with fsmonitor, hooks, filters and textconv out of reach; the ship broker deploys a checked copy; tokens leave argv. Co-Authored-By: Claude <noreply@anthropic.com>
636 lines
25 KiB
Python
636 lines
25 KiB
Python
#!/usr/bin/env python3
|
||
"""
|
||
``claude`` on a guest's computer — pick which Claude runs before it starts.
|
||
|
||
The worker installer (link mode: a guest's own computer) wraps the shell's
|
||
``claude`` in this — a function in ~/.bashrc / ~/.zshrc (fish: conf.d) that
|
||
calls ``ai-agent-claude``. Typed in a terminal, it asks:
|
||
|
||
╭─ Which Claude? · fedora ──────────────────────────────────────────╮
|
||
│ ❯ ai-agent Claude Gabriel's Claude · synced to the app · $8.20 left │
|
||
│ My own Claude your login · stays on this computer │
|
||
│ │
|
||
│ [ ] Remember for ~/code/app and its subfolders │
|
||
╰─ ↑↓ choose · space remember · enter start · esc quit ─────────────╯
|
||
|
||
**ai-agent Claude** runs through the hub's Claude proxy — the pair the hub's
|
||
own runs here use (``claude-proxy.json``) — so it bills the owner's plan within
|
||
the guest's limits, and the hub mirrors the session: it sees its id on the
|
||
proxy (backend ``workers/terminal.py``). **My own Claude** is the machine's
|
||
own login, untouched; such a session can be synced later (the mod's
|
||
``/ai-agent sync``, ``ai-agent-worker sync``, or *Sync* in the portal).
|
||
|
||
It starts on the last pick in this folder, else the last pick anywhere, else
|
||
ai-agent Claude. No question when:
|
||
|
||
* the launcher is off (``claude-launcher.off``, the portal's switch), the
|
||
computer has no proxy config, or a ``claude`` subcommand / --help /
|
||
--version runs — the real ``claude``, as it always was;
|
||
* ``--ai-agent`` / ``--local`` say which (taken off the command line;
|
||
``--choose`` asks even where a choice is remembered);
|
||
* the folder, or one above it, has a remembered choice;
|
||
* ``--resume <id>`` names a session whose Claude is known (it runs where it
|
||
ran), or nobody is there to answer (``-p``, a pipe): local.
|
||
|
||
A new session gets its id up front (``--session-id``), so the line printed
|
||
before Claude starts already links it in the app. With the mod loaded
|
||
(``worker/claude-mod``, Claude Code ≥ MOD_MIN) the launcher stays the parent
|
||
of ``claude``: the mod's *Continue on ai-agent Claude* — offered when the
|
||
guest's own plan runs out — writes ``relaunch.json`` and exits, and the
|
||
launcher resumes the same session on ai-agent Claude.
|
||
|
||
claude_launcher.py [claude args…] the launcher (``ai-agent-claude``)
|
||
ai-agent-worker sync [<id>|--last] share a session (a list without)
|
||
ai-agent-worker unsync <id> stop syncing it (the app keeps it)
|
||
ai-agent-worker claude [list|reset [dir]|off|on]
|
||
|
||
(``ai-agent-worker`` runs those as ``AI_AGENT_LAUNCHER_CMD=<cmd>
|
||
claude_launcher.py …`` — the launcher's own argv is claude's.)
|
||
|
||
Stdlib only.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import pathlib
|
||
import re
|
||
import select
|
||
import shutil
|
||
import signal
|
||
import subprocess
|
||
import sys
|
||
import time
|
||
import uuid
|
||
|
||
ROOT = pathlib.Path(__file__).resolve().parent.parent
|
||
sys.path.insert(0, str(ROOT / "sidecar"))
|
||
import proxy_pair # noqa: E402
|
||
import terminal # noqa: E402
|
||
|
||
MOD_DIR = ROOT / "worker" / "claude-mod"
|
||
# The first Claude Code whose mods (function-hook plugins) we tested.
|
||
MOD_MIN = (2, 1, 312)
|
||
# Any other way to authenticate would win over the hub's pair (claude_proxy.py).
|
||
_STRIP = ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN",
|
||
"ANTHROPIC_BASE_URL")
|
||
SUBCOMMANDS = {"mcp", "config", "update", "upgrade", "doctor", "install",
|
||
"migrate-installer", "setup-token", "plugin", "plugins", "auth",
|
||
"agents", "login", "logout"}
|
||
PASSTHROUGH_FLAGS = {"-h", "--help", "-v", "--version"}
|
||
OUR_FLAGS = {"--ai-agent": "ai-agent", "--local": "local", "--choose": "ask"}
|
||
RELAUNCH_MAX_AGE_S = 120
|
||
|
||
|
||
# ── where things are ─────────────────────────────────────────────────────────
|
||
def config_dir() -> pathlib.Path:
|
||
return pathlib.Path(os.path.expanduser(os.environ.get("CLAUDE_CONFIG_DIR") or "~/.claude"))
|
||
|
||
|
||
def projects_dir() -> pathlib.Path:
|
||
return config_dir() / "projects"
|
||
|
||
|
||
def real_claude() -> str | None:
|
||
pinned = os.environ.get("AI_AGENT_CLAUDE_BIN")
|
||
if pinned and os.access(pinned, os.X_OK):
|
||
return pinned
|
||
return shutil.which("claude")
|
||
|
||
|
||
def proxy_config() -> dict:
|
||
try:
|
||
cfg = json.loads((terminal.state_dir() / "claude-proxy.json").read_text())
|
||
except (OSError, ValueError):
|
||
return {}
|
||
if not isinstance(cfg, dict) or not cfg.get("url") or not cfg.get("token"):
|
||
return {}
|
||
account = cfg.get("default") or next(iter(cfg.get("accounts") or []), None)
|
||
return {**cfg, "account": account} if account else {}
|
||
|
||
|
||
def hub_url(cfg: dict, status: dict) -> str:
|
||
url = status.get("hubUrl") or re.sub(r"/proxy/claude/?$", "", cfg.get("url") or "")
|
||
return url.rstrip("/")
|
||
|
||
|
||
def conversation_url(hub: str, cwd: str, sid: str) -> str:
|
||
"""The app's page for session ``sid``. The hub resolves a bare session id
|
||
to the conversation's own (opaque) id — the path a transcript sits at never
|
||
goes into a link. ``cwd`` is kept for the callers' sake."""
|
||
return f"{hub}/conversation/{sid}" if hub else ""
|
||
|
||
|
||
def claude_version(binary: str) -> tuple[int, ...] | None:
|
||
"""From the native installer's path (``…/versions/2.1.312``), else
|
||
``claude --version``, cached per binary."""
|
||
real = os.path.realpath(binary)
|
||
m = re.search(r"(\d+)\.(\d+)\.(\d+)", os.path.basename(real))
|
||
if m:
|
||
return tuple(int(x) for x in m.groups())
|
||
cache = terminal.state_dir() / "claude-version.json"
|
||
try:
|
||
key = f"{real}:{os.stat(real).st_mtime}"
|
||
except OSError:
|
||
return None
|
||
try:
|
||
c = json.loads(cache.read_text())
|
||
if c.get("key") == key:
|
||
return tuple(c["version"])
|
||
except (OSError, ValueError, KeyError, TypeError):
|
||
pass
|
||
try:
|
||
out = subprocess.run([binary, "--version"], capture_output=True, text=True,
|
||
timeout=10).stdout
|
||
except (OSError, subprocess.SubprocessError):
|
||
return None
|
||
m = re.search(r"(\d+)\.(\d+)\.(\d+)", out)
|
||
if not m:
|
||
return None
|
||
v = tuple(int(x) for x in m.groups())
|
||
try:
|
||
cache.write_text(json.dumps({"key": key, "version": v}))
|
||
except OSError:
|
||
pass
|
||
return v
|
||
|
||
|
||
def local_signed_in() -> bool:
|
||
"""Does this machine hold a Claude login of its own? (A hint for the
|
||
picker only — ``claude`` itself asks to /login when it doesn't.)"""
|
||
if any(os.environ.get(k) for k in ("ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN")):
|
||
return True
|
||
if (config_dir() / ".credentials.json").is_file():
|
||
return True
|
||
if sys.platform == "darwin" and shutil.which("security"):
|
||
try:
|
||
return subprocess.run(["security", "find-generic-password", "-s",
|
||
"Claude Code-credentials"], capture_output=True,
|
||
timeout=2).returncode == 0
|
||
except (OSError, subprocess.SubprocessError):
|
||
return True
|
||
return False
|
||
|
||
|
||
# ── the command line ─────────────────────────────────────────────────────────
|
||
def parse(argv: list[str]) -> dict:
|
||
want = None
|
||
rest: list[str] = []
|
||
for a in argv:
|
||
if a in OUR_FLAGS:
|
||
want = OUR_FLAGS[a]
|
||
else:
|
||
rest.append(a)
|
||
resume = None
|
||
for i, a in enumerate(rest):
|
||
if a in ("-r", "--resume") and i + 1 < len(rest) and not rest[i + 1].startswith("-"):
|
||
resume = rest[i + 1]
|
||
elif a.startswith("--resume="):
|
||
resume = a.split("=", 1)[1]
|
||
return {
|
||
"want": want, "args": rest,
|
||
"passthrough": bool(rest and rest[0] in SUBCOMMANDS)
|
||
or any(a in PASSTHROUGH_FLAGS for a in rest),
|
||
"print": any(a in ("-p", "--print") for a in rest),
|
||
"resume": resume.lower() if resume and terminal.SID_RE.match(resume.lower()) else None,
|
||
"continues": any(a in ("-r", "--resume", "-c", "--continue") or a.startswith("--resume=")
|
||
for a in rest),
|
||
"sessionId": any(a == "--session-id" or a.startswith("--session-id=") for a in rest),
|
||
}
|
||
|
||
|
||
# ── the picker ───────────────────────────────────────────────────────────────
|
||
DIM, BOLD, CYAN, GREEN, RESET = "\x1b[2m", "\x1b[1m", "\x1b[36m", "\x1b[32m", "\x1b[0m"
|
||
_ANSI = re.compile(r"\x1b\[[0-9;]*m")
|
||
|
||
|
||
def _vis(s: str) -> int:
|
||
return len(_ANSI.sub("", s))
|
||
|
||
|
||
def _fit(s: str, width: int) -> str:
|
||
"""``s`` cut (ANSI-aware) to ``width`` visible columns, padded to it."""
|
||
limit = width if _vis(s) <= width else width - 1
|
||
out, n, i, cut = [], 0, 0, False
|
||
while i < len(s):
|
||
m = _ANSI.match(s, i)
|
||
if m:
|
||
out.append(m.group())
|
||
i = m.end()
|
||
continue
|
||
if n < limit:
|
||
out.append(s[i])
|
||
n += 1
|
||
else:
|
||
cut = True
|
||
i += 1
|
||
if cut:
|
||
out.append("…")
|
||
n += 1
|
||
return "".join(out) + RESET + " " * max(0, width - n)
|
||
|
||
|
||
def _home(p: str) -> str:
|
||
h = os.path.expanduser("~")
|
||
return "~" + p[len(h):] if p == h or p.startswith(h + "/") else p
|
||
|
||
|
||
def options(status: dict, cfg: dict) -> list[dict]:
|
||
owner = status.get("ownerName") or "the hub owner"
|
||
left = status.get("leftUsd")
|
||
hub_note, why = f"{owner}'s Claude · synced to the app", None
|
||
if isinstance(left, (int, float)):
|
||
hub_note += f" · ${max(0.0, left):.2f} left"
|
||
if status.get("paused"):
|
||
why = "paused on this computer"
|
||
elif isinstance(left, (int, float)) and left <= 0:
|
||
why = "this month's budget is spent"
|
||
elif status.get("waiting") == "plan":
|
||
why = f"{owner}'s plan is at its limit — try later"
|
||
mine = "your login · stays on this computer"
|
||
if not local_signed_in():
|
||
mine = "not signed in on this computer — it will ask you to /login"
|
||
return [{"mode": "ai-agent", "label": "ai-agent Claude", "note": why or hub_note,
|
||
"off": bool(why)},
|
||
{"mode": "local", "label": "My own Claude", "note": mine, "off": False}]
|
||
|
||
|
||
def render(opts: list[dict], sel: int, remember: bool, cwd: str, title: str,
|
||
width: int) -> list[str]:
|
||
inner = width - 4
|
||
lw = max(_vis(o["label"]) for o in opts) + 3
|
||
top = f"─ {BOLD}Which Claude?{RESET} · {title} "
|
||
lines = [f"╭{top}" + "─" * max(0, width - 2 - _vis(top)) + "╮"]
|
||
for i, o in enumerate(opts):
|
||
mark = f"{CYAN}❯{RESET}" if i == sel else " "
|
||
label = f"{BOLD}{o['label']}{RESET}" if i == sel else o["label"]
|
||
if o["off"]:
|
||
label, note = f"{DIM}{o['label']}{RESET}", f"{DIM}{o['note']}{RESET}"
|
||
else:
|
||
note = f"{DIM}{o['note']}{RESET}"
|
||
cell = f"{mark} {label}" + " " * (lw - _vis(o["label"])) + note
|
||
lines.append(f"│ {_fit(cell, inner)} │")
|
||
lines.append(f"│ {' ' * inner} │")
|
||
box = f"{GREEN}[x]{RESET}" if remember else "[ ]"
|
||
lines.append(f"│ {_fit(f' {box} Remember for {_home(cwd)} and its subfolders', inner)} │")
|
||
foot = f"─ {DIM}↑↓ choose · space remember · enter start · esc quit{RESET} "
|
||
lines.append(f"╰{foot}" + "─" * max(0, width - 2 - _vis(foot)) + "╯")
|
||
return lines
|
||
|
||
|
||
def _read_key(fd: int) -> str:
|
||
ch = os.read(fd, 1)
|
||
if ch == b"\x1b":
|
||
r, _, _ = select.select([fd], [], [], 0.05)
|
||
if r:
|
||
ch += os.read(fd, 8)
|
||
return ch.decode(errors="ignore")
|
||
|
||
|
||
def pick(opts: list[dict], start: str, cwd: str, title: str) -> tuple[str, bool] | None:
|
||
"""The arrow-key box on the terminal; None when the guest quits."""
|
||
import termios
|
||
import tty
|
||
try:
|
||
tty_fd = os.open("/dev/tty", os.O_RDWR)
|
||
except OSError:
|
||
return None
|
||
out = os.fdopen(tty_fd, "w", closefd=False)
|
||
width = max(44, min(shutil.get_terminal_size((80, 24)).columns - 1, 84))
|
||
sel = next((i for i, o in enumerate(opts) if o["mode"] == start and not o["off"]),
|
||
next(i for i, o in enumerate(opts) if not o["off"]))
|
||
remember, drawn = False, 0
|
||
old = termios.tcgetattr(tty_fd)
|
||
try:
|
||
tty.setcbreak(tty_fd)
|
||
out.write("\x1b[?25l")
|
||
while True:
|
||
lines = render(opts, sel, remember, cwd, title, width)
|
||
if drawn:
|
||
out.write(f"\x1b[{drawn}F")
|
||
out.write("".join(f"\x1b[2K{line}\n" for line in lines))
|
||
out.flush()
|
||
drawn = len(lines)
|
||
k = _read_key(tty_fd)
|
||
if k in ("\x1b[A", "k", "\x1b[D"):
|
||
sel = _step(opts, sel, -1)
|
||
elif k in ("\x1b[B", "j", "\x1b[C", "\t"):
|
||
sel = _step(opts, sel, 1)
|
||
elif k in ("1", "2") and not opts[int(k) - 1]["off"]:
|
||
sel = int(k) - 1
|
||
elif k == " ":
|
||
remember = not remember
|
||
elif k in ("\r", "\n"):
|
||
return opts[sel]["mode"], remember
|
||
elif k in ("\x1b", "q", "\x03", "\x04"):
|
||
return None
|
||
finally:
|
||
termios.tcsetattr(tty_fd, termios.TCSADRAIN, old)
|
||
if drawn:
|
||
out.write(f"\x1b[{drawn}F" + "\x1b[2K\n" * drawn + f"\x1b[{drawn}F")
|
||
out.write("\x1b[?25h")
|
||
out.flush()
|
||
os.close(tty_fd)
|
||
|
||
|
||
def _step(opts: list[dict], sel: int, d: int) -> int:
|
||
for _ in opts:
|
||
sel = (sel + d) % len(opts)
|
||
if not opts[sel]["off"]:
|
||
break
|
||
return sel
|
||
|
||
|
||
# ── running it ───────────────────────────────────────────────────────────────
|
||
def settings_env_conflicts() -> bool:
|
||
"""Does ``~/.claude/settings.json``'s env set a key of the pair? It
|
||
outranks the process environment (claude_proxy.with_settings_env)."""
|
||
try:
|
||
env = json.loads((config_dir() / "settings.json").read_text()).get("env") or {}
|
||
except (OSError, ValueError, AttributeError):
|
||
return False
|
||
return any(k in env for k in _STRIP)
|
||
|
||
|
||
def pair_settings(pair: dict) -> str:
|
||
"""The ``--settings`` value carrying the pair: a 0600 file in the
|
||
worker's state dir, so the hub's token isn't on claude's command line for
|
||
every process on this machine to list. (One file, rewritten each start —
|
||
the token is already at rest next to it.) The JSON itself only when the
|
||
file can't be written."""
|
||
body = json.dumps({"env": pair})
|
||
path = terminal.state_dir() / "claude-pair.settings.json"
|
||
try:
|
||
path.parent.mkdir(parents=True, exist_ok=True)
|
||
tmp = path.with_name(f"{path.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:
|
||
f.write(body)
|
||
os.chmod(tmp, 0o600)
|
||
os.replace(tmp, path)
|
||
return str(path)
|
||
except OSError:
|
||
return body
|
||
|
||
|
||
def own_login(args: list[str], env: dict, cfg: dict, cwd: str) -> list[str]:
|
||
"""*My own Claude*: none of the hub's pair, which a settings file (it
|
||
outranks the environment) or the shell may carry — or "my own" would
|
||
bill the host through the proxy (sidecar/proxy_pair.py). ``env`` is
|
||
stripped in place; the files' copy is unset in ``--settings``."""
|
||
hosts = proxy_pair.hub_hosts(cfg.get("url"), hub_url(cfg, terminal.hub_status()))
|
||
hits = proxy_pair.find(config_dir(), cwd, hosts, {cfg.get("token") or ""}, env)
|
||
proxy_pair.strip_env(env, hits)
|
||
out = proxy_pair.with_env(args, proxy_pair.neutraliser(hits))
|
||
if out is None:
|
||
say("your --settings keeps the ai-agent proxy's ANTHROPIC_BASE_URL — this "
|
||
"session may bill ai-agent Claude, not yours")
|
||
return args
|
||
for h in hits:
|
||
if h["source"] in ("user", "project"):
|
||
say(f"{h['path']} sends Claude to ai-agent's proxy "
|
||
f"({', '.join(h['keys'])}) — ignored for your own Claude")
|
||
elif h["source"] == "managed":
|
||
say(f"{h['path']} (managed settings) sends Claude to ai-agent's proxy — "
|
||
"it can't be overridden, so this session bills ai-agent Claude")
|
||
return out
|
||
|
||
|
||
def build(mode: str, p: dict, cfg: dict, cwd: str, mod: bool) -> tuple[list[str], dict, str | None]:
|
||
"""``(args, env, new session id)`` for ``claude`` on ``mode``."""
|
||
args = list(p["args"])
|
||
env = dict(os.environ)
|
||
# What the mod reads (worker/claude-mod): which Claude, where the state
|
||
# is, how to run this file's sync/unsync/note, the app's address.
|
||
env.update({"AI_AGENT_CLAUDE_MODE": mode,
|
||
"AI_AGENT_WORKER_STATE": str(terminal.state_dir()),
|
||
"AI_AGENT_LAUNCHER_PY": sys.executable,
|
||
"AI_AGENT_LAUNCHER": str(pathlib.Path(__file__).resolve()),
|
||
"AI_AGENT_HUB_URL": hub_url(cfg, terminal.hub_status())})
|
||
if mode == "ai-agent":
|
||
for k in _STRIP:
|
||
env.pop(k, None)
|
||
pair = {"ANTHROPIC_BASE_URL": f"{cfg['url'].rstrip('/')}/{cfg['account']}",
|
||
"CLAUDE_CODE_OAUTH_TOKEN": cfg["token"]}
|
||
env.update(pair)
|
||
if settings_env_conflicts() and not any(a.startswith("--settings") for a in args):
|
||
args = ["--settings", pair_settings(pair), *args]
|
||
else:
|
||
args = own_login(args, env, cfg, cwd)
|
||
sid = None
|
||
if not p["continues"] and not p["sessionId"]:
|
||
sid = str(uuid.uuid4())
|
||
args = ["--session-id", sid, *args]
|
||
if mod:
|
||
args = ["--plugin-dir", str(MOD_DIR), *args]
|
||
return args, env, sid
|
||
|
||
|
||
def take_relaunch() -> dict | None:
|
||
f = terminal.state_dir() / "relaunch.json"
|
||
try:
|
||
d = json.loads(f.read_text())
|
||
f.unlink()
|
||
except (OSError, ValueError):
|
||
return None
|
||
if not isinstance(d, dict) or time.time() - float(d.get("at") or 0) > RELAUNCH_MAX_AGE_S:
|
||
return None
|
||
if d.get("mode") not in terminal.MODES or not terminal.SID_RE.match(str(d.get("sid") or "")):
|
||
return None
|
||
return d
|
||
|
||
|
||
def _default_signals() -> None:
|
||
# An ignored signal survives exec: a relaunched claude must get its own.
|
||
for s in (signal.SIGINT, signal.SIGQUIT):
|
||
signal.signal(s, signal.SIG_DFL)
|
||
|
||
|
||
def run_child(binary: str, args: list[str], env: dict) -> int:
|
||
child = subprocess.Popen([binary, *args], env=env, preexec_fn=_default_signals)
|
||
# Ctrl-C / Ctrl-\ are claude's business; the launcher only waits.
|
||
for s in (signal.SIGINT, signal.SIGQUIT):
|
||
signal.signal(s, signal.SIG_IGN)
|
||
for s in (signal.SIGTERM, signal.SIGHUP):
|
||
signal.signal(s, lambda n, _f: child.send_signal(n))
|
||
while True:
|
||
try:
|
||
return child.wait()
|
||
except InterruptedError:
|
||
continue
|
||
|
||
|
||
def say(line: str) -> None:
|
||
try:
|
||
sys.stderr.write(line + "\n")
|
||
sys.stderr.flush()
|
||
except OSError:
|
||
pass
|
||
|
||
|
||
def banner(mode: str, cfg: dict, status: dict, cwd: str, sid: str | None,
|
||
mod: bool = True) -> None:
|
||
if mode == "ai-agent":
|
||
owner = status.get("ownerName") or "the hub owner"
|
||
link = conversation_url(hub_url(cfg, status), cwd, sid) if sid else hub_url(cfg, status)
|
||
say(f"{GREEN}●{RESET} ai-agent Claude · {owner}'s plan · synced"
|
||
+ (f" → {link}" if link else ""))
|
||
else:
|
||
how = "/ai-agent sync" if mod else "ai-agent-worker sync --last (once it ends)"
|
||
say(f"{DIM}○ your own Claude · not synced — {how} shares this session{RESET}")
|
||
|
||
|
||
def launch(argv: list[str]) -> int:
|
||
binary = real_claude()
|
||
if not binary:
|
||
say("claude isn't installed here (https://claude.com/claude-code)")
|
||
return 127
|
||
p = parse(argv)
|
||
cfg = proxy_config()
|
||
if p["passthrough"] or not terminal.launcher_on() or not cfg:
|
||
os.execv(binary, [binary, *p["args"]])
|
||
cwd = os.getcwd()
|
||
status = terminal.hub_status()
|
||
opts = options(status, cfg)
|
||
hub_off = opts[0]["off"]
|
||
interactive = sys.stdin.isatty() and sys.stdout.isatty() and not p["print"]
|
||
rem = terminal.remembered(cwd)
|
||
known = terminal.session_mode(p["resume"]) if p["resume"] else None
|
||
if p["want"] in terminal.MODES:
|
||
mode = p["want"]
|
||
elif p["want"] != "ask" and (rem or known):
|
||
mode = rem[0] if rem else known
|
||
if mode == "ai-agent" and hub_off:
|
||
say(f"ai-agent Claude: {opts[0]['note']} — starting your own Claude "
|
||
"(claude --ai-agent to try anyway)")
|
||
mode = "local"
|
||
elif not interactive:
|
||
mode = "local"
|
||
else:
|
||
got = pick(opts, terminal.preselect(cwd), cwd,
|
||
status.get("computer") or os.uname().nodename.split(".")[0])
|
||
if got is None:
|
||
return 130
|
||
mode, keep = got
|
||
terminal.note(cwd, mode, remember=keep)
|
||
version = claude_version(binary)
|
||
mod = bool(interactive and version and version >= MOD_MIN and MOD_DIR.is_dir())
|
||
args, env, sid = build(mode, p, cfg, cwd, mod)
|
||
if sid:
|
||
terminal.note_session(sid, mode)
|
||
if interactive:
|
||
banner(mode, cfg, status, cwd, sid, mod)
|
||
if not mod:
|
||
os.execve(binary, [binary, *args], env)
|
||
while True:
|
||
rc = run_child(binary, args, env)
|
||
again = take_relaunch()
|
||
if not again:
|
||
return rc
|
||
# The mod handed the session over (the guest's own plan ran out).
|
||
p = parse(["--resume", again["sid"]])
|
||
mode = again["mode"]
|
||
args, env, _ = build(mode, p, cfg, cwd, mod)
|
||
terminal.note_session(again["sid"], mode)
|
||
banner(mode, cfg, status, cwd, again["sid"])
|
||
|
||
|
||
# ── ai-agent-worker sync / unsync / choice ───────────────────────────────────
|
||
def _here(rows: list[dict], cwd: str) -> list[dict]:
|
||
return [r for r in rows if (r.get("cwd") or "") == cwd
|
||
or (r.get("cwd") or "").startswith(cwd.rstrip("/") + "/")]
|
||
|
||
|
||
def cmd_sync(args: list[str]) -> int:
|
||
cfg, status = proxy_config(), terminal.hub_status()
|
||
cwd = os.getcwd()
|
||
if args and args[0] not in ("--last",):
|
||
sid = args[0].lower()
|
||
row = terminal.describe(next(projects_dir().glob(f"*/{sid}.jsonl"), pathlib.Path("/nonexistent")))
|
||
else:
|
||
rows = [r for r in _here(terminal.sessions(projects_dir(), 40), cwd) if not r["synced"]]
|
||
if not rows:
|
||
print(f"no unsynced session in {_home(cwd)} — `ai-agent-worker sync <id>` names one")
|
||
return 1
|
||
row = rows[0] if args else _pick_session(rows[:9], cwd)
|
||
if row is None:
|
||
return 130
|
||
sid = row["id"]
|
||
if not terminal.sync(sid, cwd=(row or {}).get("cwd")):
|
||
print(f"not a session id: {sid}")
|
||
return 2
|
||
url = conversation_url(hub_url(cfg, status), (row or {}).get("cwd") or cwd, sid)
|
||
print(f"synced {(row or {}).get('title') or sid} — in the app in a few seconds"
|
||
+ (f": {url}" if url else ""))
|
||
return 0
|
||
|
||
|
||
def _pick_session(rows: list[dict], cwd: str) -> dict | None:
|
||
if not sys.stdin.isatty():
|
||
return rows[0]
|
||
print(f"Sync which session of {_home(cwd)}?")
|
||
for i, r in enumerate(rows, 1):
|
||
age = time.strftime("%d %b %H:%M", time.localtime(r["mtime"]))
|
||
print(f" {i}. {r['title'][:60]} {DIM}{age}{RESET}")
|
||
try:
|
||
ans = input(f"1-{len(rows)} (enter = 1, q = quit): ").strip()
|
||
except (EOFError, KeyboardInterrupt):
|
||
return None
|
||
if ans.lower() == "q":
|
||
return None
|
||
try:
|
||
return rows[int(ans or "1") - 1]
|
||
except (ValueError, IndexError):
|
||
return None
|
||
|
||
|
||
def cmd_unsync(args: list[str]) -> int:
|
||
if not args:
|
||
print("usage: ai-agent-worker unsync <session id>")
|
||
return 2
|
||
if terminal.unsync(args[0]):
|
||
print("stopped syncing it — what the app already has stays there")
|
||
return 0
|
||
print("that session isn't synced from here")
|
||
return 1
|
||
|
||
|
||
def cmd_choice(args: list[str]) -> int:
|
||
sub = args[0] if args else "list"
|
||
if sub == "off":
|
||
terminal.set_launcher(False)
|
||
print("`claude` runs your own Claude again, no question "
|
||
"(`ai-agent-worker claude on` brings the question back)")
|
||
elif sub == "on":
|
||
terminal.set_launcher(True)
|
||
print("`claude` asks which Claude to use again")
|
||
elif sub == "reset":
|
||
gone = terminal.forget(os.path.abspath(args[1]) if len(args) > 1 else None)
|
||
print(f"forgot {len(gone)} remembered folder(s)" if gone else "nothing remembered there")
|
||
else:
|
||
print(f"choose at start: {'on' if terminal.launcher_on() else 'off'}")
|
||
for folder, mode in sorted(terminal.choices().items()):
|
||
print(f" {_home(folder)} → {mode}")
|
||
return 0
|
||
|
||
|
||
def cmd_note(args: list[str]) -> int:
|
||
"""The mod: this session runs on that Claude (a resumed one's id is only
|
||
known inside it)."""
|
||
if len(args) == 2:
|
||
terminal.note_session(args[0], args[1])
|
||
return 0
|
||
|
||
|
||
def main(argv: list[str]) -> int:
|
||
if os.environ.get("AI_AGENT_LAUNCHER_CMD"):
|
||
cmd = os.environ.pop("AI_AGENT_LAUNCHER_CMD")
|
||
return {"sync": cmd_sync, "unsync": cmd_unsync, "claude": cmd_choice,
|
||
"note": cmd_note}[cmd](argv)
|
||
return launch(argv)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main(sys.argv[1:]))
|