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

134 lines
5.1 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()
# <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/, <session id>.superseded-1789290815002/
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
# {"type": "user", "message": {"role": "user", "content": "merge it"}}
def content(entry):
message = entry.get("message")
return message.get("content") if isinstance(message, dict) else None
# {"type": "assistant", "message": {"content": [{"type": "text", "text": "ok"}]}}
def parts(entry):
found = content(entry)
return found if isinstance(found, list) 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": "typed", "message": {"content": "merge it"}}
if isinstance(text := content(entry), str):
return UserEntryKind.COMMAND if 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
# An "assistant" entry's part, alike in the transcript and in stream-json:
# {"type": "text", "text": "ok"}, {"type": "tool_use", "name": "Bash", "input": {"command": "echo hi"}}
def said(part, limit=400):
kind = part.get("type") if isinstance(part, dict) else None
if kind == "text" and isinstance(part.get("text"), str) and part["text"].strip():
return part["text"]
if kind == "tool_use":
return f"[tool {part.get('name')}] {json.dumps(part.get('input'))[:limit]}"
return ""
# 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", ...}]}}}
# The newest file has the highest fetchedAt.
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 []