Files
ai-agent/sidecar/callprobe.py

533 lines
21 KiB
Python

"""
The call probe, through **agent-probe** — the standalone binary
(github.com/GabrielVidal1/agent-probe, claude-probe's successor) that measures
what each shell call of a coding agent — Claude Code, opencode, Codex, pi —
and every process it started, cost: CPU, peak RSS, disk I/O, GPU and exit code
per process, a subagent's calls attributed to it, plus the turn boundaries.
Exact from the kernel on Linux (its CO-RE eBPF program, loaded under the file
capabilities `sudo agent-probe setup-kernel` gives it) and from kqueue on
macOS (no setup); sampled from /proc otherwise.
This module is the runner's side of it:
- **the binary**: ``SIDECAR_AGENT_PROBE``, else the capable copy
``/usr/local/bin/agent-probe``, else ``~/.local/bin`` / ``PATH``; missing,
the latest release is downloaded into ``~/.local/bin`` (checksum-checked;
``SIDECAR_AGENT_PROBE_FETCH=0`` turns that off) — how paired workers get
it without reinstalling. The ``SIDECAR_CLAUDE_PROBE*`` names still work;
- **claude-probe's records, once** (``agent-probe migrate``, ids kept so the
hub's cursor carries on): when its store exists and agent-probe's doesn't,
its daemon is stopped and its store copied before anything else;
- **its hooks** in every account's ``settings.json`` and the hooks / plugins of
every other agent on the machine (``agent-probe install --config-dir …``:
claude-probe's hooks are replaced in place), and the hooks of the Python
probe before them taken out;
- **a daemon kept up** (``agent-probe daemon --idle 0``: the hook would start
one on demand anyway, this spares the first call that second);
- **``GET /callmeta``** — the hub's pull — answered by the daemon over its unix
socket, or by ``agent-probe export`` when no daemon runs. The records are
the same ``call`` / ``mark`` versions the hub has ingested since the probe
began (backend ``perf/calls.py``), plus each one's ``agent``.
``SIDECAR_CALLPROBE=0`` takes the hooks out and answers ``/callmeta`` empty.
"""
from __future__ import annotations
import hashlib
import http.client
import json
import os
import pathlib
import platform
import shutil
import signal
import socket
import subprocess
import threading
import time
import urllib.request
from fastapi import APIRouter, Header, Query
from validate import _auth
def _env(name: str, default: str | None = None) -> str | None:
"""``SIDECAR_AGENT_PROBE…``, else the claude-probe-era ``SIDECAR_CLAUDE_PROBE…``."""
v = os.environ.get("SIDECAR_AGENT_PROBE" + name)
if v is None:
v = os.environ.get("SIDECAR_CLAUDE_PROBE" + name)
return default if v is None else v
ENABLED = os.environ.get("SIDECAR_CALLPROBE", "1") not in ("0", "false", "")
FETCH = _env("_FETCH", "1") not in ("0", "false", "")
RELEASES = _env("_RELEASES", "https://github.com/GabrielVidal1/agent-probe/releases")
# The oldest agent-probe this sidecar works with: 0.1.2 knows Claude Code's
# Code Mode — its scripts group their calls (a call's "script"), the Claude
# Code its Code Mode restart re-runs by its versioned path is still measured,
# and its hooks never block a call from code when they fail. (0.1.1 recorded
# a daemonized process's fork parent as its ppid.)
# A fetched copy (~/.local/bin) older than this is replaced by the latest
# release; the root-owned capable copy is upgraded by hand (setup-kernel).
MIN_VERSION = (0, 1, 2)
HOME = pathlib.Path(os.path.expanduser("~"))
KERNEL_COPY = pathlib.Path("/usr/local/bin/agent-probe")
LOCAL_COPY = HOME / ".local" / "bin" / "agent-probe"
# the Python probe's hooks (before claude-probe): taken out of settings.json
OLD_MARK = "ai-agent call probe"
OLD_EVENTS = ("PreToolUse", "PostToolUse", "UserPromptSubmit", "Stop",
"SubagentStart", "SubagentStop")
def socket_path() -> str:
"""Where the daemon listens (agent-probe's paths.Socket)."""
if os.environ.get("AGENT_PROBE_SOCK"):
return os.environ["AGENT_PROBE_SOCK"]
if platform.system() == "Darwin":
return str(HOME / "Library" / "Caches" / "agent-probe" / "probe.sock")
return str(HOME / ".cache" / "agent-probe" / "probe.sock")
def binary() -> str | None:
"""The agent-probe the hooks and this module run."""
env = _env("")
if env:
return env if os.access(env, os.X_OK) else None
for p in (KERNEL_COPY, LOCAL_COPY):
if p.is_file() and os.access(p, os.X_OK):
return str(p)
return shutil.which("agent-probe")
def _asset() -> str | None:
osname = {"Linux": "linux", "Darwin": "darwin"}.get(platform.system())
arch = {"x86_64": "amd64", "amd64": "amd64", "arm64": "arm64",
"aarch64": "arm64"}.get(platform.machine().lower())
return f"agent-probe-{osname}-{arch}" if osname and arch else None
def fetch(dest: pathlib.Path = LOCAL_COPY, timeout: float = 60) -> str | None:
"""Download the latest release for this machine into ``dest`` (checked
against the release's checksums.txt). None when there is nothing to fetch."""
asset = _asset()
if asset is None:
return None
base = f"{RELEASES}/latest/download"
with urllib.request.urlopen(f"{base}/checksums.txt", timeout=timeout) as r:
sums = r.read().decode()
want = next((line.split()[0] for line in sums.splitlines()
if line.split()[-1:] in ([asset], ["*" + asset])), None)
if not want:
raise RuntimeError(f"{asset} is not in the release's checksums.txt")
with urllib.request.urlopen(f"{base}/{asset}", timeout=timeout) as r:
data = r.read()
if hashlib.sha256(data).hexdigest() != want:
raise RuntimeError(f"checksum mismatch for {asset}")
dest.parent.mkdir(parents=True, exist_ok=True)
tmp = dest.with_name(dest.name + ".tmp")
tmp.write_bytes(data)
tmp.chmod(0o755)
os.replace(tmp, dest)
return str(dest)
def version_of(bin_: str) -> tuple[int, ...] | None:
"""``agent-probe version`` as a tuple (v0.2.0-3-gabc → (0, 2, 0)); None
when it can't say (a dev build counts as new)."""
try:
r = _run([bin_, "version"], timeout=10)
v = json.loads(r.stdout).get("version") or ""
except (OSError, ValueError, subprocess.SubprocessError):
return None
head = v.lstrip("v").split("-")[0].split(".")
try:
return tuple(int(x) for x in head[:3])
except ValueError:
return None
def outdated(bin_: str) -> bool:
v = version_of(bin_)
return v is not None and v < MIN_VERSION
def remove_old_hooks(path: pathlib.Path) -> bool:
"""Take the Python probe's hooks out of one settings.json."""
path = path.resolve()
if not path.exists():
return False
data = json.loads(path.read_text())
hooks = data.get("hooks") if isinstance(data, dict) else None
if not isinstance(hooks, dict):
return False
changed = False
for event in OLD_EVENTS:
groups = hooks.get(event)
if not isinstance(groups, list):
continue
keep = [g for g in groups if not (isinstance(g, dict) and any(
OLD_MARK in str(h.get("command") or "") for h in g.get("hooks") or []
if isinstance(h, dict)))]
if len(keep) != len(groups):
changed = True
if keep:
hooks[event] = keep
else:
del hooks[event]
if not changed:
return False
if not hooks:
data.pop("hooks", None)
mode = path.stat().st_mode & 0o777
tmp = path.with_name(path.name + ".ai-agent.tmp")
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode)
with os.fdopen(fd, "w") as f:
f.write(json.dumps(data, indent=2) + "\n")
os.replace(tmp, path)
return True
def _run(args: list[str], timeout: float = 30) -> subprocess.CompletedProcess:
return subprocess.run(args, capture_output=True, text=True, timeout=timeout)
def install(bin_: str) -> None:
"""agent-probe's hooks in every config this runner serves, and the hooks /
plugins of the other agents found here (in or out — ``uninstall`` takes
claude-probe's out too)."""
from config import claude_config_dirs # noqa: PLC0415
verb = "install" if ENABLED else "uninstall"
args = [bin_, verb]
for d in claude_config_dirs():
try:
if remove_old_hooks(d / "settings.json"):
print(f"[callprobe] old Python hooks removed from {d / 'settings.json'}", flush=True)
except (OSError, ValueError) as e:
print(f"[callprobe] {d / 'settings.json'}: {e}", flush=True)
args += ["--config-dir", str(d)]
try:
r = _run(args, timeout=120) # trusting Codex's hooks may take 30 s
if r.returncode != 0:
print(f"[callprobe] {verb}: {(r.stderr or r.stdout).strip()[:300]}", flush=True)
except (OSError, subprocess.SubprocessError) as e:
print(f"[callprobe] {verb}: {e}", flush=True)
def _state_dir() -> pathlib.Path:
if os.environ.get("AGENT_PROBE_STATE_DIR"):
return pathlib.Path(os.environ["AGENT_PROBE_STATE_DIR"])
if platform.system() == "Darwin":
return HOME / "Library" / "Application Support" / "agent-probe"
return HOME / ".local" / "state" / "agent-probe"
def _legacy() -> tuple[pathlib.Path, str]:
"""claude-probe's state dir and socket (agent-probe's paths.Legacy)."""
if platform.system() == "Darwin":
return (HOME / "Library" / "Application Support" / "claude-probe",
str(HOME / "Library" / "Caches" / "claude-probe" / "probe.sock"))
return HOME / ".local" / "state" / "claude-probe", str(HOME / ".cache" / "claude-probe" / "probe.sock")
def stop_legacy_daemon(sock: str, wait: float = 15) -> bool:
"""Stop claude-probe's daemon if one answers on ``sock`` (its pid from
``GET /health``) and wait for the socket to go quiet."""
status, body = daemon_get("/health", sock=sock, timeout=2)
pid = (body or {}).get("pid") if status == 200 else None
if not pid:
return False
try:
os.kill(int(pid), signal.SIGTERM)
except (OSError, ValueError) as e:
print(f"[callprobe] claude-probe's daemon (pid {pid}): {e}", flush=True)
return False
end = time.time() + wait
while time.time() < end:
if daemon_get("/health", sock=sock, timeout=0.5)[0] == 0:
return True
time.sleep(0.2)
return False
def migrate(bin_: str, attempts: int = 3) -> bool:
"""Once: claude-probe's store into agent-probe's (``agent-probe migrate``,
record ids kept — the hub's cursor carries on). Only while claude-probe's
store exists and agent-probe's doesn't; claude-probe's daemon is stopped
first (a session's claude-probe hook may start it again in between: then
once more). Never raises — a failure is logged."""
old_state, old_sock = _legacy()
if not (old_state / "probe.db").exists() or (_state_dir() / "probe.db").exists():
return False
err = ""
for _ in range(attempts):
stop_legacy_daemon(old_sock)
try:
r = _run([bin_, "migrate", "--from", str(old_state)], timeout=900)
except (OSError, subprocess.SubprocessError) as e:
print(f"[callprobe] migrate: {e}", flush=True)
return False
if r.returncode == 0:
print(f"[callprobe] claude-probe migrated: {r.stdout.strip()[:300]}", flush=True)
return True
err = (r.stderr or r.stdout).strip()
if "still running" not in err:
break
print(f"[callprobe] migrate failed: {err[:300]}", flush=True)
return False
def stop_daemon(wait: float = 15) -> None:
"""Stop the running daemon (its pid is in its lock file) and wait for its
lock to be free, so the next one doesn't exit on it."""
import fcntl # noqa: PLC0415
import signal # noqa: PLC0415
import time # noqa: PLC0415
lock = _state_dir() / "daemon.lock"
try:
pid = int(lock.read_text().split()[0])
os.kill(pid, signal.SIGTERM)
except (OSError, ValueError, IndexError):
return
end = time.time() + wait
while time.time() < end:
try:
with open(lock, "a") as f:
fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
fcntl.flock(f, fcntl.LOCK_UN)
return
except OSError:
time.sleep(0.2)
def start_daemon(bin_: str) -> None:
"""Keep a daemon up (one per user: a second exits on its lock)."""
log = _state_dir() / "daemon.log"
log.parent.mkdir(parents=True, exist_ok=True)
with open(log, "a") as out:
subprocess.Popen([bin_, "daemon", "--idle", "0"], stdout=out, stderr=out,
stdin=subprocess.DEVNULL, start_new_session=True)
# Directories whose children are git worktrees (the homelab's
# scripts/new-worktree.sh puts them in ~/worktrees): agent-probe lists their
# repos' worktrees beside the ones the sessions' cwds lead to.
WORKTREE_ROOTS = [p for p in os.environ.get(
"SIDECAR_STORAGE_WORKTREE_ROOTS", os.environ.get("WORKTREES_ROOT") or str(HOME / "worktrees")
).split(":") if p]
def configure_storage(bin_: str) -> None:
"""agent-probe's storage tracking: the worktree roots this runner keeps."""
for root in WORKTREE_ROOTS:
if not os.path.isdir(root):
continue
try:
r = _run([bin_, "storage", "config", "--worktree-root", root, "--json"])
if r.returncode != 0: # a binary from before storage tracking
print(f"[callprobe] storage config: {(r.stderr or r.stdout).strip()[:200]}", flush=True)
return
except (OSError, subprocess.SubprocessError) as e:
print(f"[callprobe] storage config: {e}", flush=True)
return
def _startup() -> None:
# the Python probe's hooks go first, binary or not: they name a script
# that no longer runs anything (call_hook.py, a no-op kept for that)
from config import claude_config_dirs # noqa: PLC0415
for d in claude_config_dirs():
try:
if remove_old_hooks(d / "settings.json"):
print(f"[callprobe] old Python hooks removed from {d / 'settings.json'}", flush=True)
except (OSError, ValueError) as e:
print(f"[callprobe] {d / 'settings.json'}: {e}", flush=True)
bin_ = binary()
stale = bin_ is not None and pathlib.Path(bin_) == LOCAL_COPY and outdated(bin_)
if (bin_ is None or stale) and FETCH and ENABLED:
try:
bin_ = fetch()
print(f"[callprobe] fetched agent-probe → {bin_}", flush=True)
if stale:
stop_daemon() # the old one keeps its lock: the new binary's takes over
except Exception as e: # noqa: BLE001 — offline, no release yet
print(f"[callprobe] agent-probe {'outdated' if stale else 'not installed'}, fetch failed: {e}",
flush=True)
elif bin_ is not None and outdated(bin_):
print(f"[callprobe] {bin_} is older than {'.'.join(map(str, MIN_VERSION))} — upgrade it (setup-kernel)",
flush=True)
if bin_ is None:
return
if ENABLED:
try:
migrate(bin_) # before the hooks: nothing may write agent-probe's store yet
except Exception as e: # noqa: BLE001 — never fail the sidecar on it
print(f"[callprobe] migrate: {e}", flush=True)
install(bin_)
if ENABLED:
configure_storage(bin_)
start_daemon(bin_)
def start() -> None:
"""Sidecar startup — off the event loop (a fetch can take seconds)."""
threading.Thread(target=_startup, name="callprobe-setup", daemon=True).start()
# ── /callmeta ────────────────────────────────────────────────────────────────
class _UnixHTTP(http.client.HTTPConnection):
def __init__(self, path: str, timeout: float = 5):
super().__init__("probe", timeout=timeout)
self._path = path
def connect(self):
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
s.settimeout(self.timeout)
s.connect(self._path)
self.sock = s
def daemon_get(path: str, sock: str | None = None, timeout: float = 5) -> tuple[int, dict | None]:
"""GET from a daemon's API (agent-probe's, or the one on ``sock``):
(status, JSON) — (0, None) when none answers."""
try:
c = _UnixHTTP(sock or socket_path(), timeout=timeout)
c.request("GET", path)
r = c.getresponse()
raw = r.read()
c.close()
except (OSError, http.client.HTTPException):
return 0, None
try:
return r.status, json.loads(raw)
except ValueError:
return r.status, None
def daemon_post(path: str, body: dict, timeout: float) -> tuple[int, dict | None]:
"""POST to the daemon's API: (status, JSON) — (0, None) when none answers."""
try:
c = _UnixHTTP(socket_path(), timeout=timeout)
c.request("POST", path, body=json.dumps(body), headers={"Content-Type": "application/json"})
r = c.getresponse()
raw = r.read()
c.close()
try:
return r.status, json.loads(raw)
except ValueError:
return r.status, {"error": raw.decode(errors="replace")[:300]}
except (OSError, http.client.HTTPException):
return 0, None
def from_daemon(after: int, limit: int) -> dict | None:
try:
c = _UnixHTTP(socket_path())
c.request("GET", f"/callmeta?after={after}&limit={limit}")
r = c.getresponse()
body = r.read()
c.close()
return json.loads(body) if r.status == 200 else None
except (OSError, ValueError, http.client.HTTPException):
return None
def from_store(after: int, limit: int) -> dict | None:
bin_ = binary()
if bin_ is None:
return None
try:
r = _run([bin_, "export", "--after", str(after), "--limit", str(limit)], timeout=20)
return json.loads(r.stdout) if r.returncode == 0 else None
except (OSError, ValueError, subprocess.SubprocessError):
return None
router = APIRouter()
def _storage_call(path: str, body: dict, timeout: float) -> dict:
from fastapi import HTTPException # noqa: PLC0415
if not ENABLED:
raise HTTPException(503, "the call probe is off on this runner")
status, out = daemon_post(path, body, timeout)
if status == 0:
raise HTTPException(503, "agent-probe's daemon isn't running")
if status == 404:
raise HTTPException(501, "this runner's agent-probe has storage tracking off")
if status != 200:
raise HTTPException(502, (out or {}).get("error") or f"agent-probe answered {status}")
return out or {}
@router.post("/storage/rm")
def storage_rm(body: dict, authorization: str | None = Header(default=None)) -> dict:
"""Remove a session's scratch dir or a worktree — agent-probe decides
whether it is safe (``unsafe`` + why, unless ``force``)."""
_auth(authorization)
path = str(body.get("path") or "")
if not path.startswith("/"):
from fastapi import HTTPException # noqa: PLC0415
raise HTTPException(400, "an absolute path, please")
return _storage_call("/storage/rm", {"path": path, "force": bool(body.get("force")),
"dry": bool(body.get("dry"))}, timeout=320)
@router.get("/storage/config")
def storage_config_get(authorization: str | None = Header(default=None)) -> dict:
"""agent-probe's storage config here: extra roots, auto-clean, nudge."""
_auth(authorization)
return _storage_config([])
@router.post("/storage/config")
def storage_config_set(body: dict, authorization: str | None = Header(default=None)) -> dict:
"""Set the auto-clean days (0: off) and/or the nudge threshold."""
_auth(authorization)
args = []
if body.get("autoCleanDays") is not None:
args += ["--auto-clean", str(max(0.0, float(body["autoCleanDays"])))]
if body.get("nudgeAt") is not None:
n = float(body["nudgeAt"])
args += ["--nudge-at", "off" if n <= 0 else str(n)]
return _storage_config(args)
def _storage_config(args: list[str]) -> dict:
from fastapi import HTTPException # noqa: PLC0415
bin_ = binary()
if bin_ is None:
raise HTTPException(503, "agent-probe isn't installed on this runner")
try:
r = _run([bin_, "storage", "config", *args, "--json"])
except (OSError, subprocess.SubprocessError) as e:
raise HTTPException(502, str(e)) from e
if r.returncode != 0:
raise HTTPException(501 if "unknown command" in (r.stderr or "") else 400,
(r.stderr or r.stdout).strip()[:300])
return json.loads(r.stdout or "{}")
@router.post("/storage/scan")
def storage_scan(authorization: str | None = Header(default=None)) -> dict:
"""Measure everything now (agent-probe's full storage pass)."""
_auth(authorization)
return _storage_call("/storage/scan", {}, timeout=890)
@router.get("/callmeta")
def callmeta(after: int = Query(0, ge=0), limit: int = Query(500, ge=1, le=2000),
authorization: str | None = Header(default=None)) -> dict:
"""agent-probe's records after ``after`` (the hub keeps the cursor)."""
_auth(authorization)
if not ENABLED:
return {"records": [], "last": after, "enabled": False}
out = from_daemon(after, limit) or from_store(after, limit)
if out is None:
return {"records": [], "last": after, "enabled": False,
"error": "agent-probe isn't installed on this runner"}
return out