Files
ai-agent/sidecar/run_errors.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

114 lines
4.7 KiB
Python

"""
Typed run errors — one vocabulary for "why did a run fail", shared by every
harness: the core's launch errors (a run's log tail), the routes' 4xx bodies,
and the harness plugins' drivers (harness-opencode / harness-agy read it as
the sidecar module ``run_errors``).
``error_detail`` is the HTTPException body every caller reads the same way:
``{message, kind, hint?, account?}``. ``run_failure`` turns what a run
printed before dying into ``(message, kind)``. ``LoginError`` is a login step
that failed, with the HTTP status to answer.
(Split out of the old ``claude_cli.py`` when the harnesses moved into plugins:
the claude login flow is the harness-claude plugin's own ``cli.py``.)
"""
from __future__ import annotations
import json
import re
# ---- error classification --------------------------------------------------
# One vocabulary for "why did claude fail", shared by launch errors (the CLI's
# result line in a run log) and the transcript's API-error turns (the viewer
# maps the transcript's own `error` field the same way).
KINDS = ("auth", "rate_limit", "cli_outdated", "overloaded", "network",
"unknown")
_KIND_PATTERNS: list[tuple[str, re.Pattern]] = [
("auth", re.compile(
r"not logged in|please run /login|failed to authenticate|oauth"
r".*(expired|revoked|refresh)|invalid api key|authentication_failed"
r"|\b401\b", re.I)),
("rate_limit", re.compile(
r"session limit|usage limit|rate.?limit|weekly limit|\b429\b", re.I)),
("cli_outdated", re.compile(
r"does not support this model|newer is required|claude update", re.I)),
("overloaded", re.compile(r"overloaded|\b529\b|\b5\d\d\b", re.I)),
("network", re.compile(
r"connection (lost|error|refused)|ECONNRESET|ETIMEDOUT|ENOTFOUND"
r"|fetch failed", re.I)),
]
# The transcript's `error` field (CLI's own names) → our kind.
_API_KINDS = {"authentication_failed": "auth", "rate_limit": "rate_limit",
"server_error": "overloaded", "overloaded": "overloaded"}
HINTS = {
"auth": "The account's Claude login is missing or expired — log in again "
"from Settings → Claude accounts.",
"rate_limit": "The subscription's usage limit is reached — wait for the "
"reset or run on the other account.",
"cli_outdated": "The claude CLI on the host is too old for this model — "
"run `claude update`.",
"overloaded": "Anthropic's API is overloaded or erroring — retry shortly.",
"network": "The connection to Anthropic's API dropped — retry.",
}
def classify(text: str | None, api_error: str | None = None) -> str:
"""The error kind for a failure message (and the CLI's own error name)."""
if api_error in _API_KINDS:
return _API_KINDS[api_error]
for kind, rx in _KIND_PATTERNS:
if rx.search(text or ""):
return kind
return "unknown"
def error_detail(message: str, *, kind: str | None = None,
account: str | None = None, **extra) -> dict:
"""An HTTPException detail every caller can read the same way:
``{message, kind, hint?, account?}``."""
kind = kind or classify(message)
out = {"message": message, "kind": kind}
if HINTS.get(kind):
out["hint"] = HINTS[kind]
if account:
out["account"] = account
out.update({k: v for k, v in extra.items() if v is not None})
return out
def run_failure(text: str) -> tuple[str, str]:
"""(message, kind) for what a run printed before dying.
``claude -p --output-format json`` ends with a single JSON ``result`` line
(``{"type":"result","is_error":true,"result":"Not logged in · Please run
/login",…}``) — dumping that line raw is what the composer used to show.
Prefer its ``result`` text; fall back to the last plain line."""
lines = [ln.strip() for ln in (text or "").splitlines() if ln.strip()]
for ln in reversed(lines):
if not ln.startswith("{"):
continue
try:
rec = json.loads(ln)
except ValueError:
continue
if isinstance(rec, dict) and rec.get("type") == "result":
msg = str(rec.get("result") or rec.get("terminal_reason")
or "claude failed")[:400]
status = rec.get("api_error_status")
return msg, classify(f"{msg} {status or ''}")
msg = (lines[-1][:400] if lines else "(no output)")
return msg, classify(msg)
class LoginError(Exception):
"""A login step failed; ``status`` is the HTTP code to answer with."""
def __init__(self, status: int, message: str, kind: str = "login"):
super().__init__(message)
self.status, self.message, self.kind = status, message, kind