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

407 lines
18 KiB
Python

"""
Writing a v1 transcript — what the opencode and agy mirrors share
(``docs/transcript-format.md`` is the contract; harness-pi's ``runner/cli.mjs`` is
pi's own writer, in JavaScript).
A converter turns each thing its harness recorded into a **group** of v1
events — one key (``ocKey`` / ``agyKey``) per group, on its first event, so
the set of what a file holds is rebuilt from the file itself after a restart.
``Out`` appends groups to one file: the header first on a new file, a
``session`` event when the cwd or the branch moved, and — on a file the
converter wrote in the old Claude-Code-shaped format before (a conversation
from before v1, resumed) — a v1 header line ahead of its first v1 line, which
tells the hub's reader that every line from there on is v1.
**Steps are written whole**: a model step's ``call``, its blocks, then its
``usage``, in one append, once the model has finished the step — the hub
holds a step until its usage (or the next event) arrives, so a whole step
shows at once and a tool card shows while the tool runs.
The hub's reader of the old format interpreted text conventions (an
interrupt marker, a ``<command-name>`` record, an author tag…); a v1 event
says what it is instead. ``prompt_events`` turns a user message's text into
the events that reader made of it, with the same rules, so a v1 transcript
reads like the old one did. The tables below are copies of the hub's
(``backend/conversations/parse``): ``backend/test_converter_tables.py``
keeps them equal.
"""
from __future__ import annotations
import json
import os
import pathlib
import re
V = 1
STEP_TYPES = ("usage", "text", "thinking", "tool_call", "error")
# ── one line ─────────────────────────────────────────────────────────────────
# Flags whose absence means false, token counts whose absence means 0.
_FALSE_FLAGS = {"call": ("virtual", "failed", "empty"), "text": ("paused",),
"tool_settled": ("late",)}
_ZERO_TOKENS = ("cacheRead", "cacheWrite5m", "cacheWrite1h", "cacheWrite", "reasoning")
def compact(ev: dict) -> dict:
"""``ev`` without what says nothing (null, a false flag, a zero token
count) — the hub reads each as absent. A ``session`` event stays whole."""
if ev.get("t") == "session":
return ev
flags = _FALSE_FLAGS.get(ev.get("t"), ())
zeros = _ZERO_TOKENS if ev.get("t") == "usage" else ()
return {k: v for k, v in ev.items()
if v is not None and not (k in flags and v is False)
and not (k in zeros and v == 0)}
def dumps(ev: dict) -> str:
"""One v1 line, no newline: compact JSON, ``t`` and ``at`` first."""
ev = compact(ev)
head = {k: ev[k] for k in ("t", "at") if k in ev}
return json.dumps({**head, **ev}, ensure_ascii=False, separators=(",", ":"))
def is_v1_header(o) -> bool:
return isinstance(o, dict) and "t" in o and "v" in o
# ── one file ─────────────────────────────────────────────────────────────────
KEY_FIELDS = ("ocKey", "ocKeys", "agyKey")
_FACTS = ("cwd", "branch")
class Out:
"""One v1 transcript a converter appends to (a conversation, or a
subagent's sidechain). ``facts``: the session header's fields (``id``,
``harness``, ``harnessVersion``, ``cwd``, ``branch``, ``sidechain``,
``agent``). Reading the file back on open rebuilds the keys it holds
(``keys``), its title (``title``), the facts last written and whether it
is in the old format (``legacy``)."""
def __init__(self, path: pathlib.Path, facts: dict, key_field: str):
self.path = path
self.facts = {k: v for k, v in facts.items() if v is not None}
self.key_field = key_field
self.keys: set[str] = set()
self.title: str | None = None
self.legacy = False # lines in the old format, no v1 yet
self.started = False # anything on disk
self._last: dict = {} # cwd / branch the file last said
self._load()
def _load(self) -> None:
try:
fh = self.path.open("rb")
except OSError:
return
first = True
with fh:
for raw in fh:
try:
o = json.loads(raw)
except ValueError:
continue
if not isinstance(o, dict):
continue
self.started = True
if first:
self.legacy = not is_v1_header(o)
first = False
elif self.legacy and is_v1_header(o):
self.legacy = False
for k in KEY_FIELDS:
v = o.get(k)
if isinstance(v, str):
self.keys.add(v)
elif isinstance(v, list):
self.keys.update(x for x in v if isinstance(x, str))
if o.get("t") == "session":
for f in _FACTS:
if f in o:
self._last[f] = o[f]
elif "t" not in o: # a record of the old format
if "cwd" in o:
self._last["cwd"] = o["cwd"]
if "gitBranch" in o:
self._last["branch"] = o["gitBranch"]
if o.get("type") == "ai-title" and o.get("aiTitle"):
self.title = o["aiTitle"]
elif o.get("t") == "meta" and o.get("kind") == "title" and o.get("data"):
self.title = o["data"]
def append(self, groups: list[tuple[str | None, list[dict]]]) -> int:
"""Write the groups (``(key, events)``) whose key the file doesn't
hold yet; the number of lines written. ``key`` may be a list (a group
that also stands for other keys: the first one names it). Nothing
moves in memory before the lines are on disk (a failed write is
retried)."""
todo: list[tuple[list[str], list[dict]]] = []
keys: set[str] = set()
for key, evs in groups:
ks = [key] if isinstance(key, str) else list(key or [])
if ks and (ks[0] in self.keys or ks[0] in keys):
continue
evs = [e for e in evs if e]
if evs:
keys.update(ks)
todo.append((ks, evs))
if not todo:
return 0
first_at = next((e["at"] for _ks, evs in todo for e in evs if e.get("at")), None)
if not self.started and first_at is None:
return 0 # a new file opens on its first moment (a title alone has none)
if self.legacy and first_line_is_v1(self.path):
self.legacy = False # rewritten to v1 meanwhile (scripts/transcripts-v1.py)
lines: list[str] = []
last = dict(self._last)
if not self.started or self.legacy:
# the session's facts as of the first moment written
lines.append(dumps({"t": "session", "at": first_at, "v": V, **self.facts}))
last.update({f: self.facts.get(f) for f in _FACTS})
for ks, evs in todo:
moved = {f: self.facts.get(f) for f in _FACTS
if self.facts.get(f) is not None and last.get(f) != self.facts.get(f)}
if moved:
lines.append(dumps({"t": "session", "at": evs[0].get("at"), **moved}))
last.update(moved)
if ks:
field = {self.key_field: ks[0]}
if len(ks) > 1:
field[self.key_field + "s"] = ks[1:]
evs = [{**evs[0], **field}, *evs[1:]]
lines += [dumps(e) for e in evs]
if not lines:
return 0
self.path.parent.mkdir(parents=True, exist_ok=True)
with self.path.open("a", encoding="utf-8") as fh:
fh.write("\n".join(lines) + "\n")
self.keys |= keys
self.started, self.legacy, self._last = True, False, last
for _k, evs in groups:
for e in evs or []:
if e and e.get("t") == "meta" and e.get("kind") == "title":
self.title = e.get("data")
return len(lines)
# ── the events of a step ─────────────────────────────────────────────────────
def step(call: dict, blocks: list[dict], usage: dict | None) -> list[dict]:
"""A model step, whole: its ``call``, its blocks (named after the call),
then its ``usage`` when the harness knows it."""
cid = call.get("id")
out = [{"t": "call", **call}]
for b in blocks:
out.append({**b, **({"call": cid} if cid is not None else {})})
if usage is not None:
out.append({"t": "usage", "at": call.get("at"), **usage,
**({"call": cid} if cid is not None else {})})
return out
def api_error(key_id: str, at, field: str | None, text: str, uid: str | None = None) -> list[dict]:
"""A failed model call, as the hub reads Claude Code's own API-error turn:
a ``failed`` call on the ``<synthetic>`` placeholder (it never reached a
model) with a zero usage, its ``error``, and the turn's end."""
kind = api_error_kind(field, text)
return [{"t": "call", "at": at, "id": key_id, "model": "<synthetic>", "failed": True},
{"t": "error", "at": at, "call": key_id, "kind": kind, "text": text, "id": uid},
{"t": "usage", "at": at, "call": key_id, "input": 0, "output": 0},
{"t": "turn_end", "at": at, "reason": "error"}]
_NO_RESPONSE_RE = re.compile(r"^\s*No response requested\.?\s*$")
def text(at, text: str) -> dict:
"""A text block — Claude Code's canned "No response requested." reads as
the paused tag it is."""
if _NO_RESPONSE_RE.match(text):
return {"t": "text", "at": at, "text": text, "paused": True}
return {"t": "text", "at": at, "text": text}
def tool_result(at, call_id: str, text: str, is_error: bool) -> dict:
return {"t": "tool_result", "at": at, "toolCall": call_id, "ok": not is_error,
"text": text}
# ── a user message's text ────────────────────────────────────────────────────
# (hubtext.py / claudetext.py)
_INBOX_RE = re.compile(
r"\A(?:Another Claude session sent a message[^:\n]*:\s*\n)?"
r"\[(?:Follow-up from your user|Message from the ai-agent hub)[^\]]*\]\s*\n+"
r"(.*?)"
r"(?:\n\n+This came from another Claude session\b.*)?\Z", re.S)
_AUTHOR_RE = re.compile(
r'\A<ai-agent-from user="([^"]*)" name="([^"]*)" role="([^"]*)"\s*/>\s*\n?')
_INTERRUPT_RE = re.compile(r"^\s*\[Request interrupted by user")
_SLASH_CMD_RE = re.compile(r"<command-name>/?([^<\s]+)\s*</command-name>")
_SLASH_ARGS_RE = re.compile(r"<command-args>([\s\S]*?)</command-args>")
_SKILL_BODY_RE = re.compile(r"^Base directory for this skill:[ \t]*(\S[^\n]*)\n+", re.S)
_SKILL_NOTE_RE = re.compile(r"^\s*(?:\(Re-invocation of /|Skill /\S+ is already loaded)")
_COMPACT_LEAD_RE = re.compile(
r"^This session is being continued from a previous conversation.*?\n\n", re.S)
_COMPACT_REMINDER_RE = re.compile(r"<system-reminder>.*?</system-reminder>\s*", re.S)
def unwrap_inbox(c: str) -> str:
m = _INBOX_RE.match(c)
return m.group(1).strip() if m else c
def split_author(c: str) -> tuple[dict | None, str]:
m = _AUTHOR_RE.match(c or "")
if not m:
return None, c
return {"id": m.group(1), "name": m.group(2), "role": m.group(3)}, c[m.end():]
def slash_command(text: str) -> dict | None:
m = _SLASH_CMD_RE.search(text or "")
if not m:
return None
a = _SLASH_ARGS_RE.search(text)
return {"name": m.group(1), "args": (a.group(1).strip() if a else "")}
def skill_body(text: str) -> tuple[str, str] | None:
m = _SKILL_BODY_RE.match(text or "")
if not m:
return None
return m.group(1).strip(), text[m.end():]
def compact_summary_text(text: str) -> str:
text = _COMPACT_REMINDER_RE.sub("", _COMPACT_LEAD_RE.sub("", text or "", count=1))
return re.sub(r"^Summary:\s*", "", text.strip())
def skill_inject(name, ref, text: str, at, invoked: dict | None = None) -> dict:
"""A skill's prompt, injected: its marker line read off as ``baseDir``."""
based = skill_body(text)
base_dir, body = based if based is not None else (None, text)
ev = {"t": "inject", "at": at, "kind": "skill", "name": name, "ref": ref,
"baseDir": base_dir, "text": None if _SKILL_NOTE_RE.match(body) else body}
if invoked is not None:
ev["invoked"] = invoked
return ev
def prompt_events(text: str, at) -> list[dict]:
"""What the user (or the hub on their behalf) sent, as events: a
``prompt`` — its author tag and the hub's inbox note unwrapped — or, for
the conventions a message can carry instead, ``turn_end`` (the interrupt
marker), ``inject`` (a typed ``/command``; anything else in ``<…>`` is
context the thread doesn't show)."""
c = text if isinstance(text, str) else ""
origin = "user"
u = unwrap_inbox(c)
if u != c:
origin, c = "inbox", u
author, c = split_author(c)
if _INTERRUPT_RE.match(c):
return [{"t": "turn_end", "at": at, "reason": "interrupted"}]
if c.strip() and not c.startswith("<"):
ev = {"t": "prompt", "at": at, "text": c, "origin": origin}
if author:
ev["author"] = author
return [ev]
if c.lstrip().startswith("<command-"):
ev = {"t": "inject", "at": at, "kind": "command", "text": c}
cmd = slash_command(c)
if cmd is not None:
ev["name"], ev["args"] = cmd["name"], cmd["args"]
return [ev]
kind = "reminder" if c.lstrip().startswith("<system-reminder>") else "note"
return [{"t": "inject", "at": at, "kind": kind, "text": c}]
# ── API errors (errors.py) ───────────────────────────────────────────────────
_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 api_error_kind(field: str | None, text: str | None) -> str:
"""An API error's kind: the CLI vocabulary's ``error`` field when the
converter has one, else the wording."""
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"
# ── tool names (readers/toolnames.py) ────────────────────────────────────────
CLAUDE = {
"Bash": "shell",
"BashOutput": "shell_output", "TaskOutput": "shell_output",
"KillShell": "shell_kill", "TaskStop": "shell_kill",
"Read": "read", "NotebookRead": "read",
"Write": "write",
"Edit": "edit", "MultiEdit": "edit", "NotebookEdit": "edit",
"Grep": "grep", "Glob": "glob", "LS": "list_dir",
"WebFetch": "web_fetch", "WebSearch": "web_search",
"Agent": "agent", "Task": "agent",
"Skill": "skill",
"TodoWrite": "todo", "TaskCreate": "todo", "TaskUpdate": "todo",
"TaskGet": "todo", "TaskList": "todo",
"AskUserQuestion": "ask_user",
}
LEGACY = {"ApplyPatch": "apply_patch", "DeleteFile": "delete_file"}
# A harness's own tool its converter shaped under a Claude-Code-looking name.
LEGACY_OWN = {"opencode": {"Execute": "execute"}}
def neutral(claude_name: str, harness: str) -> str:
"""The neutral ``tool`` of a call the converter shaped as Claude Code's
``claude_name`` (its argument shapes are those): a core name, an MCP
tool's own, else the harness's own name behind its id
(``opencode:execute``) — ``toolnames.claude_name`` with the harness."""
n = CLAUDE.get(claude_name) or LEGACY.get(claude_name)
if n is not None:
return n
if claude_name.startswith("mcp_"):
return claude_name
return f"{harness}:{LEGACY_OWN.get(harness, {}).get(claude_name, claude_name)}"
def tool_call(at, call_id: str, claude_name: str, native: str, inp, harness: str) -> dict:
return {"t": "tool_call", "at": at, "id": call_id,
"tool": neutral(claude_name, harness), "native": native, "input": inp}
# ── a file to rewrite? ───────────────────────────────────────────────────────
def first_line_is_v1(path: os.PathLike) -> bool:
"""Whether ``path`` opens on a v1 header."""
try:
with open(path, "rb") as fh:
line = fh.readline()
return is_v1_header(json.loads(line))
except (OSError, ValueError):
return False