The readers put the neutral name in a tool_call's `tool` and the record's own in `native` (readers/toolnames.py): Bash → shell, Read → read, Agent/Task → agent, the five task tools → todo, CronCreate → claude:CronCreate; a converter-written legacy file namespaces its own tools under its entrypoint (agy:manage_task, opencode:execute), an unstamped one's lowercase names are pi's. MCP names are untouched. The fold, the cost buckets (bash → shell, task → todo; TaskOutput / TaskStop now count as shell, TaskGet / TaskList as todo), taskevents, the resource miner, the lifecycle / deploy / worktree detection, tree.py's agent cards, spawned children, the scaffold and the bgtasks route key on the neutral names only. The `todo` calls are told apart by their input (tools.todo_op). A tool card carries `native` when it differs. PARSER_VERSION 45 (a full re-index). docs/transcript-format.md gets the "Tool names" table with the agy column filled from sidecar/agy_tools.py; the v1 fixtures use the neutral names. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
110 lines
4.6 KiB
Python
110 lines
4.6 KiB
Python
"""Claude Code's Code Mode in a transcript.
|
|
|
|
In Code Mode Claude writes JavaScript that the CLI runs through its ``REPL``
|
|
tool, and the shell / file calls that code makes are real tool calls of
|
|
their own. The transcript records them like this:
|
|
|
|
- the ``REPL`` tool_use (``input.code``) and its tool_result, which comes back
|
|
at once: ``"(dispatched #N)"``, ``toolUseResult.evalId`` N;
|
|
- once the code settles, a *delivery*: a ``poll_events`` attachment or a
|
|
``Poll`` tool_result whose text holds
|
|
``<event kind="repl-eval" eval="N" ms="…" status="settled"><result>…``;
|
|
- right after it, the calls that code made, as *virtual* records
|
|
(``isVirtual: true``, tool ids ``repl_<uuid>``, a zero usage), each with
|
|
its virtual tool_result.
|
|
|
|
Nothing on a virtual call names its script, so :class:`CodeMode` links them
|
|
by that order: the calls after a delivery belong to the evals it settled.
|
|
When one delivery settles several, the script whose code holds the call's
|
|
command (or file name) takes it, else the first. A call that outlived its
|
|
script can be missing from the transcript altogether; agent-probe's call
|
|
records carry its script too (``perf.calls`` → ``script``).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
|
|
_EVENT = re.compile(r'<event\b([^>]*)>(.*?)</event>', re.S)
|
|
_ATTR = re.compile(r'(\w+)="([^"]*)"')
|
|
_RESULT = re.compile(r'<result>(.*?)</result>', re.S)
|
|
_LOG = re.compile(r'<log>(.*?)</log>', re.S)
|
|
|
|
SCRIPT_TOOL = "REPL"
|
|
# …and the neutral name of its card (``parse/readers/toolnames.py``).
|
|
SCRIPT_CARD = "claude:REPL"
|
|
|
|
|
|
def from_code(tool_use_id: str | None) -> bool:
|
|
"""A call a Code Mode script made, not one of the model's own."""
|
|
return bool(tool_use_id) and tool_use_id.startswith("repl_")
|
|
|
|
|
|
def settled(text: str) -> list[dict]:
|
|
"""The repl-eval events in a delivery's text: eval id, status, ms, and
|
|
what the code returned (its result, else its logs)."""
|
|
out = []
|
|
for m in _EVENT.finditer(text or ""):
|
|
attrs = dict(_ATTR.findall(m.group(1)))
|
|
if attrs.get("kind") != "repl-eval" or not attrs.get("eval", "").isdigit():
|
|
continue
|
|
body = m.group(2)
|
|
r = _RESULT.search(body)
|
|
result = r.group(1).strip() if r else "\n".join(x.strip() for x in _LOG.findall(body)).strip()
|
|
out.append({"eval": int(attrs["eval"]), "status": attrs.get("status"),
|
|
"ms": int(attrs["ms"]) if attrs.get("ms", "").isdigit() else None,
|
|
"result": result})
|
|
return out
|
|
|
|
|
|
class CodeMode:
|
|
"""Which script each virtual call belongs to, record by record (plain
|
|
dicts: the parser state is snapshotted between feeds)."""
|
|
|
|
def __init__(self) -> None:
|
|
self.evals: dict[int, str] = {} # eval id → its REPL call's toolUseId
|
|
self.codes: dict[str, str] = {} # REPL toolUseId → its code
|
|
self.pending: list[str] = [] # the scripts the last delivery settled
|
|
|
|
def started(self, tool_use_id: str | None, inp) -> None:
|
|
if tool_use_id and isinstance(inp, dict) and isinstance(inp.get("code"), str):
|
|
self.codes[tool_use_id] = inp["code"]
|
|
|
|
def dispatched(self, tool_use_id: str | None, tool_use_result) -> int | None:
|
|
"""A REPL call's result: the eval its code runs as."""
|
|
ev = tool_use_result.get("evalId") if isinstance(tool_use_result, dict) else None
|
|
if tool_use_id and isinstance(ev, int):
|
|
self.evals[ev] = tool_use_id
|
|
return ev
|
|
return None
|
|
|
|
def delivered(self, text: str) -> list[tuple[str, dict]]:
|
|
"""A delivery: the scripts it settled (each with its event); the
|
|
virtual calls that follow are theirs."""
|
|
found = [(self.evals[e["eval"]], e) for e in settled(text) if e["eval"] in self.evals]
|
|
if found:
|
|
self.pending = list(dict.fromkeys(sid for sid, _ in found))
|
|
return found
|
|
|
|
def script_of(self, inp) -> str | None:
|
|
"""The script a virtual call (its input) belongs to."""
|
|
if not self.pending:
|
|
return None
|
|
if len(self.pending) == 1:
|
|
return self.pending[0]
|
|
needle = ""
|
|
if isinstance(inp, dict):
|
|
needle = str(inp.get("command") or inp.get("file_path") or "")
|
|
if inp.get("file_path"):
|
|
needle = needle.rsplit("/", 1)[-1]
|
|
needle = needle.strip()[:40]
|
|
if needle:
|
|
for sid in self.pending:
|
|
if needle in self.codes.get(sid, ""):
|
|
return sid
|
|
return self.pending[0]
|
|
|
|
def model_turn(self) -> None:
|
|
"""A record of the model's own: the virtual calls of a delivery are over."""
|
|
self.pending = []
|