86 lines
3.5 KiB
Python
86 lines
3.5 KiB
Python
import io
|
|
import json
|
|
import pathlib
|
|
import typing
|
|
|
|
from claude_code.entries import AssistantTurn, Entry, HumanTurn, LoopPrompt, parse_entry, Text, ToolCall
|
|
from failure import Failure
|
|
from text_files.compressed import read_stored
|
|
|
|
JUDGED_TOOL_INPUT = 400
|
|
|
|
|
|
class Typed(typing.NamedTuple):
|
|
"""A -p prompt of loop-claude's that carries an answer the human typed: loop-claude's words, and that answer."""
|
|
loop_words: str
|
|
answer: str
|
|
|
|
|
|
def read_transcript(path: str) -> list[Entry] | Failure:
|
|
"""The entries of the transcript at path, or of its gzip where compress-archives gzipped it."""
|
|
try:
|
|
return [entry for raw in io.BytesIO(read_stored(pathlib.Path(path))) if (entry := parse_entry(raw))]
|
|
except OSError as failure:
|
|
return Failure(f"could not read the transcript {path}: {failure.strerror}")
|
|
|
|
|
|
def current_thread(entries: list[Entry]) -> list[Entry]:
|
|
"""The entries of the transcript's current thread since its last compaction, oldest first: the newest entry with a uuid and its ancestors by parentUuid.
|
|
|
|
That leaves out a branch the session rewound, and the results of parallel tool calls that Claude Code chains on a side branch."""
|
|
chained = [entry for entry in entries if entry.uuid]
|
|
by_uuid = {entry.uuid: entry for entry in chained}
|
|
found: list[Entry] = []
|
|
entry = chained[-1] if chained else None
|
|
# A compaction writes {"type": "system", "subtype": "compact_boundary", "parentUuid": null, ...}, so the thread starts there; the length check stops a parent cycle.
|
|
while entry is not None and len(found) < len(chained):
|
|
found.append(entry)
|
|
entry = by_uuid.get(entry.parent_uuid)
|
|
return found[::-1]
|
|
|
|
|
|
# The lines before it, such as the session's title, are the same for every chunk of a project.
|
|
def first_timestamped_line(raw: bytes) -> bytes:
|
|
lines = raw.splitlines()
|
|
return next((line for line in lines if (entry := parse_entry(line)) and entry.timestamp), lines[0] if lines else b"")
|
|
|
|
|
|
def human_turns(entries: list[Entry]) -> int:
|
|
return sum(1 for entry in entries if isinstance(entry, HumanTurn))
|
|
|
|
|
|
def render(entries: list[Entry], typed_answer: typing.Callable[[str], Typed | None]) -> str:
|
|
"""The transcript as the judge reads it. typed_answer splits the answer the human typed out of a -p prompt of loop-claude's, so that answer reads as the human's, like one typed in claude."""
|
|
lines = []
|
|
for entry in entries:
|
|
if isinstance(entry, AssistantTurn):
|
|
lines += assistant_lines(entry)
|
|
elif isinstance(entry, HumanTurn):
|
|
lines.append("[human] " + entry.text)
|
|
elif isinstance(entry, LoopPrompt):
|
|
typed = typed_answer(entry.text)
|
|
lines += ["[loop] " + entry.text] if typed is None else ["[loop] " + typed.loop_words, "[human] " + typed.answer]
|
|
return "\n\n".join(lines)
|
|
|
|
|
|
def human_answers(entries: list[Entry], typed_answer: typing.Callable[[str], Typed | None]) -> list[str]:
|
|
"""Each answer the human typed, whole, as render shows it on a [human] line, latest last."""
|
|
found = []
|
|
for entry in entries:
|
|
if isinstance(entry, HumanTurn):
|
|
found.append(entry.text)
|
|
elif isinstance(entry, LoopPrompt) and (typed := typed_answer(entry.text)):
|
|
found.append(typed.answer)
|
|
return found
|
|
|
|
|
|
def assistant_lines(turn: AssistantTurn) -> list[str]:
|
|
"""The turn's text and tool calls as the judge reads them."""
|
|
return [line for part in turn.parts if (line := part_line(part, JUDGED_TOOL_INPUT))]
|
|
|
|
|
|
def part_line(part: Text | ToolCall, tool_input_chars: int) -> str:
|
|
if isinstance(part, ToolCall):
|
|
return f"[tool {part.name}] {json.dumps(part.input, ensure_ascii=False)[:tool_input_chars]}"
|
|
return part.text if part.text.strip() else ""
|