Files

241 lines
11 KiB
Python

"""
opencode tool calls → Claude Code tool calls, for the transcript mirror.
The viewer keys everything on Claude Code's PascalCase tool names and their
argument shapes — cost-by-tool buckets, the auto project/service tags (an edit
tool's ``file_path``), Bash cards, edit diffs, Agent cards linked to their
subagent transcript. opencode V2 names its tools differently (``shell``,
``patch``, ``subagent`` …) with camelCase arguments, so the mirror translates
each call here, the way the pi runner's ``mapToolCall`` does for pi.
``patch`` is the one that doesn't map one to one: GPT models get it *instead
of* ``edit``/``write``, and one call may touch several files in the Codex
``*** Begin Patch`` grammar. It is split into one Claude call per file
(``Write`` for an added file, ``Edit``/``MultiEdit`` for an update, each ``@@``
chunk an edit), so every file gets its diff card and its project tag.
Sessions an older opencode (1.x) recorded keep the 1.x names (``bash``,
``task``, ``todowrite``, ``filePath`` …) after the V2 migration; they map too.
"""
from __future__ import annotations
import os
import re
# A subagent's first user message, as opencode writes it (the model reads it;
# the viewer shows only the prompt the parent wrote).
SUBAGENT_PREFIX = "You are a subagent spawned by another session.\n"
def _abs(path, cwd: str | None) -> str:
p = str(path or "")
if p and cwd and not os.path.isabs(p):
return os.path.normpath(os.path.join(cwd, p))
return p
def _path(inp: dict) -> str:
return inp.get("path") or inp.get("filePath") or inp.get("file_path") or ""
def map_call(name: str, inp, cwd: str | None, call_id: str) -> list[tuple[str, str, dict]]:
"""``[(tool_use id, Claude tool name, input), …]`` for one opencode call —
one entry, except a multi-file ``patch``."""
inp = inp if isinstance(inp, dict) else {"input": inp}
n = name or "tool"
if n == "read":
out = {"file_path": _abs(_path(inp), cwd)}
for k in ("offset", "limit"):
if inp.get(k) is not None:
out[k] = inp[k]
return [(call_id, "Read", out)]
if n == "write":
return [(call_id, "Write", {"file_path": _abs(_path(inp), cwd),
"content": inp.get("content") or ""})]
if n == "edit":
out = {"file_path": _abs(_path(inp), cwd),
"old_string": inp.get("oldString", inp.get("old_string", "")),
"new_string": inp.get("newString", inp.get("new_string", ""))}
if inp.get("replaceAll") or inp.get("replace_all"):
out["replace_all"] = True
return [(call_id, "Edit", out)]
if n == "multiedit": # 1.x
edits = [{"old_string": e.get("oldString", ""), "new_string": e.get("newString", "")}
for e in inp.get("edits") or [] if isinstance(e, dict)]
return [(call_id, "MultiEdit", {"file_path": _abs(_path(inp), cwd), "edits": edits})]
if n in ("patch", "apply_patch"):
calls = patch_calls(inp.get("patchText") or inp.get("patch") or "", cwd, call_id)
return calls or [(call_id, "ApplyPatch", {"patch": inp.get("patchText") or ""})]
if n in ("shell", "bash"):
out = {"command": inp.get("command") or ""}
if inp.get("description"):
out["description"] = inp["description"]
if isinstance(inp.get("timeout"), (int, float)) and inp["timeout"] > 0:
out["timeout"] = inp["timeout"] # ms on both sides
if inp.get("background"):
out["run_in_background"] = True
if inp.get("workdir"):
out["workdir"] = inp["workdir"]
return [(call_id, "Bash", out)]
if n == "glob":
out = {"pattern": inp.get("pattern") or ""}
if inp.get("path"):
out["path"] = _abs(inp["path"], cwd)
return [(call_id, "Glob", out)]
if n == "grep":
out = {"pattern": inp.get("pattern") or "", "output_mode": "content"}
if inp.get("path"):
out["path"] = _abs(inp["path"], cwd)
if inp.get("include"):
out["glob"] = inp["include"]
if inp.get("caseSensitive") is False:
out["-i"] = True
return [(call_id, "Grep", out)]
if n == "list": # 1.x
return [(call_id, "LS", {"path": _abs(_path(inp), cwd)})]
if n == "webfetch":
return [(call_id, "WebFetch", {"url": inp.get("url") or "",
"prompt": f"as {inp.get('format') or 'markdown'}"})]
if n == "websearch":
return [(call_id, "WebSearch", {"query": inp.get("query") or ""})]
if n in ("subagent", "task"):
out = {"description": inp.get("description") or "",
"prompt": inp.get("prompt") or "",
"subagent_type": inp.get("agent") or inp.get("subagent_type") or "general"}
if inp.get("background"):
out["run_in_background"] = True
return [(call_id, "Agent", out)]
if n == "skill":
return [(call_id, "Skill", {"skill": inp.get("id") or inp.get("name") or ""})]
if n == "question":
qs = [{"question": q.get("question", ""), "header": q.get("header", ""),
"options": q.get("options") or [], "multiSelect": bool(q.get("multiple"))}
for q in inp.get("questions") or [] if isinstance(q, dict)]
return [(call_id, "AskUserQuestion", {"questions": qs})]
if n == "todowrite": # 1.x
return [(call_id, "TodoWrite", {"todos": inp.get("todos") or []})]
if n == "execute":
code = str(inp.get("code") or "")
return [(call_id, "Execute", {"description": _first_line(code), "code": code})]
return [(call_id, n, inp)]
def _first_line(text: str, limit: int = 80) -> str:
line = next((ln.strip() for ln in text.splitlines() if ln.strip()), "")
return line if len(line) <= limit else line[:limit - 1] + "…"
# ── the Codex patch grammar ──────────────────────────────────────────────────
_FILE_RE = re.compile(r"^\*\*\* (Add|Delete|Update) File:\s*(.+?)\s*$")
_MOVE_RE = re.compile(r"^\*\*\* Move to:\s*(.+?)\s*$")
def parse_patch(text: str) -> list[dict]:
"""``*** Begin Patch`` text → ``[{op, path, moveTo?, lines?, chunks?}]``.
``Add`` carries the new file's lines; ``Update`` its chunks, each
``(old_lines, new_lines)`` (context lines land on both sides). Tolerant:
a missing ``Begin``/``End`` marker or a stray line never raises — the
mirror would rather show a partial diff than lose the call."""
files: list[dict] = []
cur: dict | None = None
chunk: tuple[list[str], list[str]] | None = None
for raw in (text or "").splitlines():
line = raw.rstrip("\r")
m = _FILE_RE.match(line)
if m:
cur = {"op": m.group(1).lower(), "path": m.group(2), "lines": [], "chunks": []}
files.append(cur)
chunk = None
continue
if cur is None or line.startswith("*** Begin Patch") or line.startswith("*** End"):
continue
mv = _MOVE_RE.match(line)
if mv:
cur["moveTo"] = mv.group(1)
continue
if cur["op"] == "add":
if line.startswith("+"):
cur["lines"].append(line[1:])
continue
if cur["op"] != "update":
continue
if line.startswith("@@"):
chunk = ([], [])
cur["chunks"].append(chunk)
continue
if chunk is None:
chunk = ([], [])
cur["chunks"].append(chunk)
if line.startswith("-"):
chunk[0].append(line[1:])
elif line.startswith("+"):
chunk[1].append(line[1:])
else:
body = line[1:] if line.startswith(" ") else line
chunk[0].append(body)
chunk[1].append(body)
return files
def patch_calls(text: str, cwd: str | None, call_id: str) -> list[tuple[str, str, dict]]:
out: list[tuple[str, str, dict]] = []
for i, f in enumerate(parse_patch(text)):
cid = call_id if i == 0 else f"{call_id}.{i}"
path = _abs(f["path"], cwd)
if f["op"] == "add":
out.append((cid, "Write", {"file_path": path, "content": "\n".join(f["lines"])}))
elif f["op"] == "delete":
out.append((cid, "DeleteFile", {"file_path": path,
"description": f"deleted {os.path.basename(path)}"}))
else:
edits = [{"old_string": "\n".join(o), "new_string": "\n".join(n)}
for o, n in f["chunks"] if o != n]
target = _abs(f["moveTo"], cwd) if f.get("moveTo") else path
if len(edits) == 1:
out.append((cid, "Edit", {"file_path": target, **edits[0]}))
else:
out.append((cid, "MultiEdit", {"file_path": target, "edits": edits}))
return out
# ── results ──────────────────────────────────────────────────────────────────
def result_text(state: dict) -> tuple[str, bool]:
"""(text, is_error) of a settled tool state: its ``content`` items joined
(a file item becomes a placeholder — the viewer previews files from the
call, not the result), plus the error message on a failure."""
parts = []
for c in state.get("content") or []:
if not isinstance(c, dict):
continue
if c.get("type") == "text":
parts.append(c.get("text") or "")
elif c.get("type") == "file":
parts.append(f"[{c.get('mime') or 'file'}{': ' + c['name'] if c.get('name') else ''}]")
err = state.get("status") == "error"
if err:
e = state.get("error") or {}
msg = e.get("message") or e.get("type") or "tool failed"
parts.append(f"Error: {msg}" if not parts else f"\nError: {msg}")
return "\n".join(p for p in parts if p is not None), err
_SKILL_RE = re.compile(r"<skill_content[^>]*>\s*(?:# Skill: [^\n]*\n+)?(.*?)\n+Base directory for this skill:",
re.S)
def skill_body(text: str) -> str:
"""The skill's own text out of opencode's ``<skill_content>`` block."""
m = _SKILL_RE.search(text or "")
return (m.group(1) if m else text or "").strip()
_SUBAGENT_RE = re.compile(r"^\s*<subagent\b[^>]*>\n?(.*?)\n?</subagent>\s*$", re.S)
def subagent_report(text: str) -> str:
"""A subagent's final text, without opencode's ``<subagent …>`` wrapper."""
m = _SUBAGENT_RE.match(text or "")
return m.group(1) if m else (text or "")