Files
claude-config/bin/loop_claude/claude_code/formats.py
T

156 lines
6.0 KiB
Python

"""Every Claude Code format loop-claude reads, each under a sample of it, as Claude Code 2.1.284 writes it."""
import enum
import glob
import json
import os
from loop_claude.outcome import Failure
class UserEntryKind(enum.Enum):
"""Who wrote a "user" entry: the human wrote HUMAN, Claude Code every other kind."""
COMMAND = enum.auto()
CTRL_C = enum.auto()
EMPTY = enum.auto()
HUMAN = enum.auto()
META = enum.auto()
NON_TEXT = enum.auto()
SDK_PROMPT = enum.auto()
def locations(home):
return home / ".claude.json", home / ".claude" / "cache" / "model-catalog", home / ".claude" / "projects"
# <projects>/-home-me-code-log/<session id>.jsonl
def transcript_path(projects, session_id):
hit = glob.glob(os.path.join(glob.escape(str(projects)), "*", f"{session_id}.jsonl"))
return hit[0] if hit else ""
# <session id>.jsonl, <session id>/subagents/, and from older versions <session id>.superseded-1789290815002/ and <session id>.orphaned-*.jsonl
def session_files(transcript):
return glob.glob(glob.escape(transcript.removesuffix(".jsonl")) + "*")
def parse(raw):
try:
entry = json.loads(raw)
except ValueError:
return None
return entry if isinstance(entry, dict) else None
def content(entry):
message = entry.get("message")
return message.get("content") if isinstance(message, dict) else None
def parts(entry):
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):
return parts(entry) if entry.get("type") == "assistant" else []
def user_entry_kind(entry):
# {"type": "user", "isMeta": true, "message": {"content": "<local-command-caveat>Caveat: ..."}}
if entry.get("isMeta"):
return UserEntryKind.META
# {"type": "user", "promptSource": "sdk", "message": {"content": "Continue the task; ..."}}
if entry.get("promptSource") == "sdk":
return UserEntryKind.SDK_PROMPT
# {"type": "user", "message": {"content": "<command-name>/model</command-name>\n..."}}
# {"type": "user", "promptSource": "system", "message": {"content": "<task-notification>..."}}
# {"type": "user", "promptSource": "typed", "message": {"content": "merge it"}}
if isinstance(text := content(entry), str):
source = entry.get("promptSource")
return UserEntryKind.COMMAND if source == "system" or (source != "typed" and text.startswith("<")) else UserEntryKind.HUMAN
texts = [part_text(part) for part in parts(entry)]
if not texts:
return UserEntryKind.EMPTY
# {"type": "user", "message": {"content": [{"tool_use_id": "toolu_01…", "type": "tool_result", "content": "hi"}]}}
if None in texts:
return UserEntryKind.NON_TEXT
# {"type": "user", "message": {"content": [{"type": "text", "text": "[Request interrupted by user]"}]}}
if any(text.startswith("[Request interrupted") for text in texts):
return UserEntryKind.CTRL_C
return UserEntryKind.HUMAN
def human_text(entry):
"""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 user_entry_kind(entry) is not UserEntryKind.HUMAN:
return None
text = content(entry)
return text if isinstance(text, str) else "".join(part_text(part) or "" for part in parts(entry))
# 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):
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):
return part["text"] if isinstance(part, dict) and part.get("type") == "text" and isinstance(part.get("text"), str) else None
# {"type": "tool_use", "name": "Bash", "input": {"command": "echo hi"}}
def tool_call(part):
return (part.get("name"), part.get("input")) if isinstance(part, dict) and part.get("type") == "tool_use" else None
# stream-json's last line: {"type": "result", "subtype": "success", ...}
def ends_stream(event):
return event.get("type") == "result"
# {"type": "result", "structured_output": {"evidence": "...", ...}, ...}
def structured_output(stdout):
return (parse(stdout) or {}).get("structured_output")
# ~/.claude.json: {"projects": {"/home/me/code/log": {"hasTrustDialogAccepted": true, ...}}, ...}
def trust_records(config):
projects = config.setdefault("projects", {}) if isinstance(config, dict) else None
if not isinstance(projects, dict):
return Failure('not an object whose "projects" is an object')
if (wrong := next((path for path, record in projects.items() if not isinstance(record, dict)), None)) is not None:
return Failure(f"projects[{json.dumps(wrong)}] is not an object")
return projects
def mark_trusted(projects, roots):
untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")]
for path in untrusted:
projects.setdefault(path, {})["hasTrustDialogAccepted"] = True
return untrusted
# <model catalog>/*.json: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}}
def catalog(folder):
newest = {}
for path in folder.glob("*.json"):
try:
with open(path, encoding="utf-8") as handle:
data = json.load(handle)
except (OSError, ValueError):
continue
if isinstance(data, dict) and isinstance(data.get("fetchedAt"), (int, float)) and data["fetchedAt"] > newest.get("fetchedAt", -1):
newest = data
models = newest
for key in ("catalog", "config", "models"):
models = models.get(key) if isinstance(models, dict) else None
return [(entry["id"], entry.get("name", entry["id"])) for entry in models if isinstance(entry, dict) and isinstance(entry.get("id"), str)] if isinstance(models, list) else []