Files
gabrielvidalandClaude Opus 5.5 3ec287a493 refactor(conversations): turn parse.py into a package (pass a: pure moves)
conversations/parse.py (2,449 lines) becomes conversations/parse/:
records (JSONL records, timestamps, clipped blocks, _item), usertext (inbox /
cancel / relay / author / held / slash / skill / image / compact text), tools
(buckets, sub-labels, project / service / worktree / commit evidence,
lifecycle + deploys), errors (API-error kinds, limit resets), usage (delta /
estimate / cost-state helpers), turns (turn-end records), state
(ParserState + parse_conversation, unchanged) and cut (find_cut_line).

Code moved verbatim. The package re-exports every name the module had, and
its __all__ is exactly what `from .parse import *` exported before, so the
`conversations` namespace is identical (checked name by name).

Verified against 57a4d8ee: parse-ab 500 files x 2 modes 0 differing,
--chunked 0 mismatches, pricing-dump identical, test_parse_fixtures OK.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 23:34:14 +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 (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()