Files
gabrielvidalandClaude Opus 5.5 49eaac0f55 feat(parse): stepSince — when the model step now streaming was sent
Claude Code writes an api-request record as it sends a step and the
response's blocks only once it has ended, so the last request with no
blocks after it is a response still streaming. The detail carries its send
time (stepSince): what a queued follow-up or a finished task waits behind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 01:53:30 +01:00

178 lines
7.0 KiB
Python

"""The neutral transcript events (v1) — what a reader turns a harness's
records into and what the fold (``state.ParserState.apply``) reads.
An event is a plain dict with a ``t`` key: the same shape as a line of a v1
transcript on disk (``docs/transcript-format.md``). No classes on the hot
path — the claude reader builds thousands of these per transcript. ``at`` (an
ISO timestamp, or null) may ride on any event; ids are opaque strings unique
in the session. Unknown types and unknown keys are ignored by the fold, so a
newer converter does not break an older hub.
``FIELDS`` below is the contract: per type, the required fields and the
optional ones. ``validate`` checks one event against it (the v1 reader runs
it on every line, the tests on every event a reader emits). The doc lists
the same table; ``test_parse_events`` keeps the two in sync."""
V = 1
# type -> (required fields, optional fields). `t` and `at` are implied.
FIELDS: dict[str, tuple[tuple[str, ...], tuple[str, ...]]] = {
# Header (first line of a v1 file, `v` required there) and any change of
# a session fact afterwards. Only the fields that changed are present.
"session": ((), ("v", "id", "harness", "harnessVersion", "account", "machine",
"cwd", "branch", "sidechain", "agent", "parent")),
# Something a person (or the hub on their behalf) sent, already unwrapped.
"prompt": (("text",), ("id", "origin", "author", "images", "files")),
# Content put into the context that the user did not type.
"inject": (("kind",), ("name", "args", "text", "ref", "baseDir", "invoked", "notes",
"taskIds")),
# A model API call (one step) starts; the blocks that follow belong to it.
"call": ((), ("id", "request", "model", "effort", "turnEffort", "tier", "virtual",
"failed", "elapsedMs", "empty")),
"text": (("text",), ("call", "id", "paused")),
"thinking": (("text",), ("call",)),
"tool_call": (("tool",), ("id", "call", "native", "input", "caller")),
"tool_result": ((), ("toolCall", "ok", "text", "plainText", "data", "images", "async")),
# An asynchronous call's outcome, after its tool_result (a Code Mode script
# that settled): what it returned and how long it ran.
"tool_settled": (("toolCall",), ("text", "ms", "late")),
"usage": ((), ("call", "input", "output", "cacheRead", "cacheWrite5m", "cacheWrite1h",
"cacheWrite", "reasoning", "elapsedMs", "cost")),
"error": (("kind",), ("call", "id", "text", "resetsAt")),
"turn_end": (("reason",), ("durationMs", "heldS")),
"queue": (("op",), ("text",)),
"compact": ((), ("trigger", "preTokens", "postTokens", "durationMs")),
"agent": (("id",), ("toolCall", "state", "session")),
"meta": (("kind",), ("data", "toolCall", "text")),
# The harness was alive at `at` and nothing else happened; `busy`: it is
# (again) at work, which reopens a finished turn.
"tick": ((), ("busy", "request")),
}
PROMPT_ORIGINS = ("user", "queued", "inbox", "relay", "scheduled", "hook")
INJECT_KINDS = ("skill", "command", "reminder", "task_done", "compact_summary",
"held", "cancel", "note", "tasks_noted")
TURN_END_REASONS = ("done", "interrupted", "error", "held")
ERROR_KINDS = ("auth", "rate_limit", "overloaded", "api_key", "context", "network",
"cli_outdated", "unknown", "other")
QUEUE_OPS = ("enqueue", "dequeue", "remove")
META_KINDS = ("title", "mode", "cost_state", "pr", "hook_output")
USAGE_TOKENS = ("input", "output", "cacheRead", "cacheWrite5m", "cacheWrite1h",
"cacheWrite", "reasoning")
# Events that belong to the open step (a `call`): the fold collects them and
# folds the step once it is complete.
STEP_TYPES = frozenset(("usage", "text", "thinking", "tool_call", "error"))
_ENUMS = {
("prompt", "origin"): PROMPT_ORIGINS,
("inject", "kind"): INJECT_KINDS,
("turn_end", "reason"): TURN_END_REASONS,
("error", "kind"): ERROR_KINDS,
("queue", "op"): QUEUE_OPS,
("meta", "kind"): META_KINDS,
}
def validate(ev) -> dict:
"""``ev`` if it is a well-formed event, else ``ValueError`` naming why.
An unknown ``t`` is valid (the fold ignores it); unknown keys too."""
if not isinstance(ev, dict):
raise ValueError("an event is a JSON object")
t = ev.get("t")
if not isinstance(t, str) or not t:
raise ValueError("an event needs a string `t`")
at = ev.get("at")
if at is not None and not isinstance(at, str):
raise ValueError(f"{t}: `at` is an ISO timestamp string")
spec = FIELDS.get(t)
if spec is None:
return ev
for f in spec[0]:
if ev.get(f) is None:
raise ValueError(f"{t}: `{f}` is required")
for (et, f), allowed in _ENUMS.items():
if et == t and ev.get(f) is not None and ev[f] not in allowed:
raise ValueError(f"{t}: `{f}` must be one of {', '.join(allowed)}")
if t == "usage":
for k in USAGE_TOKENS:
v = ev.get(k)
if v is not None and (isinstance(v, bool) or not isinstance(v, (int, float))):
raise ValueError(f"usage: `{k}` is a number")
if t == "usage" and ev.get("cost") is not None:
c = ev["cost"]
if not isinstance(c, dict) or isinstance(c.get("usd"), bool) \
or not isinstance(c.get("usd"), (int, float)):
raise ValueError(f"{t}: `cost` is {{usd: number, source}}")
if t in ("text", "thinking", "prompt") and not isinstance(ev["text"], str):
raise ValueError(f"{t}: `text` is a string")
if t == "session" and ev.get("v") is not None and ev["v"] != V:
raise ValueError(f"session: this hub reads v{V}, not v{ev['v']}")
return ev
def is_v1_header(rec) -> bool:
"""A record that opens a v1 transcript (``{"t": "session", "v": 1, …}``)."""
return isinstance(rec, dict) and "t" in rec and "v" in rec
# Constructors, for converters and tests (the readers build literals inline).
def session(**f) -> dict:
return {"t": "session", **f}
def prompt(text: str, **f) -> dict:
return {"t": "prompt", "text": text, **f}
def inject(kind: str, **f) -> dict:
return {"t": "inject", "kind": kind, **f}
def call(**f) -> dict:
return {"t": "call", **f}
def text(text: str, **f) -> dict:
return {"t": "text", "text": text, **f}
def thinking(text: str, **f) -> dict:
return {"t": "thinking", "text": text, **f}
def tool_call(tool: str, **f) -> dict:
return {"t": "tool_call", "tool": tool, **f}
def tool_result(tool_call_id, **f) -> dict:
return {"t": "tool_result", "toolCall": tool_call_id, **f}
def usage(**f) -> dict:
return {"t": "usage", **f}
def error(kind: str, **f) -> dict:
return {"t": "error", "kind": kind, **f}
def turn_end(reason: str, **f) -> dict:
return {"t": "turn_end", "reason": reason, **f}
def queue(op: str, **f) -> dict:
return {"t": "queue", "op": op, **f}
def compact(**f) -> dict:
return {"t": "compact", **f}
def meta(kind: str, **f) -> dict:
return {"t": "meta", "kind": kind, **f}
def tick(**f) -> dict:
return {"t": "tick", **f}