A converter that resumes a conversation from before v1 writes a v1 header line ahead of its first event: LegacyReader hands every line after it to a V1Reader. conversations/parse/rewrite_v1.py turns a legacy pi / opencode / agy transcript into the v1 events a converter would have written — the legacy reader's own events, steps written whole, the mirrors' dedup keys kept — with each fix switchable: whole_steps (quirk a: opencode's late usage joins its step), source_times (quirk c: agy's turn closes take the source's last time, not the mirror's clock), harness (pi named in the header), no_pi_fallback (an opencode step that failed empty no longer reads as pi's pre-2026-11-06 error turn: one made-up error card less). With no fix the v1 file parses exactly like the old one (summary, thread, chunked). ids.head_timestamp_ms and toolimage.read_path read v1 lines too; parse output for files that are not rewritten is unchanged (no PARSER_VERSION bump). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
137 lines
5.5 KiB
Python
137 lines
5.5 KiB
Python
"""The image a tool handed the model, served back from the transcript.
|
|
|
|
An image ``Read`` puts the bitmap itself into the transcript — the tool_result
|
|
carries it as a base64 ``image`` block (the copy the model saw, downscaled past
|
|
~2000 px). So the viewer can show it wherever the run happened: a Mac worker's
|
|
``/Users/…`` file or a scratchpad the OS has since cleared are not on this
|
|
disk, but their transcript (mirrored here, workers/remotefeed.py) is.
|
|
|
|
``find`` scans one transcript for the tool_result of one tool call; the route
|
|
(``GET /api/conversation-image``) tries the conversation's own transcript and
|
|
then its subagents'. With ``original=1`` it serves the file itself instead —
|
|
for a run on a worker, fetched from that machine (``from_worker``, the
|
|
sidecar's ``/media``) by the path the call read, never one the browser names."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import base64
|
|
import binascii
|
|
import json
|
|
import pathlib
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
# What the Messages API accepts as an image block — all safe to render inline.
|
|
MEDIA_TYPES = {"image/png", "image/jpeg", "image/gif", "image/webp"}
|
|
|
|
|
|
def _images(content) -> list[dict]:
|
|
if not isinstance(content, list):
|
|
return []
|
|
return [b for b in content
|
|
if isinstance(b, dict) and b.get("type") == "image"
|
|
and isinstance(b.get("source"), dict)
|
|
and b["source"].get("type") == "base64"]
|
|
|
|
|
|
def _blocks(path: pathlib.Path, tool_use_id: str):
|
|
"""The content blocks of ``path``'s records that name ``tool_use_id``."""
|
|
if not tool_use_id:
|
|
return
|
|
try:
|
|
fh = path.open(encoding="utf-8", errors="ignore")
|
|
except OSError:
|
|
return
|
|
with fh:
|
|
for line in fh:
|
|
# Tool ids are unique random strings: a substring test skips the
|
|
# JSON parse of every other record (some carry megabytes).
|
|
if tool_use_id not in line:
|
|
continue
|
|
try:
|
|
rec = json.loads(line)
|
|
except ValueError:
|
|
continue
|
|
content = (rec.get("message") or {}).get("content") if isinstance(rec, dict) else None
|
|
if isinstance(content, list):
|
|
yield from (b for b in content if isinstance(b, dict))
|
|
|
|
|
|
def read_path(path: pathlib.Path, tool_use_id: str) -> str | None:
|
|
"""The ``file_path`` tool call ``tool_use_id`` read, or None."""
|
|
for b in _blocks(path, tool_use_id):
|
|
if b.get("type") == "tool_use" and b.get("id") == tool_use_id:
|
|
fp = (b.get("input") or {}).get("file_path")
|
|
return fp if isinstance(fp, str) and fp else None
|
|
ev = _v1_call(path, tool_use_id) # a v1 transcript (pi, opencode, agy)
|
|
fp = ((ev or {}).get("input") or {}).get("file_path") if isinstance(ev, dict) else None
|
|
return fp if isinstance(fp, str) and fp else None
|
|
|
|
|
|
def _v1_call(path: pathlib.Path, tool_use_id: str) -> dict | None:
|
|
"""A v1 transcript's ``tool_call`` event ``tool_use_id``, or None."""
|
|
try:
|
|
fh = path.open(encoding="utf-8", errors="ignore")
|
|
except OSError:
|
|
return None
|
|
with fh:
|
|
for line in fh:
|
|
if tool_use_id not in line or '"tool_call"' not in line:
|
|
continue
|
|
try:
|
|
ev = json.loads(line)
|
|
except ValueError:
|
|
continue
|
|
if isinstance(ev, dict) and ev.get("t") == "tool_call" and ev.get("id") == tool_use_id:
|
|
return ev
|
|
return None
|
|
|
|
|
|
def find(path: pathlib.Path, tool_use_id: str, index: int = 0) -> tuple[bytes, str] | None:
|
|
"""``(bytes, media type)`` of the ``index``-th image in the result of tool
|
|
call ``tool_use_id`` in transcript ``path``, or None."""
|
|
for b in _blocks(path, tool_use_id):
|
|
if b.get("type") == "tool_result" and b.get("tool_use_id") == tool_use_id:
|
|
imgs = _images(b.get("content"))
|
|
if not 0 <= index < len(imgs):
|
|
return None
|
|
src = imgs[index]["source"]
|
|
media = str(src.get("media_type") or "")
|
|
if media not in MEDIA_TYPES:
|
|
return None
|
|
try:
|
|
return base64.b64decode(src.get("data") or "", validate=True), media
|
|
except (binascii.Error, ValueError):
|
|
return None
|
|
return None
|
|
|
|
|
|
class Unavailable(Exception):
|
|
"""The worker couldn't hand the file over — ``status`` is what the route
|
|
answers (404: gone or never an image; 502: the machine is unreachable)."""
|
|
|
|
def __init__(self, status: int, message: str):
|
|
super().__init__(message)
|
|
self.status = status
|
|
|
|
|
|
def from_worker(w: dict, file_path: str, timeout: float = 20) -> tuple[bytes, str]:
|
|
"""The file at ``file_path`` on worker ``w`` (its sidecar's ``/media``)."""
|
|
url = f"{w['url']}/media?{urllib.parse.urlencode({'path': file_path})}"
|
|
req = urllib.request.Request(url, headers={"Authorization": f"Bearer {w['token']}"})
|
|
name = w.get("name") or w.get("id") or "the worker"
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
media = r.headers.get_content_type()
|
|
data = r.read()
|
|
except urllib.error.HTTPError as e:
|
|
if e.code == 404:
|
|
raise Unavailable(404, f"{file_path} is no longer on {name}")
|
|
raise Unavailable(502, f"{name} answered HTTP {e.code}")
|
|
except (urllib.error.URLError, OSError) as e:
|
|
raise Unavailable(502, f"{name} is unreachable: {e}")
|
|
if media not in MEDIA_TYPES:
|
|
raise Unavailable(404, f"{file_path} is not an image")
|
|
return data, media
|