Name each entry shape written_by_human checks, and annotate every parameter in loop_claude

This commit is contained in:
2026-10-01 23:47:03 +02:00
parent 70ad9a9caa
commit 39acf6dff0
24 changed files with 113 additions and 84 deletions
+2 -1
View File
@@ -1,9 +1,10 @@
import json
import pathlib
from loop_claude.claude_code.formats import models_in
def offered_models(folder) -> list[tuple[str, object]]:
def offered_models(folder: pathlib.Path) -> list[tuple[str, object]]:
files = []
for path in folder.glob("*.json"):
try:
+38 -28
View File
@@ -4,7 +4,7 @@ import json
from loop_claude.outcome import Failure
def parse(raw) -> dict | None:
def parse(raw: str | bytes) -> dict | None:
try:
entry = json.loads(raw)
except ValueError:
@@ -12,41 +12,52 @@ def parse(raw) -> dict | None:
return entry if isinstance(entry, dict) else None
def content(entry) -> object:
def content(entry: dict) -> object:
message = entry.get("message")
return message.get("content") if isinstance(message, dict) else None
def parts(entry) -> list:
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) -> list:
def assistant_parts(entry: dict) -> list:
return parts(entry) if entry.get("type") == "assistant" else []
def written_by_human(entry) -> bool:
def written_by_human(entry: dict) -> bool:
"""Whether the human wrote a "user" entry; Claude Code writes the rest."""
# {"type": "user", "isMeta": true, "message": {"content": "<local-command-caveat>Caveat: ..."}}
# {"type": "user", "promptSource": "sdk", "message": {"content": "Continue the task; ..."}}
if entry.get("isMeta") or entry.get("promptSource") == "sdk":
if tagged_as_injected(entry):
return False
# {"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"}}
# Claude Code tags what it injects, and an entry without promptSource carries no other mark, so a leading < is its own.
if isinstance(text := content(entry), str):
source = entry.get("promptSource")
return source != "system" and (source == "typed" or not text.startswith("<"))
texts = [part_text(part) for part in parts(entry)]
# {"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]"}]}}
text = content(entry)
return typed_string(entry, text) if isinstance(text, str) else typed_blocks(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>..."}}
def tagged_as_injected(entry: dict) -> bool:
return bool(entry.get("isMeta")) 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 typed_string(entry: dict, text: str) -> bool:
# An entry without promptSource carries no other mark, so a leading < is 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 typed_blocks(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) -> str | None:
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
@@ -58,7 +69,7 @@ def human_text(entry) -> str | 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) -> str | None:
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
@@ -66,29 +77,28 @@ def queued_human_text(entry) -> str | None:
# {"type": "text", "text": "ok"}
def part_text(part) -> str | None:
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", "name": "Bash", "input": {"command": "echo hi"}}
def tool_call(part) -> tuple[object, object] | None:
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
# stream-json's last line: {"type": "result", "subtype": "success", ...}
def ends_stream(event) -> bool:
def ends_stream(event: dict) -> bool:
return event.get("type") == "result"
# {"type": "result", "structured_output": {"evidence": "...", ...}, ...}
def structured_output(stdout) -> object:
def structured_output(stdout: str) -> object:
return (parse(stdout) or {}).get("structured_output")
# Claude Code's config: {"projects": {"/home/me/code/log": {"hasTrustDialogAccepted": true, ...}}, ...}
def mark_trusted(config, roots) -> tuple[dict, list[str]] | Failure:
projects = config.get("projects", {}) if isinstance(config, dict) else None
if not isinstance(projects, dict):
def mark_trusted(config: object, roots: list[str]) -> tuple[dict, list[str]] | Failure:
if not isinstance(config, dict) or not isinstance(projects := config.get("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")
@@ -98,7 +108,7 @@ def mark_trusted(config, roots) -> tuple[dict, list[str]] | Failure:
# A model catalog file: {"fetchedAt": 1790618085238, "catalog": {"config": {"models": [{"id": "claude-opus-5-5", "name": "Opus 5.5", ...}]}}}
def models_in(files) -> list[tuple[str, object]]:
def models_in(files: list[object]) -> list[tuple[str, object]]:
"""The (id, name) of each model in the newest of the parsed catalog files."""
newest: dict = {}
for data in files:
+5 -3
View File
@@ -6,6 +6,8 @@ import shutil
import sys
import uuid
from loop_claude.paths import Paths
NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
@@ -17,19 +19,19 @@ class Session:
name: str
def session_for(project, paths) -> Session:
def session_for(project: str, paths: Paths) -> Session:
# "A " is the human's cue in the session picker that the session is the loop's.
name = f"A {project} loop-claude"
return Session(id=uuid.uuid5(NAMESPACE, name), claude_code_transcripts=paths.claude_code_transcripts, name=name)
# <claude_code_transcripts>/-home-me-code-log/<session id>.jsonl
def transcript_file(session) -> str:
def transcript_file(session: Session) -> str:
hit = glob.glob(os.path.join(glob.escape(str(session.claude_code_transcripts)), "*", f"{session.id}.jsonl"))
return hit[0] if hit else ""
def delete_session(session) -> None:
def delete_session(session: Session) -> None:
path = transcript_file(session)
if not path:
return
+4 -4
View File
@@ -4,7 +4,7 @@ from loop_claude.claude_code.formats import assistant_parts, human_text, parse,
from loop_claude.outcome import Failure
def read(path) -> list[dict] | Failure:
def read(path: str) -> list[dict] | Failure:
try:
with open(path, "rb") as handle:
return [entry for raw in handle if (entry := parse(raw))]
@@ -12,11 +12,11 @@ def read(path) -> list[dict] | Failure:
return Failure(f"could not read the transcript {path}: {failure.strerror}")
def human_turns(entries) -> int:
def human_turns(entries: list[dict]) -> int:
return sum(1 for entry in entries if human_text(entry) is not None)
def render(entries) -> str:
def render(entries: list[dict]) -> str:
lines = []
for entry in entries:
lines += [line for part in assistant_parts(entry) if (line := part_line(part))]
@@ -25,7 +25,7 @@ def render(entries) -> str:
return "\n\n".join(lines)
def part_line(part, limit=400) -> str:
def part_line(part: object, limit: int = 400) -> str:
if (text := part_text(part)) and text.strip():
return text
if call := tool_call(part):
+2 -1
View File
@@ -1,4 +1,5 @@
import json
import pathlib
import sys
from loop_claude.claude_code.formats import mark_trusted
@@ -7,7 +8,7 @@ from loop_claude.outcome import Failure
# A failure only warns: the interrupt still runs, and the human answers Claude Code's trust dialog.
def trust(config, roots) -> None:
def trust(config: pathlib.Path, roots: list[str]) -> None:
try:
with open(config, encoding="utf-8") as handle:
data = json.load(handle)