Owner jobs and guests' own scheduled jobs are the cron-jobs live plugin's (forms move-ai-agent-cron-jobs-into-a-plugin_u0wa6b, cron-scheduled-in-the-cli-and-mcp_x4nk83). Gone: backend/cron/, schemas/cron.py, /api/cron*, /api/me/cron*, the cron scheduler thread, Settings → Cron and the guests' Tâches planifiées pages, `ai-agent cron` (now a pointer), MCP run_cron_job / set_cron_job / browse cron, the scheduled-jobs core skill, guestDefaults.cronLimits. The core keeps thin contracts: - runs.guest bridge (runs/guestjob.py): a guest's job run as that guest, confined by the core from their record; the plugin only names it. - runs.start's cron stamp → meta.cron. - delivery of a guest job's result (push, mail, mailHtml) off the stamp. - « Discuter »: POST /api/cron-runs/discuss. - runs.cron provider readers (plugins/cron_bridge.py): budget, auto-archive, agents catalog, the agents page's Schedule. - core/cronexpr.py, agents/runconfig.py; context.write create for a new agent definition; ui.pages[].unless; setRoute keeps a Settings page under /settings/p/. - carryover.cron_jobs: /data/cron-jobs.json → the plugin's jobs.json, cronLimits → limits.json, guests' qwen jobs → sonnet (PR #23's decision, superseded). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude-sidecar
A tiny host-side FastAPI wrapper that launches claude -p sessions on behalf
of the ai-agent viewer.
Why a host process (not a container)
The ai-agent viewer runs in Docker and can't reach the host's claude CLI — its
auth (~/.claude/.credentials.json), RTK/vault hooks, and skills all live in the
host user's home. This sidecar runs natively on the host as the repo owner, so
a session it spawns is exactly like one started from a terminal.
Flow
Frontend (sticky input)
│ POST /api/spawn {prompt}
▼
ai-agent backend (container)
│ generates a session UUID, POST /spawn to the sidecar
▼ http://host.docker.internal:8790/spawn (Bearer SIDECAR_TOKEN)
claude-sidecar (host)
└─ claude -p <prompt> --session-id <uuid> --output-format json \
--permission-mode bypassPermissions --model opus \
--remote-control (detached)
--remote-control is added by default so every spawned run registers with
Claude Code Remote Control and shows up in the Claude app — you can watch and
drive the conversation from your phone. Set SIDECAR_REMOTE_CONTROL=0 to opt
out.
Claude writes its transcript to
~/.claude/projects/-home-gabrielvidal-homelab/<uuid>.jsonl, which the ai-agent
container already watches read-only. The new conversation appears in the viewer
within ~2s and the frontend redirects to it once it has synced.
The conversation view has a matching sticky composer that continues an existing
thread: it POSTs /api/spawn's sibling /api/resume, which the backend proxies
to POST /resume here — claude -p <prompt> --resume <sessionId> in the
session's original cwd. Because resume reuses the session id, the new turns
append to the same transcript and stream straight into the open conversation.
Install (host)
sidecar/install.sh
Creates a venv, writes a systemd user unit (~/.config/systemd/user/claude-sidecar.service),
and starts it. Reboot survival needs sudo loginctl enable-linger $USER.
Config comes from the repo .env: SIDECAR_TOKEN, SIDECAR_PORT (default 8790).
The ai-agent container reads SIDECAR_URL + SIDECAR_TOKEN (see its
docker-compose.yml, which also adds host.docker.internal:host-gateway).
Modules
uvicorn sidecar:app (and python sidecar.py on the macOS worker) loads one
thin entry module that mounts a router per concern:
sidecar.py— the FastAPIapp: logging filter, startup hook, router mounts,__main__.config.py— every env var and constant (SIDECAR_*), each with its comment.pids.py— pid-record tracking:logs/<sid>.pid, liveness (/procor psutil), startup reconcile.validate.py— bearer check and per-field validation (uuid, model, harness, thinking / effort flags).claude_env.py— the env every run launches with (_run_env: session id, notify CLI on PATH, a worker's outbox), the env that selects a Claude login (_account_env:CLAUDE_CONFIG_DIR, the hub's proxy pair) for the core's ownclaudeside calls, an account's transcripts dir, and whether a run bills this machine's own login (machine_login). The claude harness itself — runs, argv, logins,auth status,/health'sownLogin— is the harness-claude plugin's.launch.py— any harness's detached launch, launch probe and stop, plus the two run specs every harness reads: a guest'sscope(valid_scope) and a cron job'slean(valid_lean,lean_prompt). Claude Code's own argv —--settings(Stop guard, Bash diff, guard, allow guard, gcloud's hook), a scope's permission rules and sandbox,--append-system-prompt/--agents, lean flags,/compact,--remote-control, Code Mode — is the harness-claude plugin'ssidecar/claude_launch.py(since 2026-11-26).allow_guard.py— the PreToolUse hook that holds a lean claude run's Bash to itsallowprograms (the pi runner's permissions extension parses the same way).- (
POST /local-ready, the liveprogressof/sessionsand the pre-launch room-making on the EVOX2 are the provider-evox2 plugin's sidecar module since 2026-11-26.) routes_runs.py—/sessions,/spawn,/resume,/interrupt,/message.- (
POST /tasks/output/POST /tasks/stop— the hub's Background shells card — are the harness-claude plugin'sbgtasks.py, mounted through its driver'sextra_routers().) procstats.py—GET /procs: CPU + memory of every agent run on this machine, its process tree, the leftovers of ended runs and the host's totals (the hub's Performance dashboard polls it);POST /procs/killstops an ended conversation's leftovers only. Lazy: a scan runs only when asked.routes_accounts.py—/health,/accounts, the login / logout routes.fork.py—/forkand the transcript surgery behind it.inhibit.py— a Linux worker's sleep lock: a logindsleepblock inhibitor (systemd-inhibit … caton a pipe, so it dies with the sidecar) held whilepids.list_live()is non-empty, re-checked on/spawn/resume/forkand every 5 s (15 s idle), dropped at shutdown;/health→sleepInhibitor {enabled, available, engaged, reason?}. On by default on a Linux worker,SIDECAR_INHIBIT_SLEEP=0|1overrides; a no-op on macOS and on the host sidecar.feed.py,pairing.py,outbox.py,skills_list.py,uploads.py,media.py— the worker endpoints (make_router(auth, …)).run_errors.py— the typed run errors every harness shares (classify,error_detail,run_failure,LoginError).- (
stop_guard.py— the Stop hook injected into every claude run, see below — andturn_hook.py/conv_ref_hook.py— the account-wide no-op Stop hook and conv-ref prompt hook, installed at the driver's startup — are the harness-claude plugin's since 2026-11-26.SIDECAR_TURN_HOOK=0/SIDECAR_CONV_REF_HOOK=0still disable them.) bash_diff.py— the Bash PreToolUse/PostToolUse hook pair injected into every claude run: what each Bash call changed on disk, printed as{"bashDiff": …}into the transcript (see the mainCLAUDE.md→ "What a Bash call changed"). Files only since 2026-11-27: commits are thecommitsplugin's git shim.path_shims.py— live plugins'pathShims(backendplugins/path_shims.py):apply(), called bylaunch._launchfor every harness, writes a POSIX-sh wrapper per shim under~/.cache/ai-agent/shims/bin[-guest]/(SIDECAR_SHIMS_DIR) and puts it first on the run's PATH — a trigger-word argument runs the plugin's script (python -I), anything elseexecs the real command — and exportsAIA_SESSION_ID,AIA_REPORT_SPOOLand, on the lab,AIA_REPORT_URL+AIA_REPORT_TOKEN. Its spool drain (every 20 s) sends a report a run couldn't: into the outbox on a worker, to the hub on the lab. Off withSIDECAR_PLUGIN_HOOKS=0.aia_report.py— the stdlib helper a shim script imports (AIA_REPORT_PY):report(event, summary, blob)→ the hub (lab) or the outbox's one-shotreportkind (worker), else the spool. Never raises, never prints, ≤ 2 s.complete.py—/complete: one short answer from any model (a harness driver'scomplete(), the EVOX2 or OpenRouter over HTTP), host only — theconversation-labelsplugin's titles and action badges.transcript_v1.py— what the harness plugins' mirrors share (writing v1: the header, the dedup keys, a file from before v1 continued behind a v1 header, the hub's text conventions and tables).
The four harnesses (claude, pi, opencode, agy) and the plan-usage readers are not here: they are the harness-* / provider-* plugins of ~/projects/ai-agent-plugins (see "Harness drivers" below).
Endpoints
GET /health→{ok, cwd, claude, accounts, defaultAccount}GET /accounts(Bearer auth) → each account'sclaude auth status(loggedIn,email,orgName,subscriptionType), cached 60s, plus thependingLoginbelow when one is waiting.POST /accounts/{id}/login{email?}→{loginId, url, startedAt, expiresAt}— starts a headlessclaude auth login --claudeaiunder the account's env and answers the OAuth sign-in URL. One login per account; killed after 10 min (SIDECAR_LOGIN_TTL_S).POST /accounts/{id}/login/code{code}→ the freshauth status— pipes thecode#statethe sign-in page ends on into the waiting CLI.400 bad_code(malformed, or a#statefrom another attempt) keeps the login pending;502 login_failedends it.DELETE /accounts/{id}/login→{cancelled}.POST /accounts/{id}/logout→claude auth logout+ the fresh status.POST /spawn(Bearer auth){prompt, sessionId?, model?, cwd?, account?}→{sessionId, pid, log}— spawns detached, returns immediately.POST /resume(Bearer auth){sessionId, prompt, model?, cwd?, account?}→{sessionId, pid, log}— continues an existing conversation by runningclaude -p <prompt> --resume <sessionId>. Reuses the original session id, so the new turns append to the same transcript and stream into the open conversation.--resumeis directory-scoped, so pass the session's originalcwd.POST /interrupt(Bearer auth){sessionId}→{sessionId, pid, signal, ok}— sends the run's process group aSIGINT(like Ctrl+C), so Claude aborts the turn, writes a[Request interrupted by user]marker and exits.404if no live process is tracked for that session.POST /message(Bearer auth){sessionId, prompt}→{sessionId, pid, delivered: "inbox"}— delivers a follow-up into a live run without stopping it, through the CLI's per-session inbox socket (<config dir>/sessions/<pid>.json→messagingSocketPath; runs are launched withcrossSessionInbound: accept). The model reads it between tool calls, or at once when idle-waiting, and its background work survives.404 not_runningwhen no process is live (do a plain/resume),409 inbox_unavailablewhen the run can't take it (a pi run, an older CLI — fall back to/resumewithforce). The text is prefixed (INBOX_PREFIX) because the CLI records it as a peer message; the backend's parser strips both.POST /complete(Bearer auth, host only){system, prompt, model, harness?, account?, fallbackModel?, fallbackHarness?, fallbackAccount?, wakeLocal?, timeout?}→{text, model, harness, account, usage?, costUsd?, fallbackUsed, primaryError?}— one short answer, no transcript, no tools:claude -p --no-session-persistence/agy --print/opencode runon a throwaway database through each driver's optionalcomplete(), or the EVOX2's / OpenRouter's chat API directly.wakeLocal: falsenever wakes the EVOX2 or loads a model: asleep → the fallback at once.usagecomes back in Anthropic's shape for the hub's price book.GET /media?path=<absolute path>(Bearer auth, workers only) → the image's bytes — what the hub's Original ↗ link on an image card serves at full size (the card itself shows the transcript's copy). Raster images only (png/jpeg/gif/webp, judged by a symlink's target), up toWORKER_MEDIA_MAX_BYTES(50 MB);404otherwise,409on the host sidecar.
Background work in a headless run
A claude -p process ends when the model ends its turn. Plain Bash run_in_background tasks die with it at once (the CLI's local_bash tasks are
excluded from its exit wait); subagents and Monitors are waited for, but only up
to CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS (CLI default 10 min). The sidecar
therefore launches every claude run with:
CLAUDE_CODE_PRINT_BG_WAIT_CEILING_MS=SIDECAR_BG_WAIT_CEILING_MS(default7200000, 2 h;0= wait indefinitely;""= the CLI default);--settingscarrying a Stop hook,stop_guard.py(harness-claude's): while a running plain background shell is left, it holds the stop — polling the task'stasks/<id>.outputfor the CLI's[exited with code N]marker, no API call — then answersblockwith "your task finished, its output is at …". Monitors are excluded. One hold lasts at mostSTOP_GUARD_MAX_WAIT_S(3300 s) under the hook'sSIDECAR_STOP_GUARD_TIMEOUT_S(3600);SIDECAR_STOP_GUARD=0disables it. The hook'sstop-guard: …lines go tologs/<sid>.guard.lognext to the run log (the CLI keeps a hook's stderr to itself;STOP_GUARD_STATE_DIR=LOG_DIRin the run env); the hold shows in the viewer as a compact held tag.--settingsalso carrying the Bash diff hooks,bash_diff.py pre|post(PreToolUse/PostToolUse, matcherBash, timeout 30 s): git snapshots of the repo a command runs in, before and after, through a private index + object store under~/.cache/ai-agent/bash-diff/; post prints the diff for the transcript. A scoped run's commands add--within <writeDir>.SIDECAR_BASH_DIFF=0disables them.- A follow-up during a hold. The inbox socket accepts and drops a message while the session sits in a Stop hook, so
/messagechecks for the hook'slogs/<sid>.holdmarker first and, when present, leaves the text inlogs/<sid>.inbox/(answersdelivered: "hold"); the hook polls that mailbox, ends the hold at once and relays the text in its block reason, fenced between<<<USER MESSAGE>>>/<<<END USER MESSAGE>>>— the viewer shows it as the user's own turn — and asks the model to answer, then end its turn again so the hold resumes for what is still running.
Per-session stdout/stderr is captured under logs/<sessionId>.log; the pid is
recorded in logs/<sessionId>.pid so /interrupt can find the run.
Errors are {detail: {message, kind, hint?, account?}}. kind (from
run_errors.classify): auth, rate_limit, cli_outdated, overloaded,
network, unknown, and for the login routes bad_code, login_failed,
login_expired, login_timeout. A run that dies on launch is read from the
CLI's JSON result line ("Not logged in · Please run /login") instead of
echoing that line raw.
Headless login (harness-claude plugin: sidecar/cli.py)
With no TTY, claude auth login prints an authorize URL whose redirect is
Anthropic's manual code page and blocks on stdin at Paste code here if prompted >. Signing in (any device) ends on a page showing <code>#<state>;
written to the CLI's stdin it's exchanged for tokens in the account's config
dir. A code without #state → Invalid code… and the CLI re-prompts; a wrong
one → exit 1 Login failed: Request failed with status code 400. The sidecar
checks the pasted #state against the URL's before piping it, and also accepts
the whole callback URL (…?code=…&state=…). A pending login lives only in the
sidecar process — restarting it drops the login.
Accounts (personal vs work)
A claude run launches on one Claude login. The default account is the CLI's own
config (~/.claude); SIDECAR_ACCOUNTS=work=~/.claude-work (in the unit, written
by install.sh) declares more, each exported per run as CLAUDE_CONFIG_DIR.
account on /spawn, /resume and /fork picks one — resume and fork must pass
the account the session started on, since its transcript lives only in that
account's projects/. A non-default account whose dir has no .credentials.json
answers 409 (never a fallback onto the default login), ANTHROPIC_API_KEY is
stripped from every run once accounts are declared, and --remote-control is only
added for the default account. The account is recorded in the pidfile and listed
by /sessions.
opencode accounts
SIDECAR_OPENCODE_ACCOUNTS=chatgpt-work=default declares the opencode harness
on this runner: an id the hub knows (backend/accounts) → default
(opencode's own ~/.local/share/opencode) or a dir whose opencode.db the
runs use. With it, harness: "opencode" on /spawn, /resume and /fork
runs opencode run --standalone (OPENCODE_BIN, SIDECAR_OPENCODE_MODEL
gpt-6-sol, SIDECAR_OPENCODE_EFFORT high, SIDECAR_OPENCODE_INSTRUCTIONS the
CLAUDE.md files), /accounts lists its login, /accounts/<id>/login starts
the device-code login (GET polls it), the mirror and usage threads start,
/feed lists the mirror as @opencode/<account>/… and /opencode/usage
serves the usage snapshots. State lives in SIDECAR_OPENCODE_DIR
(~/.opencode-runner).
Manage
systemctl --user status claude-sidecar
systemctl --user restart claude-sidecar
journalctl --user -u claude-sidecar -f
/ask-form — the standalone ask-form tool's forms (askform.py)
Agents ask forms with ask-form;
its serve keeps them on this machine behind a loopback admin API the hub
can't reach. The sidecar proxies it under the hub's bearer — GET /ask-form/health, GET /ask-form/forms[?status=], GET /ask-form/forms/{id} [?fields=1], POST /ask-form/forms/{id}/revoke|close — one HTTP call each
to http://127.0.0.1:7461 with the admin token from
~/.config/ask-form/admin-token (ASK_FORM_ADMIN_URL / ASK_FORM_ADMIN_TOKEN
/ ASK_FORM_CONFIG as the CLI reads them), ids regex-checked, never a shell.
503 askform_missing when the tool isn't set up here, askform_down when
its server is. POST /ask-form/events (loopback or SIDECAR_BIND, no
bearer) is where a worker's ask-form serve --events-url posts; each event
becomes an outbox askform item (afe_ id, applied on the hub's ack).
Harness drivers and usage readers (typed plugins, Wave 1B)
Runs, account routes and plan-usage reads go through two registries instead of
hard-coded per-harness branches (spec: ~/homelab/data/log/2026-11-26-ai-agent-typed-plugins-spec.md §3):
harness_base.py— theSidecarHarness/SidecarUsageReadercontracts and theSidecarContexta driver gets.harness_loader.py— the live harness drivers, loaded fromSIDECAR_LIVE_HARNESSES_DIR(host/data/plugins/live-harnesses, worker~/.ai-agent-worker/harnesses;index.jsonor a scan of*/plugin.json). Each driver module is imported assidecar_ext.harness.<plugin>.<module>;reload()swaps atomically, rolls back on any import/validation/startup error ({ok: false, rolledBack: true, error}) and copies a good load to<dir>.lkg(used at boot when the live dir is missing or broken).usage_loader.py— the same for provider usage readers (SIDECAR_LIVE_PROVIDERS_DIR);GET /usage/{vendor}plus the legacy/claude/usage,/opencode/usage,/agy/usage.- Strict plugin-only: no built-in driver. A harness no plugin provides is
a 409
harness_unavailableon/spawn//resume//fork(validate.harness_unavailable; only a malformed id is a 400invalid harness) — on a worker with no harness at all the message says its lab sync hasn't brought them yet. A worker's harnesses come from the hub's/sync(labsync.py);/health'spluginSyncsays which version of those maps it holds and runs, and a same-hash/syncstill re-applies maps it lacks (labsync.plugins_stale). Cold boot never comes up empty: a live dir never materialized (noindex.json, no plugin dir) — or one that fails while nothing is loaded — falls back to its.lkgcopy, then on the host (not a worker) to the seed plugins,SIDECAR_SEED_PLUGINS_DIR(default~/projects/ai-agent-plugins/plugins). A provider with no reader (provider-evox2) loads no code but its manifest +config.jsonare kept:usage_loader.provider_configs()/usage_loader.evox2()— the EVOX2's servers and Wake-on-LAN target forlocal_ready/local_room/gen_progress.harness_loader.module(h, name)is a loaded plugin's own submodule (gen_progress reads the opencode database through it). routes_harnesses.py—GET /harnesses,POST /harnesses/reload {force}.mirror_base.py— what the transcript mirrors share (cwd slug, git branch, timestamps, atomic state file, the poll thread).mcp_base.py+routes_mcp.py—/mcp-servers: the MCP servers the hub'smcp-serversplugin sets up on this machine, per login (harness:account). The core is generic (canonical config + hash, the managed storemcp-managed.json, apply, the 30-min background listing, the ptymcp loginpaste-back, theinitializeprobes); each harness plugin's driver answersmcp_adapter()with its ownsidecar/mcp.py(Claude'sclaude mcp …, opencode's per-runOPENCODE_CONFIG_CONTENT, agy'smcp_config.json). A driver without one has no MCP servers here./sync(labsync.py) also takesharnesses/providers({pluginId: {hash, files: {rel: base64}}}), written as a version under the loaders' roots and reloaded — a failed reload swaps back and answers 409. A guest's computer keeps onlyguestAllowedharnesses and no providers.