Files
gabrielvidalandClaude Opus 5.5 c3945fe965 refactor: retire core runner/ — pi's runner lives in the harness-pi plugin
runner/ (cli.mjs, extensions/folder-permissions.ts, test, README) was a
byte-for-byte duplicate of the harness-pi plugin's runner/, kept only as the
driver's fallback through the sidecar's config.RUNNER_BIN.

- delete runner/ and sidecar config.RUNNER_BIN
- scripts/test.py: drop the `runner` suite (it runs in ai-agent-plugins now)
- scripts/ab: the pi mirror replay uses a tree's runner/ when it has one
  (refs before this), else the plugin's (AB_PI_RUNNER)
- CLAUDE.md / docs / comments point at harness-pi's runner
- sidecar/local-model.md stays (harness-opencode's LOCAL_MODEL_GUIDE)

Merge only after harness-pi 1.1.0 is installed on the lab: harness-pi 1.0.x
reads config.RUNNER_BIN and would fail every pi run on this core.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 11:44:54 +01:00

125 lines
5.8 KiB
Python

"""API-error turns: their kind, a usage limit's reset time, the pi runner's
old empty error turns, and the CLI's placeholder models."""
import datetime
import os
import re
def _real_model(model: str | None) -> bool:
"""False for Claude Code's own placeholder models (`<synthetic>`, …).
Messages the CLI fabricates itself (API-error notices, "No response
requested." fillers) carry a bracketed pseudo-model. It is not a model the
conversation ran on, so it must never become one of its model tags."""
return bool(model) and not model.startswith("<")
# The claude CLI's `error` field on an API-error turn → the viewer's kind (the
# same vocabulary as the sidecar's claude_cli.classify, which types launch
# failures). Text patterns cover older CLIs and `unknown`/unset fields.
# The pi runner (harness-pi's runner/cli.mjs) adds its own fields for what a hosted or local
# provider answers: a refused API key (OpenRouter's — not a Claude login, so
# not `auth` and its Log in button), a full context window, a dropped stream.
_API_ERROR_FIELD = {"authentication_failed": "auth", "rate_limit": "rate_limit",
"server_error": "overloaded", "overloaded": "overloaded",
"invalid_api_key": "api_key", "context_exceeded": "context",
"network_error": "network"}
_API_ERROR_TEXT = [
("api_key", re.compile(r"api key (expired|revoked)|key expired|user not found", re.I)),
("auth", re.compile(r"not logged in|please run /login|failed to authenticate"
r"|oauth.*(expired|revoked|refresh)|invalid api key", re.I)),
("rate_limit", re.compile(r"session limit|usage limit|rate.?limit"
r"|weekly limit", re.I)),
("cli_outdated", re.compile(r"does not support this model|newer is required"
r"|claude update", re.I)),
("context", re.compile(r"context (size|length|window)\b.{0,40}(exceed|too)"
r"|maximum context length|prompt is too long", re.I)),
("network", re.compile(r"connection (lost|error|refused)|ECONNRESET"
r"|ETIMEDOUT|fetch failed", re.I)),
("overloaded", re.compile(r"overloaded|API Error: 5\d\d", re.I)),
]
def legacy_error_turn(o: dict) -> dict:
"""A pi turn that failed before the runner wrote its error (2026-11-06):
an assistant record with ``stop_reason: "error"`` and nothing in it — read
as the API-error turn it was, on the ``<synthetic>`` model so the failed
model doesn't become the one the conversation ran on. Anything else is
returned as is."""
msg = o.get("message") if o.get("type") == "assistant" else None
if not isinstance(msg, dict) or msg.get("stop_reason") != "error" \
or o.get("isApiErrorMessage") or msg.get("content"):
return o
model = msg.get("model")
where = f" ({model})" if _real_model(model) else ""
return {**o, "isApiErrorMessage": True, "error": "unknown",
"message": {**msg, "model": "<synthetic>", "content": [{
"type": "text",
"text": f"API Error{where}: the model call failed — this run didn't "
"record why (pi runner before 2026-11-06)"}]}}
def api_error_kind(field: str | None, text: str | None) -> str:
"""The kind of a transcript API-error turn (``isApiErrorMessage``)."""
if field in _API_ERROR_FIELD:
return _API_ERROR_FIELD[field]
for kind, rx in _API_ERROR_TEXT:
if rx.search(text or ""):
return kind
return "unknown"
# When a usage-limit turn says the window reopens: "You've hit your session
# limit · resets 2:20pm (Europe/Paris)", "… weekly limit · resets Oct 23, 8pm
# (Europe/Paris)", or an older CLI's "Claude AI usage limit reached|<epoch>".
_RESETS_RX = re.compile(
r"resets\s+(?:(?P<mon>[A-Za-z]{3})[a-z]*\s+(?P<day>\d{1,2}),?\s+(?:at\s+)?)?"
r"(?P<h>\d{1,2})(?::(?P<m>\d{2}))?\s*(?P<ap>am|pm)\b"
r"(?:\s*\((?P<tz>[A-Za-z_]+(?:/[A-Za-z_+-]+)*)\))?", re.I)
_RESETS_EPOCH_RX = re.compile(r"limit reached\|(\d{10})\b", re.I)
_MONTHS = {m: i for i, m in enumerate(
("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"), 1)}
def limit_resets_at(text: str | None, at: str | None) -> float | None:
"""The epoch second a usage-limit turn says the limit resets — the first
such wall-clock time after the turn itself (``at``, its ISO timestamp), in
the zone the text names (else the lab's ``TZ``). None when it names none."""
if not text:
return None
m = _RESETS_EPOCH_RX.search(text)
if m:
return float(m.group(1))
m = _RESETS_RX.search(text)
if not m:
return None
from zoneinfo import ZoneInfo
try:
tz = ZoneInfo(m.group("tz") or os.environ.get("TZ") or "Europe/Paris")
except Exception:
tz = ZoneInfo("Europe/Paris")
try:
base = datetime.datetime.fromisoformat((at or "").replace("Z", "+00:00"))
except ValueError:
return None
if base.tzinfo is None:
base = base.replace(tzinfo=datetime.timezone.utc)
local = base.astimezone(tz)
hour = int(m.group("h")) % 12 + (12 if m.group("ap").lower() == "pm" else 0)
minute = int(m.group("m") or 0)
mon = _MONTHS.get((m.group("mon") or "").lower()[:3])
try:
if mon:
t = local.replace(month=mon, day=int(m.group("day")), hour=hour,
minute=minute, second=0, microsecond=0)
if t < local - datetime.timedelta(days=1): # "Jan 2" seen in December
t = t.replace(year=t.year + 1)
else:
t = local.replace(hour=hour, minute=minute, second=0, microsecond=0)
if t <= local:
t += datetime.timedelta(days=1)
except ValueError:
return None
return t.timestamp()