155 lines
6.9 KiB
Python
155 lines
6.9 KiB
Python
"""Entries of Claude Code's transcripts and of its stream-json and json output."""
|
|
import json
|
|
import typing
|
|
|
|
|
|
def parse_entry(raw: str | bytes) -> dict | None:
|
|
try:
|
|
entry = json.loads(raw)
|
|
except ValueError:
|
|
return None
|
|
return entry if isinstance(entry, dict) else None
|
|
|
|
|
|
def content(entry: dict) -> object:
|
|
message = entry.get("message")
|
|
return message.get("content") if isinstance(message, dict) else None
|
|
|
|
|
|
def parts(entry: dict) -> list:
|
|
found = content(entry)
|
|
return found if isinstance(found, list) else []
|
|
|
|
|
|
# Alike in the transcript and in stream-json: {"type": "assistant", "message": {"content": [{"type": "text", "text": "ok"}]}}
|
|
def assistant_parts(entry: dict) -> list:
|
|
return parts(entry) if entry.get("type") == "assistant" else []
|
|
|
|
|
|
def written_by_human(entry: dict) -> bool:
|
|
"""Whether the human wrote a "user" entry; Claude Code writes the rest."""
|
|
if tagged_as_injected(entry):
|
|
return False
|
|
text = content(entry)
|
|
return string_by_human(entry, text) if isinstance(text, str) else blocks_by_human(parts(entry))
|
|
|
|
|
|
# {"type": "user", "isMeta": true, "message": {"content": "<local-command-caveat>Caveat: ..."}}
|
|
# {"type": "user", "promptSource": "sdk", "message": {"content": "Continue the task; ..."}}
|
|
# {"type": "user", "promptSource": "system", "message": {"content": "<task-notification>..."}}
|
|
# {"type": "user", "isCompactSummary": true, "message": {"content": "This session is being continued from a previous conversation that ran out of context. ..."}}
|
|
def tagged_as_injected(entry: dict) -> bool:
|
|
return bool(entry.get("isMeta")) or bool(entry.get("isCompactSummary")) or entry.get("promptSource") in ("sdk", "system")
|
|
|
|
|
|
# {"type": "user", "promptSource": "typed", "message": {"content": "merge it"}}
|
|
# {"type": "user", "message": {"content": "<command-name>/model</command-name>\n..."}}
|
|
def string_by_human(entry: dict, text: str) -> bool:
|
|
# Without promptSource, nothing else says who wrote the entry, so a leading < counts as Claude Code's.
|
|
return entry.get("promptSource") == "typed" or not text.startswith("<")
|
|
|
|
|
|
# {"type": "user", "message": {"content": [{"type": "text", "text": "merge it"}]}}
|
|
# {"type": "user", "message": {"content": [{"tool_use_id": "toolu_01…", "type": "tool_result", "content": "hi"}]}}
|
|
# {"type": "user", "message": {"content": [{"type": "text", "text": "[Request interrupted by user]"}]}}
|
|
def blocks_by_human(blocks: list) -> bool:
|
|
texts = [part_text(block) for block in blocks]
|
|
return bool(texts) and all(text is not None and not text.startswith("[Request interrupted") for text in texts)
|
|
|
|
|
|
def human_text(entry: dict) -> str | None:
|
|
"""What the human wrote in the entry, or None where Claude Code wrote it."""
|
|
if (queued := queued_human_text(entry)) is not None:
|
|
return queued
|
|
if entry.get("type") != "user" or not written_by_human(entry):
|
|
return None
|
|
text = content(entry)
|
|
return text if isinstance(text, str) else "".join(part_text(part) or "" for part in parts(entry))
|
|
|
|
|
|
# {"type": "user", "promptSource": "sdk", "message": {"content": "Continue the task; the previous run ended before the chunk was finished."}}
|
|
def loop_text(entry: dict) -> str | None:
|
|
"""What loop-claude told the worker in a -p prompt."""
|
|
text = content(entry)
|
|
return text if entry.get("type") == "user" and entry.get("promptSource") == "sdk" and isinstance(text, str) else None
|
|
|
|
|
|
# What the human types while claude works, written only as this entry:
|
|
# {"type": "attachment", "attachment": {"type": "queued_command", "commandMode": "prompt", "origin": {"kind": "human"}, "prompt": "B"}}
|
|
def queued_human_text(entry: dict) -> str | None:
|
|
attachment = entry.get("attachment") if entry.get("type") == "attachment" else None
|
|
if not isinstance(attachment, dict) or attachment.get("type") != "queued_command" or not isinstance(origin := attachment.get("origin"), dict) or origin.get("kind") != "human":
|
|
return None
|
|
return prompt if isinstance(prompt := attachment.get("prompt"), str) else None
|
|
|
|
|
|
# {"type": "text", "text": "ok"}
|
|
def part_text(part: object) -> str | None:
|
|
return part["text"] if isinstance(part, dict) and part.get("type") == "text" and isinstance(part.get("text"), str) else None
|
|
|
|
|
|
# {"type": "tool_use", "id": "toolu_01…", "name": "Bash", "input": {"command": "echo hi"}}
|
|
def tool_call(part: object) -> tuple[object, object] | None:
|
|
return (part.get("name"), part.get("input")) if isinstance(part, dict) and part.get("type") == "tool_use" else None
|
|
|
|
|
|
def tool_use_id(part: object) -> str | None:
|
|
return part["id"] if isinstance(part, dict) and part.get("type") == "tool_use" and isinstance(part.get("id"), str) else None
|
|
|
|
|
|
class ToolResult(typing.NamedTuple):
|
|
tool_use_id: str
|
|
text: str
|
|
failed: bool
|
|
|
|
|
|
# {"type": "tool_result", "tool_use_id": "toolu_01…", "content": "hi"}, its content also as [{"type": "text", "text": "hi"}], and with "is_error": true where the call failed
|
|
def tool_result(part: object) -> ToolResult | None:
|
|
if not isinstance(part, dict) or part.get("type") != "tool_result":
|
|
return None
|
|
return ToolResult(str(part.get("tool_use_id")), result_text(part.get("content")), bool(part.get("is_error")))
|
|
|
|
|
|
def result_text(content: object) -> str:
|
|
if isinstance(content, str):
|
|
return content
|
|
# Claude Code may split one text across blocks, even inside a line, so the blocks join with nothing between them.
|
|
return "".join(part_text(part) or "" for part in content) if isinstance(content, list) else ""
|
|
|
|
|
|
# stream-json's last line: {"type": "result", "subtype": "success", ...}
|
|
def ends_stream(event: dict) -> bool:
|
|
return event.get("type") == "result"
|
|
|
|
|
|
# {"type": "result", "api_error_status": 429, "result": "You've hit your session limit · resets 7:40pm (Europe/Stockholm)", ...}
|
|
def hit_limit(event: dict) -> bool:
|
|
return ends_stream(event) and event.get("api_error_status") == 429
|
|
|
|
|
|
# {"type": "result", "structured_output": {"evidence": "...", ...}, ...}
|
|
def structured_output(result: dict) -> object:
|
|
return result.get("structured_output")
|
|
|
|
|
|
def limit_said(event: dict) -> str:
|
|
said = " ".join(result.split()) if isinstance(result := event.get("result"), str) else ""
|
|
return said or "claude gave no message"
|
|
|
|
|
|
# {"type": "rate_limit_event", "rate_limit_info": {"status": "rejected", "resetsAt": 1790790000, ...}}
|
|
def rejected_until(event: dict) -> int | None:
|
|
"""When a usage limit that rejected the request resets, in seconds since the epoch."""
|
|
info = event.get("rate_limit_info") if event.get("type") == "rate_limit_event" else None
|
|
if not isinstance(info, dict) or info.get("status") != "rejected":
|
|
return None
|
|
resets_at = info.get("resetsAt")
|
|
return resets_at if isinstance(resets_at, int) and not isinstance(resets_at, bool) else None
|
|
|
|
|
|
# A count Claude Code left out or wrote as another type adds nothing, so one odd entry leaves the rest of a figure standing.
|
|
def usage_count(usage: dict, field: str) -> int:
|
|
"""One token count of a message's usage: {"input_tokens": 2, "cache_creation_input_tokens": 14541, "output_tokens": 8, ...}"""
|
|
value = usage.get(field)
|
|
return value if isinstance(value, int) else 0
|