Generic platform points for the `diff-viewer` and `commits` plugins (ai-agent-plugins): a `conversation.tab` slot (Thread | Changes N) with setTab/openTab/closeTab/reply bridges; stackable + pullOut tool cards and match.hasReport; `pathShims` (a git PATH shim for every harness) with out-of-band reports (lab: /api/plugin-reports, worker: outbox `report`); `conversations.reports` and `diff.read` hub bridges; ui.pages[].opens for Project/Service "Recent commits". The core commit card, Changes view, diff page and review store are gone; bash_diff.py keeps bashDiff only. Legacy gitCommits / commit-line parsing stays for past transcripts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
334 lines
16 KiB
Python
334 lines
16 KiB
Python
"""
|
|
claude-sidecar — a tiny host-side FastAPI wrapper that launches `claude -p`.
|
|
|
|
The ai-agent viewer runs in a Docker container and therefore can't reach the
|
|
host's `claude` CLI (auth, hooks, skills all live in the host user's
|
|
`~/.claude`). This sidecar runs natively on the host as the same user, so a
|
|
session it spawns is *exactly* like one started from a terminal — same
|
|
credentials, same RTK/vault hooks, same CLAUDE.md/skills.
|
|
|
|
Flow:
|
|
ai-agent backend ──POST /spawn {prompt, sessionId}──▶ this sidecar
|
|
◀──────── {sessionId, pid} ─────────
|
|
The sidecar fires `claude -p <prompt> --session-id <uuid> --output-format json`
|
|
as a detached background process (its own session/process group) and returns as
|
|
soon as the run is known to have *started* (it watches the child for a couple of
|
|
seconds and reports a 502 if it dies on the spot — a resume whose transcript
|
|
can't be found, a bad cwd, a broken CLI). Claude writes its transcript to
|
|
`~/.claude/projects/-home-gabrielvidal-homelab/<uuid>.jsonl`, which the ai-agent
|
|
container already watches read-only — so the new conversation shows up in the
|
|
viewer within a couple of seconds and the UI redirects to it.
|
|
|
|
Restart-proofing (why the runs survive the sidecar restarting).
|
|
Spawned runs are *daemons*: `start_new_session=True` detaches them into their
|
|
own session/process group, and the systemd unit runs with `KillMode=process`
|
|
so a `systemctl restart claude-sidecar` (i.e. what happens when Claude edits
|
|
*this very sidecar* and redeploys it) only signals uvicorn — the in-flight
|
|
`claude -p` children keep running. Their identity is persisted to disk in a
|
|
per-session pidfile (`logs/<uuid>.pid`, JSON with pid + `/proc` start-time),
|
|
so a freshly restarted sidecar re-discovers the survivors on startup and can
|
|
still list and interrupt them. Startup also GCs pidfiles whose process is gone
|
|
or whose PID has been recycled (start-time mismatch).
|
|
|
|
Auth is a shared bearer token (SIDECAR_TOKEN) so nothing on the LAN can drive
|
|
`claude` on the host but the ai-agent backend.
|
|
|
|
Accounts. A claude run launches on one Claude login: the default account (the
|
|
CLI's own `~/.claude`) or one declared in SIDECAR_ACCOUNTS (`work=~/.claude-work`),
|
|
whose dir is exported as CLAUDE_CONFIG_DIR for that run. Resume and fork must
|
|
name the account the session started on — its transcript only exists under
|
|
that account's `projects/`. A non-default account with no login is a 409, never
|
|
a fallback, and ANTHROPIC_API_KEY is stripped once accounts are declared.
|
|
"""
|
|
|
|
import contextlib
|
|
import inspect
|
|
import logging
|
|
import os
|
|
import pathlib
|
|
import uuid
|
|
|
|
from fastapi import FastAPI
|
|
|
|
import claude_env
|
|
import claude_proxy
|
|
import feed
|
|
import askform
|
|
import callprobe
|
|
import fork
|
|
import labsync
|
|
import repo_plugins
|
|
import routes_mcp
|
|
import link
|
|
import opencode_proxy
|
|
import tools_check
|
|
import tools_install
|
|
import outbox
|
|
import path_shims
|
|
import pairing
|
|
import pids
|
|
import procstats
|
|
import routes_accounts
|
|
import routes_git
|
|
import routes_chrome
|
|
import routes_wol
|
|
import routes_runs
|
|
import routes_harnesses
|
|
import harness_loader
|
|
import inhibit
|
|
import scaffold
|
|
import ship
|
|
import tools
|
|
import selfupdate
|
|
import skills_list
|
|
import terminal
|
|
import complete
|
|
import uploads
|
|
import media
|
|
from config import (ACCOUNTS, AGY_ACCOUNTS, AGY_RUNNER_DIR, DEFAULT_ACCOUNT, DEFAULT_CWD, OPENCODE_ACCOUNTS,
|
|
IS_WORKER, OPENCODE_RUNNER_DIR, PERMISSION_MODE,
|
|
TOKEN)
|
|
from validate import _auth
|
|
|
|
class _QuietSessionsPoll(logging.Filter):
|
|
"""Drop ``/sessions`` and ``/procs`` access-log lines: the ai-agent backend
|
|
polls them every few seconds (run-exit detection, the Performance
|
|
dashboard), which would otherwise flood the journal with tens of thousands
|
|
of identical lines a day."""
|
|
|
|
def filter(self, record: logging.LogRecord) -> bool:
|
|
msg = record.getMessage()
|
|
return "/sessions" not in msg and "GET /procs" not in msg
|
|
|
|
|
|
logging.getLogger("uvicorn.access").addFilter(_QuietSessionsPoll())
|
|
|
|
# What runs when the server starts, in order. A lifespan, not startup events:
|
|
# Starlette 1.x dropped `add_event_handler`, and inside the hub's image the
|
|
# sidecar runs on the backend's FastAPI.
|
|
_STARTUP: list = []
|
|
# …and what runs when it stops (the lifespan's teardown).
|
|
_SHUTDOWN: list = []
|
|
|
|
|
|
@contextlib.asynccontextmanager
|
|
async def _lifespan(_app: FastAPI):
|
|
for fn in _STARTUP:
|
|
out = fn()
|
|
if inspect.isawaitable(out):
|
|
await out
|
|
try:
|
|
yield
|
|
finally:
|
|
for fn in _SHUTDOWN:
|
|
try:
|
|
fn()
|
|
except Exception as e: # noqa: BLE001 — one teardown never skips the next
|
|
print(f"[sidecar] shutdown step {fn!r} failed: {e!r}", flush=True)
|
|
|
|
|
|
app = FastAPI(title="claude-sidecar", docs_url=None, redoc_url=None,
|
|
openapi_url=None, lifespan=_lifespan)
|
|
# On (re)start, GC pidfiles whose process is gone and count the survivors —
|
|
# see pids.py.
|
|
_STARTUP.append(pids._reconcile_pidfiles)
|
|
# A Linux worker holds a logind sleep lock while a run is live, so the machine
|
|
# (the EVOX2) never auto-suspends mid-run; dropped at shutdown (inhibit.py).
|
|
_STARTUP.append(inhibit.INHIBITOR.start)
|
|
_SHUTDOWN.append(inhibit.INHIBITOR.stop)
|
|
|
|
|
|
def _mirror_proxied(accounts: list[str]) -> None:
|
|
"""Accounts the hub's opencode proxy just gave this worker: mirrored like
|
|
the declared ones — by whichever driver runs opencode (opencode_proxy.py)."""
|
|
d = harness_loader.get("opencode")
|
|
if d is not None and hasattr(d, "mirror_accounts"):
|
|
d.mirror_accounts(accounts)
|
|
|
|
|
|
# The harness drivers and usage readers (harness_loader.py, usage_loader.py):
|
|
# loaded from the live plugin dirs (or their last-known-good copy) with the
|
|
# built-in bridges behind them, then started — the opencode / agy mirrors, the
|
|
# opencode / agy / guests' Claude usage pollers.
|
|
_STARTUP.append(routes_harnesses.startup)
|
|
# A guest's computer dials out to the hub instead of listening (link.py) —
|
|
# idle on every runner without a link.json.
|
|
_STARTUP.append(link.start)
|
|
# …and a guest's ask-form posts its events here, so the hub gets each form's
|
|
# link (askform.wire_events; a no-op off a link worker).
|
|
_STARTUP.append(askform.start)
|
|
# (The no-op Stop hook every account's settings.json gets, and the conv-ref
|
|
# prompt hook, are installed by the harness-claude plugin's driver at its
|
|
# startup — turn_hook.py / conv_ref_hook.py there.)
|
|
# The call probe (callprobe.py): agent-probe's hooks in every account's
|
|
# settings.json (and opencode / Codex / pi's, when found), claude-probe's store
|
|
# migrated once, and its daemon kept up — what each shell call and every
|
|
# process it started cost (exact from the kernel on Linux once setup-kernel
|
|
# ran, from kqueue on macOS).
|
|
_STARTUP.append(callprobe.start)
|
|
|
|
# ---- the runner's own endpoints ----------------------------------------------
|
|
# /health + the account routes (routes_accounts.py), the run routes
|
|
# /sessions /spawn /resume /interrupt /message (routes_runs.py), and /fork
|
|
# with its transcript surgery (fork.py).
|
|
app.include_router(routes_accounts.router)
|
|
# A worker's Setup checklist (claude / gh / ask-form), warmed up at start.
|
|
if IS_WORKER:
|
|
_STARTUP.append(tools_check.start)
|
|
app.include_router(routes_runs.router)
|
|
app.include_router(fork.router)
|
|
# /harnesses + /harnesses/reload: the live drivers (routes_harnesses.py).
|
|
app.include_router(routes_harnesses.router)
|
|
routes_harnesses.APP = app
|
|
|
|
|
|
def _host_only(router) -> None:
|
|
"""Mount one of the lab's own routers on the host sidecar (and the
|
|
in-container runner, which has a token too) — never on a paired worker
|
|
(the Orus devbox, the Macs). The hub only calls these on the host sidecar
|
|
(runs/sidecar_client._sidecar_call with no ``worker``); on a worker they
|
|
would only be endpoints nothing uses that the worker's token still opens.
|
|
(tools.py also refuses on a worker itself.)"""
|
|
if not IS_WORKER:
|
|
app.include_router(router)
|
|
|
|
|
|
# /scaffold: a new project from one of the owner's templates — the host half
|
|
# of the hub's New project flow (scaffold.py).
|
|
_host_only(scaffold.router)
|
|
# /tools/…: the lab tools the hub's tool proxy runs here for guests and the
|
|
# owner's Macs — video-extract jobs in a library per caller, 3d-render
|
|
# (tools.py).
|
|
_host_only(tools.router)
|
|
# /ship/deploy: a guest's build published for them, outside their sandbox —
|
|
# the host half of the hub's deploy broker (ship.py).
|
|
_host_only(ship.router)
|
|
# /complete: one short answer from any model (claude / agy / opencode drivers'
|
|
# complete(), the EVOX2 or OpenRouter over HTTP) with nothing a run loads —
|
|
# the conversation-labels plugin's titles and action badges (complete.py).
|
|
_host_only(complete.router)
|
|
# /git/commit, /git/range: a commit's patch / a run of commits' net diff from a
|
|
# repo on this machine — how the hub reviews a worker conversation's commits
|
|
# that the transcript doesn't carry in full (routes_git.py).
|
|
app.include_router(routes_git.router)
|
|
# /chrome: the lab Chrome container (services/chrome) — docker status and the
|
|
# start/stop/restart/reset-profile actions behind Settings → Browser (routes_chrome.py).
|
|
_host_only(routes_chrome.router)
|
|
# /wol: a Wake-on-LAN magic packet onto the LAN, which the hub's container
|
|
# can't broadcast on — the wake-on-lan plugin's machines.wake bridge (routes_wol.py).
|
|
_host_only(routes_wol.router)
|
|
# (/local-ready — wake the EVOX2 and load a local model before a cron job runs
|
|
# on it — is the provider-evox2 plugin's: its sidecar module's extra_routers(),
|
|
# host only, as are the live generation readings /sessions adds.)
|
|
# (/pi/openrouter — whether the key pi's OpenRouter runs use is accepted — is
|
|
# the harness-pi plugin's: its driver's extra_routers(), mounted by
|
|
# routes_harnesses once it loads, on the host only.)
|
|
# /procs: CPU + memory of every agent run here and of the processes it
|
|
# started, the leftovers of ended ones (+ /procs/kill) — the hub's Performance
|
|
# dashboard (procstats.py).
|
|
app.include_router(procstats.router)
|
|
# /callmeta: agent-probe's records — each shell call and every process it
|
|
# started, the turn boundaries (callprobe.py) — the hub pulls it with /procs.
|
|
app.include_router(callprobe.router)
|
|
# (/tasks/output + /tasks/stop — one background shell / Monitor of a run, its
|
|
# output's tail and a stop — are the harness-claude plugin's extra_routers().)
|
|
|
|
# A paired remote worker has no hub URL or credential, so its runs reach the
|
|
# hub through *this* sidecar's outbox (outbox.py): the hub pulls it. The host
|
|
# sidecar (SIDECAR_TOKEN set) is next to the hub — its runs talk to it directly.
|
|
OUTBOX = outbox.Outbox(pairing.state_dir() / "outbox.json")
|
|
|
|
def _default_login() -> dict:
|
|
"""The default account's login, as the claude harness driver reads it
|
|
(pairing's identity) — {} without one."""
|
|
out = harness_loader.dispatch_account(DEFAULT_ACCOUNT, "account_status")
|
|
return out if isinstance(out, dict) else {}
|
|
|
|
|
|
# ---- worker endpoints --------------------------------------------------------
|
|
# Mounted on every runner (host sidecar, in-container runner, remote worker) —
|
|
# they're only *used* when a hub pairs with this runner as a remote worker:
|
|
# /feed is how the hub pulls transcripts it has no mount for, /pair how it gets
|
|
# the bearer in the first place. See feed.py / pairing.py.
|
|
app.include_router(feed.make_router(
|
|
_auth, lambda: claude_env._account_projects(DEFAULT_ACCOUNT),
|
|
lambda: {**{f"@opencode/{a}": OPENCODE_RUNNER_DIR / "transcripts" / a
|
|
for a in [*OPENCODE_ACCOUNTS, *opencode_proxy.accounts()]},
|
|
**{f"@agy/{a}": AGY_RUNNER_DIR / "transcripts" / a for a in AGY_ACCOUNTS}},
|
|
lambda: sorted(terminal.synced()) if IS_WORKER else []))
|
|
app.include_router(pairing.make_router(
|
|
_auth, _default_login,
|
|
lambda: {"cwd": DEFAULT_CWD, "defaultAccount": DEFAULT_ACCOUNT,
|
|
"permissionMode": PERMISSION_MODE,
|
|
"projectsDir": str(claude_env._account_projects(DEFAULT_ACCOUNT))}))
|
|
# /outbox: a worker session's notifications / asks / forms, queued for the hub
|
|
# to collect (outbox.py). Runs authenticate with the per-worker run token.
|
|
app.include_router(outbox.make_router(
|
|
OUTBOX, _auth, lambda: outbox.run_token(pairing.state_dir())))
|
|
# /ask-form: this machine's forms from the standalone ask-form tool — its
|
|
# loopback admin API proxied for the hub (list / get / revoke), and the
|
|
# `ask-form serve` events webhook, queued in the outbox like a run's
|
|
# notifications so the hub pulls it (askform.py).
|
|
app.include_router(askform.make_router(
|
|
_auth, lambda ev: OUTBOX.put("askform", {"id": f"afe_{uuid.uuid4().hex[:12]}", **ev})))
|
|
# Plugin path shims' reports a run couldn't send (aia_report.py's spool):
|
|
# drained into the outbox on a worker, to the hub on the lab (path_shims.py).
|
|
_STARTUP.append(lambda: path_shims.start_drain(OUTBOX.put, IS_WORKER))
|
|
# /update: move this worker to the hub's commit — starts worker/install.sh
|
|
# auto-update detached (selfupdate.py); /health reports how it went.
|
|
app.include_router(selfupdate.make_router(_auth))
|
|
# /claude-proxy: where this worker's Claude Code sends its model calls — the
|
|
# hub, which bills its own logins (claude_proxy.py). Pushed by the hub when
|
|
# /health's claudeProxy.hash differs.
|
|
app.include_router(claude_proxy.make_router(_auth))
|
|
# /opencode-proxy: its opencode twin — the accounts whose opencode runs bill
|
|
# the Homelab's ChatGPT login through the hub (opencode_proxy.py).
|
|
app.include_router(opencode_proxy.make_router(_auth, _mirror_proxied))
|
|
# /sync: the lab's skills and agents flagged `workers: true`, pushed by the hub
|
|
# when /health's labSync.hash is behind; linked into this machine's user-level
|
|
# skills/agents dirs (labsync.py).
|
|
app.include_router(labsync.make_router(_auth))
|
|
# /repo-plugins: the hub enables the cwd repo's own Claude Code plugins
|
|
# for the default account (repo_plugins.py).
|
|
app.include_router(repo_plugins.make_router(_auth))
|
|
# /tools/install + /gh/login: the Setup checklist's Install / Update / Sign in —
|
|
# worker/tools.sh run detached, gh's device-code sign-in (tools_install.py).
|
|
app.include_router(tools_install.make_router(_auth))
|
|
# /mcp-servers: the MCP servers the hub's mcp-servers plugin sets up, signs
|
|
# in and approves here, for every login of every harness whose driver ships
|
|
# an MCP adapter (routes_mcp.py → mcp_base.py) — never on a guest's computer.
|
|
app.include_router(routes_mcp.make_router(_auth))
|
|
# /link/token: the hub rotating the token this computer dials out with (link.py).
|
|
app.include_router(link.make_router(_auth))
|
|
# /uploads: a file attached in the hub's composer, copied here before a
|
|
# prompt naming it reaches a run — the hub swaps the lab path in the prompt
|
|
# for the one this answers (uploads.py).
|
|
app.include_router(uploads.make_router(_auth))
|
|
# /media: an image a run here read, at full size — the hub's *Original* link
|
|
# on an image card (media.py).
|
|
app.include_router(media.make_router(_auth))
|
|
# /skills: the skills a run here can use (the default account's user-level
|
|
# skills + the default cwd's project skills) — what the hub's composer lists
|
|
# when a prompt is sent to this worker (skills_list.py).
|
|
# /terminal: this computer's own `claude` sessions — which the guest syncs to
|
|
# the hub, and the launcher's *choose at start* switch (terminal.py).
|
|
app.include_router(terminal.make_router(
|
|
_auth, lambda: claude_env._account_projects(DEFAULT_ACCOUNT)))
|
|
app.include_router(skills_list.make_router(
|
|
_auth, lambda: skills_list.skill_roots(ACCOUNTS.get(DEFAULT_ACCOUNT),
|
|
pathlib.Path(DEFAULT_CWD))))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
# `python sidecar.py` — how the macOS worker's launchd agent starts it:
|
|
# SIDECAR_BIND is the Mac's Tailscale address, so the listener is reachable
|
|
# over the tailnet only (nothing on the office LAN, nothing on loopback).
|
|
import uvicorn
|
|
|
|
bind = os.environ.get("SIDECAR_BIND", "127.0.0.1")
|
|
port = int(os.environ.get("SIDECAR_PORT", "8790"))
|
|
if not (TOKEN or pairing.token()) and not pairing._read("pairing-code"):
|
|
print(f"[worker] not paired — pairing code: {pairing.new_code()}",
|
|
flush=True)
|
|
uvicorn.run(app, host=bind, port=port)
|