"""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): """~/.claude.json, the model catalog folder and the projects folder.""" return home / ".claude.json", home / ".claude" / "cache" / "model-catalog", home / ".claude" / "projects" # /-home-me-code-log/.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 "" # .jsonl, /subagents/, and from older versions .superseded-1789290815002/ and .orphaned-*.jsonl def session_files(transcript): return glob.glob(glob.escape(transcript.removesuffix(".jsonl")) + "*") # One line of a transcript or of stream-json, or --output-format json's whole output. 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": "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": "/model\n..."}} # {"type": "user", "promptSource": "system", "message": {"content": "..."}} # {"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 if not parts(entry): return UserEntryKind.EMPTY # {"type": "user", "message": {"content": [{"tool_use_id": "toolu_01…", "type": "tool_result", "content": "hi"}]}} if any(not isinstance(part, dict) or part.get("type") != "text" or not isinstance(part.get("text"), str) for part in parts(entry)): return UserEntryKind.NON_TEXT # {"type": "user", "message": {"content": [{"type": "text", "text": "[Request interrupted by user]"}]}} if any(part["text"].startswith("[Request interrupted") for part in parts(entry)): return UserEntryKind.CTRL_C return UserEntryKind.HUMAN def typed(entry): return entry.get("type") == "user" and user_entry_kind(entry) is UserEntryKind.HUMAN # {"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 # /*.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 []