Files
ai-agent/sidecar/ptyrun.py
Gabriel VidalandClaude Opus 5.5 1574ccd388 sidecar: strict plugin-only cutover (Wave 3C)
Delete the built-in bridges and the legacy harness / usage modules now owned
by ai-agent-plugins (harness_builtin, claude_cli, claude_accounts,
claude_usage, pi_runs, opencode_{cli,mirror,tools,usage},
agy_{cli,mirror,tools,usage}). routes_runs / fork keep only the routes; the
harness-* plugins' drivers launch.

- harness_loader: no builtins; the first read boots the registry; a live dir
  never materialized falls back to .lkg, then (host only) the seed plugins
  (SIDECAR_SEED_PLUGINS_DIR, default ~/projects/ai-agent-plugins/plugins);
  codeless provider entries keep their manifest + config.json; module() and
  forget_status() accessors; hub-written absolute dirs resolved by name.
- usage_loader: provider_configs() covers every provider plugin, evox2()
  reads servers + Wake-on-LAN from provider-evox2 (local_ready, gen_progress
  use it — no duplicated EVOX2 constants).
- core helpers kept self-contained: claude_env.py (run env, account env,
  machine login), run_errors.py (typed errors); launch._stop_run calls the
  driver's stop_extra; /accounts?fresh=1 and guest listing go through drivers;
  gen_progress reads the opencode db via harness_loader.module; tools_check
  via driver status; tools_install has its own gh device-login pump.
- /sync accepts a provider bundle without a usage reader.
- backend workers/labsync: always send harnesses + providers maps ({} clears
  a worker); guests only get harnesses whose own plugin.json says
  guestAllowed.
- tests + A/B scripts run the real plugins (conftest live index + legacy-name
  import hook; launch-dump / _mirror_worker load the plugins for a tree with
  no bridges). install.sh points the host unit at the hub's live dirs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 16:53:17 +01:00

418 lines
16 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""A Code Mode run: an interactive ``claude`` driven headless on a pseudo-terminal.
Why. Claude Code's Code Mode (``CLAUDE_CODE_EXPERIMENTAL_CODE_MODE=1``: the
model writes JavaScript its ``REPL`` tool runs, each `` $`…` `` / ``edit()`` in
it an ordinary tool call) only starts in an interactive terminal session —
``claude -p`` silently runs without it, and a session started in it can't be
resumed by ``-p`` at all ("This session was started in Code Mode … can't be
resumed here"). So the sidecar launches such a run through this wrapper
instead of ``claude -p`` (launch.py ``code_mode_args``)::
python3 -I ptyrun.py --sid <sid> --state <LOG_DIR> -- claude … -- <prompt>
It does what a person at the terminal would:
* forks the CLI on a pty (200 × 50), with its environment plus
``AIA_PTYRUN=1`` — which is what makes stop_guard.py drop the turn-end marker;
* answers the start-up dialogs: the folder trust, the Code Mode consent (each
login asks once), the bypass-permissions warning, a fresh login's text-style
pick. Any other dialog still up after DIALOG_GIVEUP_S is declined (Esc);
* reads the start banner — ``Code Mode (experimental) is on`` or ``… isn't
available: <reason>`` — into ``<state>/<sid>.codemode.json``
(``{"on", "reason", "at"}``; the sidecar's /spawn and /sessions report it);
* ends the session once its turn is over, so a run lives exactly as long as a
``claude -p`` one and everything keyed off the process (running state, Stop,
the exit watcher, the inbox) works unchanged: stop_guard.py — the Stop hook
every hub run has — writes ``<state>/<sid>.turnend`` when it lets a stop
through, with the background tasks still running. With none left and the
CLI's session registry (``<config dir>/sessions/*.json``) saying ``idle``,
it types ``/exit``. A background subagent or Monitor keeps it alive: its
notification starts the next turn, whose stop writes a new marker;
* on SIGINT / SIGTERM / SIGHUP (the sidecar's /interrupt and ``_stop_run``):
Esc (interrupts a turn), ``/exit``, then SIGTERM / SIGKILL the CLI — all
inside the sidecar's STOP_WAIT_S. Killed outright, the pty closes and the
CLI gets its SIGHUP.
The run log (stdout): the screen as text, ANSI stripped, for the first
LOG_HEAD bytes (start-up errors — a ``--resume`` that finds nothing — land
there, where ``run_errors.run_failure`` reads them), the ``[code-mode]``
lines, and the last screen on exit. Exit code: the CLI's.
Stdlib only (Linux + macOS workers); run with ``-I`` like the hooks.
"""
from __future__ import annotations
import argparse
import fcntl
import json
import os
import pathlib
import pty
import re
import select
import signal
import struct
import sys
import termios
import time
COLS, ROWS = 200, 50
LOG_HEAD = 64 * 1024
RECENT = 16 * 1024
# A dialog: first action this long after it shows (its input isn't wired
# before it has rendered), then one key per DIALOG_STEP_S.
DIALOG_SETTLE_S = 0.8
DIALOG_STEP_S = 0.6
DIALOG_MAX_KEYS = 8
DIALOG_GIVEUP_S = 20.0
# The turn is over: wait for the registry to say idle (the other Stop hooks
# finish) at most this long, then /exit; the CLI gets EXIT_GRACE_S to go.
IDLE_WAIT_S = 20.0
EXIT_GRACE_S = 15.0
# A stop request (the sidecar SIGKILLs the group after its STOP_WAIT_S = 6 s).
STOP_EXIT_AFTER_S = 0.7
STOP_TERM_AFTER_S = 3.0
STOP_KILL_AFTER_S = 5.0
DOWN, ENTER, ESC = b"\x1b[B", b"\r", b"\x1b"
_ANSI = re.compile(rb"\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)" # OSC
rb"|\x1bP[^\x1b]*\x1b\\" # DCS
rb"|\x1b\[[0-9;?<>=]*[ -/]*[@-~]" # CSI
rb"|\x1b[()][A-Za-z0-9]|\x1b[=>78DEHMc]") # charset, misc
_CTRL = re.compile(rb"[\x00-\x08\x0b-\x1f\x7f]")
_SPACE = re.compile(r"\s+")
# (name, what shows it, the option to pick — None: just Enter)
DIALOGS = (
("trust", "Yes, I trust this folder", "Yes, I trust this folder"),
("consent", "Yes, turn on Code Mode", "Yes, turn on Code Mode"),
("bypass", "Yes, I accept", "Yes, I accept"),
("style", "Choose the text style", None),
("continue", "Press Enter to continue", None),
)
_ON = re.compile(r"Code Mode \(experimental\) is on")
_OFF = re.compile(r"Code Mode \(experimental\) isn.t available: (.{1,400})")
_DECLINED = re.compile(r"Code Mode \(experimental\) is off for this session")
_REASON_END = re.compile(r"\s*(?:Starting with the ordinary tools|─|❯|Tips? for getting)")
_ANY_DIALOG = re.compile(r"Enter to confirm|Esc to cancel")
def plain(data: bytes) -> str:
"""Terminal output as text: escape sequences become a space (a cursor
move is a gap on screen), other control bytes go."""
return _CTRL.sub(b"", _ANSI.sub(b" ", data)).decode("utf-8", "replace")
def flat(text: str) -> str:
return _SPACE.sub(" ", text)
def banner(screen: str) -> dict | None:
"""What the start banner says about Code Mode, or None before it shows."""
s = flat(screen)
if _ON.search(s):
return {"on": True, "reason": None}
m = _OFF.search(s)
if m:
reason = _REASON_END.split(m.group(1), 1)[0].strip().rstrip(".").strip()
return {"on": False, "reason": reason or "unavailable"}
if _DECLINED.search(s):
return {"on": False, "reason": "declined at the Code Mode prompt"}
return None
def selected(screen: str) -> str:
"""The option the newest menu render highlights (the text after its last
``❯``), '' when none shows."""
s = flat(screen)
i = s.rfind("❯")
return s[i + 1:].strip() if i >= 0 else ""
def registry_status(reg_dir: pathlib.Path, sid: str, hint: list) -> str | None:
"""The CLI's own status for ``sid`` (``busy`` / ``idle`` / …) from its
session registry. The file is found by session id — accepting the Code
Mode consent restarts the CLI — and remembered in ``hint``."""
if hint and hint[0]:
try:
d = json.loads(hint[0].read_text())
if d.get("sessionId") == sid:
return d.get("status")
except (OSError, ValueError, AttributeError):
pass
try:
files = sorted(reg_dir.glob("*.json"), key=lambda p: p.stat().st_mtime,
reverse=True)
except OSError:
return None
for f in files:
try:
d = json.loads(f.read_text())
except (OSError, ValueError):
continue
if isinstance(d, dict) and d.get("sessionId") == sid:
hint[:] = [f]
return d.get("status")
return None
class Run:
def __init__(self, sid: str, state: pathlib.Path, reg_dir: pathlib.Path,
out=None, clock=time.monotonic):
self.sid, self.state, self.reg_dir = sid, state, reg_dir
self.out = out or sys.stdout.buffer
self.clock = clock
self.recent = ""
self.logged = 0
self.answered: set[str] = set()
self.dialog: dict | None = None
self.unknown_since: float | None = None
self.code_mode: dict | None = None
self.exit_typed_at: float | None = None
self.turn_over_at: float | None = None
self.stop_at: float | None = None
self.stop_steps: set[str] = set()
self.reg_hint: list = []
self.keys: list[bytes] = [] # what to type, drained by the loop
# ── output ──────────────────────────────────────────────────────────────
def log(self, line: str) -> None:
try:
self.out.write(f"\n[code-mode] {line}\n".encode())
self.out.flush()
except (OSError, ValueError):
pass
def feed(self, data: bytes) -> None:
text = plain(data)
if self.logged < LOG_HEAD:
chunk = text[:LOG_HEAD - self.logged]
self.logged += len(chunk)
try:
self.out.write(chunk.encode())
self.out.flush()
except (OSError, ValueError):
pass
self.recent = (self.recent + text)[-RECENT:]
if self.code_mode is None:
b = banner(self.recent)
if b is not None:
self.code_mode = b
self._write_state(".codemode.json", {**b, "at": time.time()})
self.log("on" if b["on"] else f"not available: {b['reason']}")
def _write_state(self, suffix: str, obj: dict) -> None:
p = self.state / f"{self.sid}{suffix}"
try:
tmp = p.with_name(p.name + ".tmp")
tmp.write_text(json.dumps(obj))
os.replace(tmp, p)
except OSError:
pass
# ── dialogs ─────────────────────────────────────────────────────────────
def dialogs(self, now: float) -> None:
if self.stop_at is not None:
return
s = flat(self.recent[-4096:])
if self.dialog is None:
for name, shows, target in DIALOGS:
if name not in self.answered and shows in s:
self.dialog = {"name": name, "target": target, "seen": now,
"last": None, "keys": 0}
self.unknown_since = None
break
d = self.dialog
if d is None:
# A dialog we don't know: decline it once it has sat there a while.
if _ANY_DIALOG.search(s):
if self.unknown_since is None:
self.unknown_since = now
elif now - self.unknown_since > DIALOG_GIVEUP_S:
self.log(f"declined an unknown dialog: {s[-300:]!r}")
self.keys.append(ESC)
self.recent, self.unknown_since = "", None
else:
self.unknown_since = None
return
if now - d["seen"] < DIALOG_SETTLE_S:
return
if d["last"] is not None and now - d["last"] < DIALOG_STEP_S:
return
if d["target"] is None or selected(self.recent[-4096:]).startswith(d["target"]):
self.keys.append(ENTER)
self.answered.add(d["name"])
self.log(f"answered the {d['name']} prompt")
self.dialog, self.recent = None, ""
return
if d["keys"] >= DIALOG_MAX_KEYS:
self.log(f"couldn't reach {d['target']!r} in the {d['name']} prompt — declined")
self.keys.append(ESC)
self.answered.add(d["name"])
self.dialog, self.recent = None, ""
return
self.keys.append(DOWN)
d["keys"] += 1
d["last"] = now
# ── the end of the turn ────────────────────────────────────────────────
def turn(self, now: float) -> None:
if self.stop_at is not None or self.exit_typed_at is not None:
return
marker = self.state / f"{self.sid}.turnend"
if marker.exists():
try:
info = json.loads(marker.read_text())
except (OSError, ValueError):
info = {}
try:
marker.unlink()
except OSError:
pass
bg = info.get("background") or []
if bg:
self.log(f"turn over, {len(bg)} background task(s) still running — staying up")
self.turn_over_at = None
else:
self.turn_over_at = now
if self.turn_over_at is None:
return
status = registry_status(self.reg_dir, self.sid, self.reg_hint)
if status in (None, "idle") or now - self.turn_over_at > IDLE_WAIT_S:
if status is None and now - self.turn_over_at < 2.0:
return # no registry to read: give the other Stop hooks a moment
self.log("turn over — /exit")
self.keys += [b"/exit", ENTER]
self.exit_typed_at, self.turn_over_at = now, None
# ── a stop request ─────────────────────────────────────────────────────
def stopping(self, now: float, child: int) -> None:
if self.stop_at is None:
return
t = now - self.stop_at
if "esc" not in self.stop_steps:
self.stop_steps.add("esc")
self.keys.append(ESC)
if t >= STOP_EXIT_AFTER_S and "exit" not in self.stop_steps:
self.stop_steps.add("exit")
self.keys += [b"/exit", ENTER]
if t >= STOP_TERM_AFTER_S and "term" not in self.stop_steps:
self.stop_steps.add("term")
_signal(child, signal.SIGTERM)
if t >= STOP_KILL_AFTER_S and "kill" not in self.stop_steps:
self.stop_steps.add("kill")
_signal(child, signal.SIGKILL)
def exiting(self, now: float, child: int) -> None:
if self.exit_typed_at is None or self.stop_at is not None:
return
t = now - self.exit_typed_at
if t > EXIT_GRACE_S and "term" not in self.stop_steps:
self.log("the CLI didn't exit after /exit — SIGTERM")
self.stop_steps.add("term")
_signal(child, signal.SIGTERM)
if t > EXIT_GRACE_S + 5 and "kill" not in self.stop_steps:
self.stop_steps.add("kill")
_signal(child, signal.SIGKILL)
def _signal(pid: int, sig: int) -> None:
try:
os.kill(pid, sig)
except OSError:
pass
def _write(fd: int, data: bytes) -> None:
try:
os.write(fd, data)
except OSError:
pass
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0])
ap.add_argument("--sid", required=True)
ap.add_argument("--state", required=True)
ap.add_argument("cmd", nargs=argparse.REMAINDER)
a = ap.parse_args(argv)
cmd = a.cmd[1:] if a.cmd[:1] == ["--"] else a.cmd
if not cmd:
ap.error("no command")
state = pathlib.Path(a.state)
cfg = os.environ.get("CLAUDE_CONFIG_DIR") or os.path.expanduser("~/.claude")
run = Run(a.sid, state, pathlib.Path(cfg) / "sessions")
pid, fd = pty.fork()
if pid == 0: # the CLI, on the pty's slave side (its own session)
try:
fcntl.ioctl(0, termios.TIOCSWINSZ, struct.pack("HHHH", ROWS, COLS, 0, 0))
except OSError:
pass
env = {**os.environ, "AIA_PTYRUN": "1"}
env.setdefault("TERM", "xterm-256color")
try:
os.execvpe(cmd[0], cmd, env)
except OSError as e:
sys.stderr.write(f"ptyrun: can't run {cmd[0]}: {e}\n")
os._exit(127)
def on_signal(signum, _frame):
if run.stop_at is None:
run.stop_at = time.monotonic()
run.log(f"stop requested ({signal.Signals(signum).name})")
for s in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP):
signal.signal(s, on_signal)
run.log(f"started {os.path.basename(cmd[0])} (pid {pid}) on a {COLS}×{ROWS} pty")
code = None
while True:
try:
r, _, _ = select.select([fd], [], [], 0.2)
except InterruptedError:
r = []
except OSError:
break
if r:
try:
data = os.read(fd, 65536)
except OSError: # EIO: the slave side is closed — the CLI is gone
data = b""
if not data:
break
run.feed(data)
now = time.monotonic()
run.dialogs(now)
run.turn(now)
run.stopping(now, pid)
run.exiting(now, pid)
while run.keys:
_write(fd, run.keys.pop(0))
if run.keys:
time.sleep(0.15)
try:
done, status = os.waitpid(pid, os.WNOHANG)
except ChildProcessError:
break
if done:
code = os.waitstatus_to_exitcode(status)
break
if code is None:
try:
_, status = os.waitpid(pid, 0)
code = os.waitstatus_to_exitcode(status)
except ChildProcessError:
code = 0
try:
os.close(fd)
except OSError:
pass
run.log(f"exited ({code}); last screen: {flat(run.recent)[-1500:]}")
return code if code >= 0 else 128 - code
if __name__ == "__main__":
sys.exit(main())