- conversations/pricing.py holds no table any more (MODEL_PRICES, FAMILY_FALLBACK,
FAST_MULT, HAIKU_LONG, OPENAI_*, GEMINI_*, OTHER_PRICES, LOCAL_WATTS,
ELECTRICITY_EUR_PER_KWH, EVOX2_*, PLAN_METER_AS, PLAN_FABLE_WEIGHT gone): a
facade over the provider plugins' registry, same names and signatures;
PRICE_BOOK / USD_PER_EUR / LOCAL_* derived lazily from the plugins;
book_key() replaces openai_model / gemini_model; price_call() exposed.
- plugins/seed_registry.py: effective() = the bound store's registry when it
has ever known a provider (strict plugin-only), else the default plugins
read from PLUGINS_SEED_DIR / the plugins checkout / fixtures — offline
parses, scripts and unit tests price with zero setup, no network.
- parser: each API call priced once through ProviderRegistry.price_call
(UsageMeter.price) — list cost, cache share and the EVOX2's time from the
CallCost, plan units passed apart into the meter; priceBook = price_book().
- projects/costs.py: rates + local outputWeight from provider-evox2's pricing.
- usage/service.remote_snapshots: one loop over the providers with a
usageReader, GET /usage/{vendor} on the lab and online workers, the legacy
/claude|opencode|agy/usage only on a 404 (or the lab not answering);
per-vendor merge policies keep the exact old results.
- providers.py: per-id memo of the claiming pricer and the token-table key
(fixed per registry) — the parse prices at the old speed.
- plugins/metering.py reads USD_PER_EUR at use time.
A/B: scripts/ab/pricing-dump.py --base 1e431f52 → identical (10104 lines);
scripts/ab/parse-ab.py --base 1e431f52 --chunked → 499 files × 2 modes,
0 differing; chunked == one-shot.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1356 lines
68 KiB
Python
1356 lines
68 KiB
Python
"""``ParserState``: the resumable transcript parser — feed records one by one,
|
||
snapshot the summary (and, when ``full``, the thread) any time — and
|
||
``parse_conversation``, its one-shot wrapper.
|
||
|
||
The parser is a fold over the neutral events of ``events.py``: ``feed``
|
||
hands a record to the transcript's reader (``readers/``, picked from the
|
||
first record), which returns its events, and ``apply`` folds each one in.
|
||
Nothing here reads a harness's record shapes or text conventions, and tool
|
||
calls are known by their neutral names only (``readers/toolnames.py``)."""
|
||
|
||
import pathlib
|
||
import re
|
||
|
||
from .. import bashdiff, closing_notify, codemode, commits as gitcommits, mcpresult, taskevents, written
|
||
from ..resources import ResourceMiner
|
||
|
||
from .. import pricing
|
||
from ..pricing import (
|
||
add_usage,
|
||
usage_tokens,
|
||
)
|
||
from .records import (
|
||
_ms,
|
||
_bin5,
|
||
_elapsed_ms,
|
||
MAX_BLOCK,
|
||
_clip,
|
||
_search_clip,
|
||
_iter_records,
|
||
_item,
|
||
)
|
||
from .usertext import (
|
||
_DONE_RE,
|
||
_COMPLETED_RE,
|
||
MAX_SKILL_PROMPT,
|
||
_rel_skill_path,
|
||
)
|
||
from .tools import (
|
||
TOOL_BUCKET_ORDER,
|
||
_EDIT_TOOLS,
|
||
_MAX_WRITTEN_DIRS,
|
||
_MAX_GIT_ROOTS,
|
||
_MAX_WORKTREE_ADDS,
|
||
_COMMIT_CMD_RE,
|
||
_LOG_ONE_RE,
|
||
_AGENT_ASYNC_RE,
|
||
_AGENT_RESUMED_RE,
|
||
_MEMORY_RE,
|
||
_deployed_url,
|
||
_lifecycle_stages,
|
||
_deploy_call,
|
||
_bucket,
|
||
_subkey,
|
||
_TASK_STATES,
|
||
_task_subject,
|
||
todo_op,
|
||
_projects_in,
|
||
_services_in,
|
||
_worktree_events,
|
||
)
|
||
from .errors import _real_model
|
||
from .events import STEP_TYPES
|
||
from .readers import reader_for
|
||
from .turns import TurnState
|
||
from .usage import (
|
||
UsageMeter,
|
||
_DELTA_KEYS,
|
||
norm,
|
||
)
|
||
|
||
# Claude Code session ids (= main transcript file stems) are UUIDs.
|
||
_UUID_RE = re.compile(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}"
|
||
r"-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
|
||
|
||
|
||
class ParserState:
|
||
"""Resumable transcript parser: feed records one by one, snapshot anytime.
|
||
|
||
Holds exactly the cross-record state ``parse_conversation`` used to keep in
|
||
locals, so the indexer can parse a *growing* live transcript incrementally —
|
||
restore the state, feed only the appended JSONL lines, snapshot the summary
|
||
again — instead of re-reading the whole file on every watcher tick.
|
||
``summary()`` is a pure snapshot (it never mutates parser state), so it can
|
||
be called repeatedly between feeds. The live state is the reader's (small:
|
||
see ``readers/claude.py``) plus this fold's."""
|
||
|
||
def __init__(self, path: pathlib.Path, full: bool = False):
|
||
self.path = path
|
||
self.full = full
|
||
# A main transcript is named `<sessionId>.jsonl`, and the file name is
|
||
# the only trustworthy identity: a resumed / forked / compacted session
|
||
# starts with history lines copied from its *source* session, whose
|
||
# `sessionId` fields still name that source. Seeding from the first
|
||
# record attributed those conversations to their origin — meta sidecar
|
||
# reads (title, state, projects) landed on the wrong conversation, so
|
||
# renaming one card appeared to rename another. Subagent transcripts
|
||
# (`agent-<id>.jsonl`, no UUID stem) keep the record fallback: their
|
||
# `sessionId` intentionally names the parent.
|
||
self.session_id = path.stem if _UUID_RE.fullmatch(path.stem) else None
|
||
self.cwd = None
|
||
self.git_branch = None
|
||
self.model = None
|
||
# Every model that produced a turn here, model id -> assistant records
|
||
# seen. A session can switch models mid-thread, so the viewer tags a
|
||
# conversation with all of them, busiest first.
|
||
self.model_turns: dict[str, int] = {}
|
||
# Same idea for the claude CLI's `--effort` level (low…max), which it
|
||
# stamps on each assistant record: a session can be resumed at another
|
||
# level, so we keep every one seen, busiest first.
|
||
self.effort_turns: dict[str, int] = {}
|
||
# When this run was actually working, as model id -> the set of
|
||
# 5-minute wall-clock bins (see `_bin5`) it produced a turn in. The
|
||
# activity dashboard counts *distinct agents per bin*, so presence is
|
||
# all that's needed — a bin is either worked in or it isn't. Collected
|
||
# here because the parser is already walking every record: deriving it
|
||
# later would mean a second pass over the whole archive.
|
||
self.active_bins: dict[str, set[int]] = {}
|
||
self.ai_title = None
|
||
# Login health (accounts/health.py): the newest API-error turn the CLI
|
||
# wrote (`{kind, at, message}`) and the newest turn a real model
|
||
# answered. An error newer than the last answer is the session's
|
||
# *trailing* error — "OAuth session expired and could not be refreshed"
|
||
# is how a signed-out account first shows up.
|
||
self.api_error: dict | None = None
|
||
self.reply_at: str | None = None
|
||
self.first_user = None
|
||
self.started = None
|
||
self.ended = None
|
||
self.user_turns = 0
|
||
self.assistant_turns = 0
|
||
# A subagent (sidechain) transcript lives at
|
||
# `<convId>/subagents/agent-*.jsonl`; every record carries
|
||
# `isSidechain: true` and an `agentId` (its `sessionId` is the parent's).
|
||
self.is_sidechain = False
|
||
self.agent_id = None
|
||
# Which agent harness wrote the transcript, when its events say so
|
||
# (``session.harness``: the opencode / agy mirrors' records, a v1
|
||
# header; a session started in a terminal has no stamp to tell).
|
||
self.harness = None
|
||
# Claude Code's Code Mode (a ``meta`` of kind ``mode``, on every turn
|
||
# of a session started in it).
|
||
self.code_mode_on = False
|
||
# A step's content written before its usage (the opencode mirror
|
||
# writes a step as soon as the model's stream ends, its tokens once
|
||
# its tools have run): call key → the attribution its usage record,
|
||
# content-less, takes over (bucket, sub-label, the card for the delta).
|
||
self._unpriced: dict[tuple, dict] = {}
|
||
# One API call = one priced usage. Claude Code writes an assistant
|
||
# message as one record *per content block* (thinking, text, each
|
||
# tool_use), every one repeating the call's full `usage` — summing them
|
||
# counted a call ~1.9× on average. Keyed on (message id, request id):
|
||
# the first record prices the call, later ones only re-home its
|
||
# attribution onto the tool they carry (see `_rehome`).
|
||
self._calls: dict[tuple, dict] = {}
|
||
# What these calls used and cost (usage.py): totals, the per-model /
|
||
# per-effort split, plan units, hour bins, the EVOX2's share, the
|
||
# context size and cache TTL, compactions and what a `/compact` saved,
|
||
# the first call's context split, the by-activity breakdown.
|
||
self.usage = UsageMeter()
|
||
self._compact_item = None # the last compaction's thread item (full mode)
|
||
# The thread item of the user's first message (full mode): the split is
|
||
# stamped onto it once the first assistant usage arrives, so the viewer
|
||
# shows "context + message" right on that bubble. Patching an appended
|
||
# item later is the same pattern tool results use (`tool_items`).
|
||
self._first_user_item = None
|
||
self.projects: set[str] = set()
|
||
self.services: set[str] = set()
|
||
# Where the session wrote (dirs of every written file), the git roots
|
||
# the Bash hook saw (root -> its main checkout, when a linked worktree
|
||
# says so) and the `git worktree add`s it ran: what a worker
|
||
# conversation's project is deduced from (conversations/written.py,
|
||
# projects/workers.py) — the hub can't look at a worker's disk.
|
||
self.written_dirs: set[str] = set()
|
||
self.git_roots: dict[str, str | None] = {}
|
||
self.worktree_adds: list[dict] = []
|
||
# Git worktrees created/removed, keyed by directory basename.
|
||
self.worktrees: dict[str, dict] = {}
|
||
# The commits this session made (conversations/commits.py), oldest
|
||
# first, and the remote-tracking refs its pushes moved.
|
||
self.commits: list[dict] = []
|
||
self.pushes: list[dict] = []
|
||
# Bash calls whose output may carry git's `[branch sha] subject` line
|
||
# → True when the command also prints the new commit with a one-line
|
||
# `git log -1` (`sha subject`, a quiet commit's only trace).
|
||
self.commit_calls: dict[str, bool] = {}
|
||
# When each pending Bash call started — a commit the hook dates before
|
||
# it can't be one the call made (see the hook attachment below).
|
||
self.bash_started: dict[str, str] = {}
|
||
self.skills: dict[str, dict] = {}
|
||
# Task list (TaskCreate/TaskUpdate or the older TodoWrite snapshots),
|
||
# keyed by sequential string id; insertion order ≈ creation order.
|
||
self.tasks: dict[str, dict] = {}
|
||
self.task_seq = 0 # running counter → next task id
|
||
self.lifecycle: dict[str, str] = {} # stage -> latest evidence ts
|
||
self.memories_read: set[str] = set()
|
||
self.last_assistant_text = "" # final assistant text (DONE marker)
|
||
# The latest ```notify block a main-thread message ended on
|
||
# (closing_notify.py): its fields + the record's uuid and time.
|
||
self.closing_notify: dict | None = None
|
||
# Trailing interrupt / "No response requested." markers — cleared by any
|
||
# later real activity; interrupt outranks paused.
|
||
self.interrupted_trailing = False
|
||
self.paused_trailing = False
|
||
# Claude parked itself: the last thing it did was schedule a wake-up
|
||
# (ScheduleWakeup) or block on a Monitor — the run sits idle until the
|
||
# trigger fires, so the viewer shows it "paused" rather than "running".
|
||
# Cleared by any later tool call, real user turn, or interrupt (NOT by
|
||
# the same turn's closing text — "I'll check back in 20 min" still ends
|
||
# with the run parked).
|
||
self.waiting_trailing = False
|
||
# Whether the model's turn is over, and the run's input queue
|
||
# (turns.py).
|
||
self.turn_state = TurnState()
|
||
self.tool_name: dict[str, str] = {}
|
||
self.tool_items: dict[str, dict] = {} # tool_use_id -> thread item
|
||
# background task id -> the card that started it (Monitor, background
|
||
# Bash, Workflow) — see `taskevents`
|
||
self.task_items: dict[str, dict] = {}
|
||
# agentId / agent name -> its Agent card, for a SendMessage naming it
|
||
self.agent_cards: dict[str, dict] = {}
|
||
# The thread item carrying the current assistant turn's cost (reset per
|
||
# assistant record) — its activity bucket is stamped on once known.
|
||
self._turn_item: dict | None = None
|
||
# Open Task/Agent calls: an entry here *is* a running subagent.
|
||
self.agent_calls: dict[str, dict] = {}
|
||
# agentId -> its call, kept once it closes: what a SendMessage that
|
||
# resumes the agent reopens.
|
||
self.agent_ids: dict[str, dict] = {}
|
||
# Set while a deploy command (Bash or the deploy-html skill) has been
|
||
# issued and hasn't returned yet — cleared on its tool_result.
|
||
self.deploying_since: str | None = None
|
||
self._deploying_tool_use_id: str | None = None
|
||
# Each skill's latest injected prompt here: name → {text, at, baseDir}.
|
||
self.skill_prompts: dict[str, dict] = {}
|
||
self.thread: list[dict] = []
|
||
self.turns: list[dict] = []
|
||
# What the thread's clipped fields held in full (`_set_clipped`): clip
|
||
# id → (its item, {field: full text}). The item carries `clipId` and
|
||
# `clipped` ({field: full length}); the viewer's *Show more* asks
|
||
# for the rest (`clip_fields`). Ids follow the transcript's order, so a
|
||
# fresh parse of the same file gives the same ones.
|
||
self._clips: list[tuple[dict, dict[str, str]]] = []
|
||
# Full-text search index: one entry per user/assistant text block, in
|
||
# transcript order (`i` matches the thread items' `mi`).
|
||
self.search_msgs: list[dict] = []
|
||
# The Linear issues / PRs / branches / Slack threads this conversation
|
||
# is about (resources.py) — fed every record's events, and each real
|
||
# user turn.
|
||
self.res = ResourceMiner()
|
||
# The transcript's reader (readers/), picked from its first record.
|
||
self.reader = None
|
||
# The model step being collected: its ``call`` event, then its usage
|
||
# and blocks — folded once complete (``_close_step``).
|
||
self._step: list[dict] | None = None
|
||
# The cwd the current record names (None when it names none): where
|
||
# a Bash call's relative paths resolve.
|
||
self._rec_cwd = None
|
||
|
||
# The fields that moved onto the meter (``self.usage``) and the turn state
|
||
# (``self.turn_state``) stay readable here — ``st.cost_total``,
|
||
# ``st.turn_ended`` — for any caller that read them off the parser.
|
||
_USAGE_FIELDS = frozenset({
|
||
"agg", "plan_units", "by_model", "meter_bins", "fast_calls", "cost_total",
|
||
"local", "context_tokens", "context_model", "last_call_at", "cache_ttl",
|
||
"compactions", "first_context_tokens", "first_message_tokens", "by_tool",
|
||
"by_tool_cost", "by_tool_sub", "by_tool_sub_cost"})
|
||
_TURN_FIELDS = frozenset({"turn_ended", "queue"})
|
||
|
||
def __getattr__(self, name):
|
||
# Only reached for names the instance doesn't have.
|
||
if name in ParserState._USAGE_FIELDS:
|
||
return getattr(self.usage, name)
|
||
if name in ParserState._TURN_FIELDS:
|
||
return getattr(self.turn_state, name)
|
||
raise AttributeError(f"{type(self).__name__!r} object has no attribute {name!r}")
|
||
|
||
def queued_followups(self) -> list[dict]:
|
||
"""The user's follow-ups a live run has queued but not read yet
|
||
(``TurnState.queued_followups``)."""
|
||
return self.turn_state.queued_followups()
|
||
|
||
def _add_search(self, role: str, text: str) -> int:
|
||
idx = len(self.search_msgs)
|
||
self.search_msgs.append(
|
||
{"i": idx, "role": role, "text": _search_clip(text)})
|
||
return idx
|
||
|
||
def _count_skill(self, name: str, ts) -> None:
|
||
e = self.skills.setdefault(name, {"count": 0, "last": None})
|
||
e["count"] += 1
|
||
if ts and (e["last"] is None or ts > e["last"]):
|
||
e["last"] = ts
|
||
|
||
def _agents_done(self, notes: list[dict]) -> None:
|
||
"""Close the agent calls the task notifications say stopped: by the
|
||
tool-use id they name — or, for an agent a SendMessage resumed (its
|
||
notification names that SendMessage), by its agentId, the
|
||
notification's task id."""
|
||
for note in notes:
|
||
self.agent_calls.pop(note.get("toolUseId") or "", None)
|
||
for tid in note.get("taskIds") or []:
|
||
call = self.agent_ids.get(tid)
|
||
if call is not None:
|
||
self.agent_calls.pop(call["toolUseId"], None)
|
||
|
||
def _task_notes(self, notes: list[dict], ts) -> None:
|
||
"""Fold the task notifications into the cards that started their
|
||
tasks (``taskevents``). Agent cards keep their own bookkeeping
|
||
(``agent_calls``)."""
|
||
if not self.full:
|
||
return
|
||
for note in notes:
|
||
tu = self.tool_items.get(note["toolUseId"]) if note["toolUseId"] else None
|
||
cards = [tu] if tu is not None else [
|
||
self.task_items[i] for i in note["taskIds"] if i in self.task_items]
|
||
for card in cards:
|
||
if card.get("name") != "agent" and not taskevents.delivered(card, note, ts):
|
||
taskevents.apply(card, note, ts)
|
||
|
||
def _queued_notes(self, text, ts, op: str) -> None:
|
||
"""A ``<task-notification>`` the CLI queued (``enqueue``: the task
|
||
ended now, read or not — ``taskevents.queued``) or handed the model
|
||
mid-turn (``remove``: read now; its attachment, stamped with the
|
||
enqueue time, follows)."""
|
||
if not self.full or not isinstance(text, str) or "<task-notification>" not in text:
|
||
return
|
||
for note in taskevents.parse(text):
|
||
tu = self.tool_items.get(note["toolUseId"]) if note["toolUseId"] else None
|
||
cards = [tu] if tu is not None else [
|
||
self.task_items[i] for i in note["taskIds"] if i in self.task_items]
|
||
for card in cards:
|
||
if card.get("name") == "agent":
|
||
continue
|
||
if op == "enqueue":
|
||
taskevents.queued(card, note, ts)
|
||
else:
|
||
taskevents.delivered(card, note, ts)
|
||
|
||
# ── feeding ─────────────────────────────────────────────────────────────
|
||
def feed(self, o: dict) -> None:
|
||
"""Fold one transcript record into the state: its reader turns it into
|
||
a batch of events, folded in order; a model step still open at the end
|
||
of the batch is folded then."""
|
||
if self.reader is None:
|
||
self.reader = reader_for(o, self.full)
|
||
evs = self.reader.feed(o)
|
||
self.res.feed_events(evs)
|
||
for ev in evs:
|
||
self.apply(ev)
|
||
if self._step is not None:
|
||
self._close_step()
|
||
|
||
def apply(self, ev: dict) -> None:
|
||
"""Fold one event (``events.py``) into the state."""
|
||
t = ev["t"]
|
||
at = ev.get("at")
|
||
if at:
|
||
self.started = self.started or at
|
||
self.ended = at
|
||
if self._step is not None:
|
||
if t in STEP_TYPES:
|
||
self._step.append(ev)
|
||
return
|
||
self._close_step()
|
||
elif t in STEP_TYPES:
|
||
# A block (or a late usage) whose call is not open: its own step.
|
||
self._on_call({"t": "call", "at": at, "id": ev.get("call"),
|
||
"empty": t == "usage"})
|
||
self._step.append(ev)
|
||
return
|
||
h = _APPLY.get(t)
|
||
if h is not None:
|
||
h(self, ev)
|
||
|
||
def _on_session(self, ev: dict) -> None:
|
||
# The first truthy value of each fact wins (a resumed / forked session
|
||
# starts with its source's records); the reader emits a fact again
|
||
# only when it changes.
|
||
if "id" in ev:
|
||
self.session_id = self.session_id or ev["id"]
|
||
if "cwd" in ev:
|
||
# cwd only seeds the human-readable project *label* (_project_name);
|
||
# it does NOT auto-tag a project — a conversation is tagged only for
|
||
# projects/services it actually edited (see _EDIT_TOOLS below).
|
||
self._rec_cwd = ev["cwd"]
|
||
if ev["cwd"]:
|
||
self.cwd = self.cwd or ev["cwd"]
|
||
if "branch" in ev:
|
||
self.git_branch = self.git_branch or ev["branch"]
|
||
parent = ev.get("parent")
|
||
if "agent" in ev:
|
||
self.agent_id = self.agent_id or ev["agent"]
|
||
elif isinstance(parent, dict) and parent.get("agent"):
|
||
self.agent_id = self.agent_id or parent["agent"]
|
||
if ev.get("sidechain") is True or parent:
|
||
self.is_sidechain = True
|
||
if ev.get("harness"):
|
||
self.harness = ev["harness"]
|
||
|
||
def _on_tick(self, ev: dict) -> None:
|
||
if ev.get("busy"):
|
||
self.turn_state.busy()
|
||
if ev.get("request"):
|
||
self.turn_state.step_since = ev.get("at")
|
||
|
||
def _on_meta(self, ev: dict) -> None:
|
||
kind = ev.get("kind")
|
||
if kind == "title":
|
||
if ev.get("data"):
|
||
self.ai_title = ev["data"]
|
||
elif kind == "mode":
|
||
self.code_mode_on = self.code_mode_on or ev.get("data") is True
|
||
elif kind == "cost_state":
|
||
if isinstance(ev.get("data"), dict):
|
||
self.usage.cost_state(ev["data"])
|
||
elif kind == "hook_output":
|
||
self.turn_state.busy()
|
||
self._hook_output(ev)
|
||
|
||
def _on_queue(self, ev: dict) -> None:
|
||
self.turn_state.queue_op(ev.get("op"), ev.get("text"), ev.get("at"))
|
||
if ev.get("op") in ("enqueue", "remove"):
|
||
self._queued_notes(ev.get("text"), ev.get("at"), ev["op"])
|
||
|
||
def _on_turn_end(self, ev: dict) -> None:
|
||
self.turn_state.step_since = None
|
||
reason = ev.get("reason")
|
||
if reason == "interrupted":
|
||
# The user interrupted: the run is trailing-interrupted (a compact
|
||
# tag in the thread), which is no turn of the user's.
|
||
self.interrupted_trailing = True
|
||
self.paused_trailing = self.waiting_trailing = False
|
||
if self.full:
|
||
self.thread.append(_item("user", "interrupted", False, 0, ts=ev.get("at")))
|
||
self.turn_state.end(reason)
|
||
|
||
def _on_compact(self, ev: dict) -> None:
|
||
self._compact_boundary(ev, ev.get("at"))
|
||
|
||
def _hook_output(self, ev: dict) -> None:
|
||
"""The ai-agent's Bash diff hook (sidecar/bash_diff.py) for a call:
|
||
the files it changed tag the conversation like an Edit's target
|
||
would, and on the card it replaces the harness's own diff — it's
|
||
exact. The commits it saw are the conversation's."""
|
||
ts, tid, stdout = ev.get("at"), ev.get("toolCall"), ev.get("text") or ""
|
||
gc = gitcommits.load_hook(stdout)
|
||
self._note_roots(gc)
|
||
started = _ms(self.bash_started.pop(tid, None))
|
||
if gc is not None:
|
||
found = gitcommits.from_hook(gc, tool_use_id=tid, ts=ts)
|
||
# The hook keeps only what the call created; a record from a
|
||
# hook updated mid-call (no baseline) carried all history.
|
||
# Commit and call share a clock — the runner's.
|
||
if started is not None:
|
||
found = [c for c in found
|
||
if (_ms(c.get("date")) or started) >= started - 5000]
|
||
gitcommits.add(self.commits, found)
|
||
self.pushes += gitcommits.pushed_refs(gc)
|
||
tu = self.tool_items.get(tid) if self.full else None
|
||
if tu is not None and found:
|
||
tu["commits"] = [{**c, "diffFiles": gitcommits.file_diffs(gc, c["sha"])}
|
||
for c in found]
|
||
d = bashdiff.load_hook(stdout)
|
||
if d is not None:
|
||
self._note_roots(d)
|
||
for path in bashdiff.changed_paths(d):
|
||
self.projects |= _projects_in(path)
|
||
self.services |= _services_in(path)
|
||
self._note_written(path)
|
||
tu = self.tool_items.get(tid) if self.full else None
|
||
view = bashdiff.from_hook(d) if tu is not None else None
|
||
if view is not None:
|
||
tu["bashDiff"] = view
|
||
|
||
def _set_clipped(self, it: dict, field: str, text: str | None,
|
||
markdown: bool = True, shown: str | None = None) -> None:
|
||
"""``it[field] = text`` cut to ``MAX_BLOCK`` (``shown``: a shorter form
|
||
already made, e.g. a compacted MCP result), keeping the full text for
|
||
*Show more* when what ships is not all of it."""
|
||
if text is None and shown is None:
|
||
return # no text: no key (as `_item` leaves it out)
|
||
cut = _clip(text if shown is None else shown, markdown)
|
||
it[field] = cut
|
||
n = it.get("clipId")
|
||
if cut == text or not text:
|
||
if n is not None: # a field rewritten whole (a late code result)
|
||
self._clips[n][1].pop(field, None)
|
||
(it.get("clipped") or {}).pop(field, None)
|
||
return
|
||
if n is None:
|
||
n = it["clipId"] = len(self._clips)
|
||
self._clips.append((it, {}))
|
||
it["clipped"] = {}
|
||
self._clips[n][1][field] = text
|
||
it["clipped"][field] = len(text)
|
||
|
||
def full_field(self, it: dict, field: str):
|
||
"""``it[field]`` in full — what was clipped off included."""
|
||
n = it.get("clipId")
|
||
if n is not None and 0 <= n < len(self._clips):
|
||
full = self._clips[n][1].get(field)
|
||
if full is not None:
|
||
return full
|
||
return it.get(field)
|
||
|
||
def last_answer(self) -> str:
|
||
"""The last assistant text of the thread, whole — a run's answer."""
|
||
for it in reversed(self.thread):
|
||
if it.get("role") == "assistant" and it.get("kind") == "text" \
|
||
and (it.get("text") or "").strip():
|
||
return (self.full_field(it, "text") or "").strip()
|
||
return ""
|
||
|
||
def clip_fields(self, n: int) -> dict[str, str] | None:
|
||
"""The full text of each clipped field of the item with ``clipId`` n."""
|
||
if not 0 <= n < len(self._clips):
|
||
return None
|
||
return dict(self._clips[n][1])
|
||
|
||
def _on_prompt(self, ev: dict) -> None:
|
||
"""A real user turn."""
|
||
self.turn_state.busy()
|
||
c, ts = ev["text"], ev.get("at")
|
||
self.interrupted_trailing = self.paused_trailing = False # real activity
|
||
self.waiting_trailing = False
|
||
self.user_turns += 1
|
||
if self.first_user is None:
|
||
self.first_user = c.strip()
|
||
self.res.prompt(c, ts)
|
||
self.usage.gain_prompt(ts)
|
||
mi = self._add_search("user", c)
|
||
if self.full:
|
||
it = _item("user", "text", False, 0,
|
||
mi=mi, ts=ts, author=ev.get("author"),
|
||
midTurn=(ev.get("origin") == "queued") or None)
|
||
self._set_clipped(it, "text", c)
|
||
if self._first_user_item is None:
|
||
self._first_user_item = it
|
||
self.thread.append(it)
|
||
|
||
def _on_inject(self, ev: dict) -> None:
|
||
"""Content the harness or the hub put into the context."""
|
||
self.turn_state.busy()
|
||
kind, ts = ev.get("kind"), ev.get("at")
|
||
if kind == "skill":
|
||
self._inject_skill(ev, ts)
|
||
elif kind == "task_done":
|
||
notes = ev.get("notes") or []
|
||
self._agents_done(notes)
|
||
self._task_notes(notes, ts)
|
||
elif kind == "tasks_noted":
|
||
# The sidecar's restart note told the model how these ended.
|
||
if self.full:
|
||
for tid in ev.get("taskIds") or []:
|
||
if tid in self.task_items:
|
||
taskevents.read_by_note(self.task_items[tid], ts)
|
||
elif kind == "command":
|
||
# A slash command typed in a terminal (`/babysit-pr <url>`): not a
|
||
# turn the thread shows, but its arguments are often exactly what
|
||
# the conversation is about.
|
||
if ev.get("text") is not None:
|
||
self.res.prompt(ev["text"], ts)
|
||
elif kind == "held":
|
||
# The Stop guard's feedback — a runner event, shown as a tag.
|
||
if self.full:
|
||
self.thread.append(_item("user", "held", False, 0, ts=ts,
|
||
text=ev.get("text")))
|
||
elif kind == "cancel":
|
||
# A queued follow-up cancelled: the message it quotes is marked.
|
||
if self.full:
|
||
want = _clip(ev.get("text"))
|
||
for it in reversed(self.thread):
|
||
if it.get("role") == "user" and it.get("kind") == "text" \
|
||
and it.get("text") == want:
|
||
it["cancelled"] = True
|
||
break
|
||
elif kind == "compact_summary":
|
||
# What the agent remembers after a compaction: shown on the
|
||
# boundary's divider, not as a turn the user typed.
|
||
if self._compact_item is not None:
|
||
self._set_clipped(self._compact_item, "text", ev.get("text"))
|
||
|
||
def _inject_skill(self, ev: dict, ts) -> None:
|
||
"""Fold a skill's injected prompt into its Skill card and keep it as
|
||
that skill's latest prompt. A typed ``/name`` (``invoked``) has no
|
||
Skill call: the card is ours to make."""
|
||
name, inv = ev.get("name"), ev.get("invoked")
|
||
if inv is not None:
|
||
card = None
|
||
self._count_skill(name, inv.get("at"))
|
||
if self.full:
|
||
inp = {"skill": name, **({"args": inv["args"]} if inv.get("args") else {})}
|
||
card = _item("user", "tool_use", False, 0, name="skill", input=inp,
|
||
ts=inv.get("at"))
|
||
self.thread.append(card)
|
||
else:
|
||
ref = ev.get("ref")
|
||
card = self.tool_items.get(ref) if ref else None
|
||
body = ev.get("text")
|
||
if body is None:
|
||
return # a repeat call's note, not the skill's text
|
||
base_dir = ev.get("baseDir")
|
||
if card is not None:
|
||
self._set_clipped(card, "skillBody", body)
|
||
rel = _rel_skill_path(base_dir, self.cwd) if base_dir else None
|
||
if rel:
|
||
card["skillPath"] = rel
|
||
if name:
|
||
cur = self.skill_prompts.get(name)
|
||
if cur is None or (ts or "") >= (cur["at"] or ""):
|
||
self.skill_prompts[name] = {
|
||
"text": body[:MAX_SKILL_PROMPT], "at": ts, "baseDir": base_dir}
|
||
|
||
def _on_tool_settled(self, ev: dict) -> None:
|
||
"""An asynchronous call's outcome (a Code Mode script that settled):
|
||
its card gets what its code returned and how long it ran."""
|
||
self.turn_state.busy()
|
||
tu = self.tool_items.get(ev.get("toolCall")) if self.full else None
|
||
if tu is None:
|
||
return
|
||
late = ev.get("late")
|
||
result = ev.get("text")
|
||
if result:
|
||
prev = self.full_field(tu, "codeResult")
|
||
self._set_clipped(tu, "codeResult", result if not prev or not late
|
||
else prev + "\n" + result, markdown=False)
|
||
if ev.get("ms") is not None and not late:
|
||
tu["codeMs"] = ev["ms"]
|
||
|
||
def _on_tool_result(self, ev: dict) -> None:
|
||
self.turn_state.busy()
|
||
ts = ev.get("at")
|
||
tid = ev.get("toolCall")
|
||
is_error = not ev.get("ok", True)
|
||
rtext = ev.get("text") or ""
|
||
# A Monitor answering means its wait is over (a ScheduleWakeup's
|
||
# result only confirms the schedule — that one stays parked until the
|
||
# wake-up fires).
|
||
if self.tool_name.get(tid) == "claude:Monitor":
|
||
self.waiting_trailing = False
|
||
# A blocking agent's result is its report → it's done. A background
|
||
# one only reports its launch here, and ends on its task notification.
|
||
call = self.agent_calls.get(tid)
|
||
aid = taskevents.agent_id("agent", rtext) if call is not None else None
|
||
if aid:
|
||
self.agent_ids[aid] = call
|
||
if call is not None and not _AGENT_ASYNC_RE.search(rtext):
|
||
self.agent_calls.pop(tid, None)
|
||
elif call is not None:
|
||
call["background"] = True
|
||
elif self.tool_name.get(tid) == "claude:SendMessage":
|
||
m = _AGENT_RESUMED_RE.search(rtext)
|
||
call = self.agent_ids.get(m.group(1)) if m else None
|
||
if call is not None:
|
||
self.agent_calls[call["toolUseId"]] = {
|
||
**call, "background": True, "startedAt": ts}
|
||
if tid == self._deploying_tool_use_id:
|
||
self.deploying_since = None
|
||
self._deploying_tool_use_id = None
|
||
if "node_type: memory" in rtext:
|
||
self.memories_read.update(_MEMORY_RE.findall(rtext))
|
||
if tid in self.commit_calls and not is_error:
|
||
found = gitcommits.from_output(
|
||
rtext, cwd=self._rec_cwd, tool_use_id=tid, ts=ts,
|
||
log_one=self.commit_calls[tid])
|
||
gitcommits.add(self.commits, found)
|
||
tu = self.tool_items.get(tid) if self.full else None
|
||
if tu is not None and found:
|
||
tu.setdefault("commits", found)
|
||
if not self.full:
|
||
return
|
||
# Nest the result inside its originating tool_use card (the UI
|
||
# collapses it there) rather than as its own row.
|
||
tu = self.tool_items.get(tid)
|
||
if tu is None:
|
||
# Orphan result (call not captured) — keep a row.
|
||
orphan = _item(
|
||
"tool", "tool_result", False, 0,
|
||
name=self.tool_name.get(tid, "tool"),
|
||
isError=is_error,
|
||
ts=ts,
|
||
)
|
||
self._set_clipped(orphan, "text", rtext, markdown=False)
|
||
self.thread.append(orphan)
|
||
return
|
||
data = ev.get("data") or {}
|
||
self._set_clipped(tu, "result", rtext, markdown=False,
|
||
shown=mcpresult.compact(tu.get("name"), rtext, MAX_BLOCK))
|
||
# How long the tool ran: the gap between the call and its result.
|
||
tu["durationMs"] = _elapsed_ms(tu.get("ts"), ts)
|
||
tu["resultChars"] = len(rtext)
|
||
aid = taskevents.agent_id(tu.get("name"), rtext)
|
||
if aid:
|
||
self.agent_cards[aid] = tu
|
||
tid2 = taskevents.started_task(tu.get("name"), tu.get("input"), rtext)
|
||
if tid2 and not is_error:
|
||
tu["taskId"] = tid2
|
||
tu.setdefault("taskState", "running")
|
||
self.task_items[tid2] = tu
|
||
elif (tu.get("name") == "shell_kill" and not is_error
|
||
and "Successfully stopped" in rtext):
|
||
inp = tu.get("input") if isinstance(tu.get("input"), dict) else {}
|
||
src = self.task_items.get(str(inp.get("task_id") or ""))
|
||
if src is not None:
|
||
taskevents.stopped(src, ts)
|
||
tu["resultLines"] = rtext.count("\n") + 1 if rtext else 0
|
||
if tu.get("name") == codemode.SCRIPT_CARD:
|
||
if data.get("evalId") is not None:
|
||
tu["evalId"] = data["evalId"]
|
||
if tu.get("name") == "shell" and "bashDiff" not in tu:
|
||
if data.get("bashDiff") is not None:
|
||
tu["bashDiff"] = data["bashDiff"]
|
||
if is_error:
|
||
tu["isError"] = True
|
||
elif tu.get("deploy"):
|
||
url = _deployed_url(rtext)
|
||
if url:
|
||
tu["deployedUrl"] = url
|
||
|
||
def _on_call(self, ev: dict) -> None:
|
||
"""A model step starts: its usage and blocks follow (``_close_step``)."""
|
||
self.turn_state.busy()
|
||
self.turn_state.step_since = None # its blocks are in: it has ended
|
||
self._step = [ev]
|
||
|
||
# ── a model step ────────────────────────────────────────────────────────
|
||
def _close_step(self) -> None:
|
||
"""Fold the open step: one model API call's ``call`` event, its
|
||
``usage`` when known by then, and its blocks (text, thinking, tool
|
||
calls, an error's message). Claude Code writes one step per content
|
||
block of a call (the same call id again): the first one prices the
|
||
call, the later ones only re-home its attribution onto the tool they
|
||
carry (``_rehome``). A step whose usage comes later (opencode) is
|
||
priced by a later step with that usage and no blocks (``_unpriced``)."""
|
||
step, self._step = self._step, None
|
||
call = step[0]
|
||
usage = None
|
||
blocks = step[1:]
|
||
for i, e in enumerate(blocks):
|
||
if e["t"] == "usage":
|
||
usage = e
|
||
blocks = blocks[:i] + blocks[i + 1:]
|
||
break
|
||
ts = call.get("at")
|
||
model = call.get("model")
|
||
# `<synthetic>` and friends are placeholders on messages a harness
|
||
# fabricates itself — not a model the conversation ran on, so they
|
||
# taint neither the primary model nor the model tags.
|
||
if _real_model(model):
|
||
if ts and not call.get("failed"):
|
||
self.reply_at = ts
|
||
self.model = self.model or model
|
||
self.model_turns[model] = self.model_turns.get(model, 0) + 1
|
||
# Only real model turns count, so synthetic records can't invent
|
||
# an effort level.
|
||
eff = call.get("effort")
|
||
if isinstance(eff, str) and eff.strip():
|
||
eff = eff.strip().lower()
|
||
self.effort_turns[eff] = self.effort_turns.get(eff, 0) + 1
|
||
# Mark this 5-minute bin as worked in, under the model that did
|
||
# the work — a mixed-model session lands in each model's own
|
||
# bins, so the histogram never attributes a turn to the wrong one.
|
||
b = _bin5(ts)
|
||
if b is not None:
|
||
self.active_bins.setdefault(model, set()).add(b)
|
||
nu = None
|
||
out_tokens = 0
|
||
call_key = (call["id"], call.get("request")) if call.get("id") else None
|
||
dup_call = self._calls.get(call_key) if call_key else None
|
||
speed = call.get("tier")
|
||
if usage is not None and dup_call is None and not call.get("virtual"):
|
||
nu = norm(usage)
|
||
self.usage.agg = add_usage(self.usage.agg, nu)
|
||
self.assistant_turns += 1
|
||
out_tokens = nu["output"]
|
||
if self.full:
|
||
self.turns.append({"model": model, **nu})
|
||
has_blocks = not call.get("empty")
|
||
first = True
|
||
turn_bucket = None # first tool this turn drives the cost attribution
|
||
turn_subkey = None # …and its sub-label (program / ext / tool name)
|
||
tmodel = model or self.model
|
||
# This API call's own tokens/cost — surfaced as a per-tool "delta" on
|
||
# the first tool card of the turn (the call that made it).
|
||
turn_tokens = usage_tokens(nu) if nu is not None else 0
|
||
# Its price, from the model's provider (``UsageMeter.price`` →
|
||
# ``ProviderRegistry.price_call``): the price table; what the provider
|
||
# billed when the harness says so (pi's runner) — authoritative, so it
|
||
# beats the estimate; and on the EVOX2 what the box's time cost
|
||
# instead of the runner's $0. Only for a call whose usage is counted:
|
||
# a repeat of an already-priced call adds nothing (it used to add its
|
||
# cost again — a double count). The time is the call's own: from the
|
||
# event that unblocked it to its reply — for a step whose usage comes
|
||
# later, the duration its content step saw (`_unpriced`).
|
||
cc = None
|
||
if nu is not None:
|
||
pend = self._unpriced.get(call_key) if call_key is not None and not has_blocks else None
|
||
ms = pend.get("ms") if pend is not None else call.get("elapsedMs")
|
||
cc = self.usage.price(ts, tmodel, speed, nu, usage, ms)
|
||
turn_cost = cc.cost if cc is not None else 0.0
|
||
self.usage.cost_total += turn_cost
|
||
# …and how much of it is just the cached prompt being replayed, so the
|
||
# cost-growth chart can stack cache under fresh tokens.
|
||
turn_cache_tokens = int(nu["cacheRead"]) if nu is not None else 0
|
||
turn_cache_cost = cc.cache_cost if cc is not None else 0.0
|
||
if nu is not None:
|
||
self.usage.priced_call(ts, tmodel, call.get("turnEffort") or call.get("effort"),
|
||
speed, usage, nu, turn_cost, turn_tokens, self.model,
|
||
cc.plan_units)
|
||
# First priced call = the session's first API call: split its input
|
||
# side into injected context vs the user's actual message (see
|
||
# EST_CHARS_PER_TOKEN). `first_ctx_u` is the context share as a usage
|
||
# dict, peeled off this turn's bucket attribution below.
|
||
first_ctx_u = None
|
||
split = self.usage.first_split(nu, self.first_user) if nu is not None else None
|
||
if split is not None:
|
||
first_ctx_u, in_side = split
|
||
if self._first_user_item is not None and in_side > 0:
|
||
self._first_user_item["firstContextTokens"] = \
|
||
self.usage.first_context_tokens
|
||
self._first_user_item["firstMessageTokens"] = \
|
||
self.usage.first_message_tokens
|
||
delta_attached = False
|
||
# The one thread item this turn's cost is stamped on (the first tool
|
||
# card / text bubble of the turn, or the carrier item below when the
|
||
# turn rendered nothing). The bucket is stamped onto it once the
|
||
# attribution is known, at the end of the step.
|
||
self._turn_item = None
|
||
pending = (self._unpriced.pop(call_key, None)
|
||
if nu is not None and call_key is not None and not has_blocks else None)
|
||
if pending is not None:
|
||
turn_bucket, turn_subkey = pending["bucket"], pending["subkey"]
|
||
if self.full and pending["item"] is not None:
|
||
it = pending["item"]
|
||
it["turnTokens"] = turn_tokens
|
||
it["turnCost"] = turn_cost
|
||
it["turnCacheTokens"] = turn_cache_tokens
|
||
it["turnCacheCost"] = turn_cache_cost
|
||
delta_attached = True
|
||
self._turn_item = it
|
||
# How long this API call took: from the previous event (the tool
|
||
# result / user turn that unblocked it) to this one.
|
||
turn_ms = call.get("elapsedMs")
|
||
rec_tool_item = None # this step's first tool card (see `_rehome`)
|
||
rec_items_from = len(self.thread)
|
||
for b in blocks:
|
||
bt = b["t"]
|
||
if bt == "tool_call":
|
||
self.interrupted_trailing = self.paused_trailing = False # real activity
|
||
bid, name, raw_inp = b.get("id"), b.get("tool"), b.get("input")
|
||
native = b.get("native")
|
||
self.tool_name[bid] = name
|
||
inp = raw_inp or {}
|
||
# A ScheduleWakeup (unless it's the stop:true loop-ender)
|
||
# parks the run until the wake-up fires; a Monitor blocks
|
||
# until its condition. Anything else is real work.
|
||
if name == "claude:ScheduleWakeup":
|
||
self.waiting_trailing = not inp.get("stop")
|
||
else:
|
||
self.waiting_trailing = name == "claude:Monitor"
|
||
if turn_bucket is None:
|
||
turn_bucket = _bucket(name)
|
||
turn_subkey = _subkey(turn_bucket, name, inp)
|
||
# Auto-tag projects/services only from files this turn
|
||
# *created or edited* — the target path of a file-mutating
|
||
# tool — not from reads, searches, or bash path mentions.
|
||
if name in _EDIT_TOOLS:
|
||
for v in (inp.get("file_path"), inp.get("notebook_path")):
|
||
self.projects |= _projects_in(v)
|
||
self.services |= _services_in(v)
|
||
self._note_written(v)
|
||
if name == "shell" and ts:
|
||
self.bash_started[bid] = ts
|
||
cmd = str(inp.get("command") or "") if name == "shell" else ""
|
||
if cmd and len(self.worktree_adds) < _MAX_WORKTREE_ADDS:
|
||
for wa in written.worktree_adds(cmd, self._rec_cwd or self.cwd):
|
||
if wa not in self.worktree_adds:
|
||
self.worktree_adds.append(wa)
|
||
if cmd and _COMMIT_CMD_RE.search(cmd):
|
||
self.commit_calls[bid] = bool(_LOG_ONE_RE.search(cmd))
|
||
for wev in _worktree_events(inp.get("command")):
|
||
wt = self.worktrees.get(wev["dir"])
|
||
if wt is None:
|
||
wt = {"name": wev["name"] or wev["dir"], "dir": wev["dir"],
|
||
"createdAt": None, "removedAt": None}
|
||
self.worktrees[wev["dir"]] = wt
|
||
if wev["kind"] == "create":
|
||
if wev["name"]:
|
||
wt["name"] = wev["name"]
|
||
if wev.get("project"):
|
||
wt["project"] = wev["project"]
|
||
if ts and (wt["createdAt"] is None or ts < wt["createdAt"]):
|
||
wt["createdAt"] = ts
|
||
elif ts and (wt["removedAt"] is None or ts > wt["removedAt"]):
|
||
wt["removedAt"] = ts
|
||
for stage in _lifecycle_stages(name, inp):
|
||
if ts and (stage not in self.lifecycle or ts > self.lifecycle[stage]):
|
||
self.lifecycle[stage] = ts
|
||
deploy = _deploy_call(name, inp)
|
||
if bid and deploy:
|
||
self.deploying_since = ts
|
||
self._deploying_tool_use_id = bid
|
||
if name == "skill":
|
||
sk = (raw_inp or {}).get("skill")
|
||
if sk:
|
||
self._count_skill(sk, ts)
|
||
# The task list (`todo`, told apart by its input: `todo_op`).
|
||
# A create appends a task (id = its 1-based ordinal, the same
|
||
# id its tool_result reports and an update cites); an update
|
||
# mutates one by id. A snapshot (Claude Code's older
|
||
# TodoWrite) re-sends the *entire* list each call, so it resets
|
||
# our task map to it — the last snapshot wins.
|
||
op = todo_op(inp) if name == "todo" else None
|
||
if op == "create":
|
||
self.task_seq += 1
|
||
tid = str(self.task_seq)
|
||
self.tasks[tid] = {
|
||
"id": tid,
|
||
"subject": _task_subject(
|
||
inp.get("subject") or inp.get("content")),
|
||
"status": "pending",
|
||
}
|
||
elif op == "update":
|
||
tid = str(inp.get("taskId") or inp.get("task_id") or "")
|
||
cur = self.tasks.get(tid)
|
||
if cur is not None:
|
||
st = inp.get("status")
|
||
if st in _TASK_STATES:
|
||
cur["status"] = st
|
||
if inp.get("subject"):
|
||
cur["subject"] = _task_subject(inp["subject"])
|
||
elif op == "snapshot":
|
||
self.tasks.clear()
|
||
self.task_seq = 0
|
||
for td in inp["todos"]:
|
||
if not isinstance(td, dict):
|
||
continue
|
||
self.task_seq += 1
|
||
tid = str(self.task_seq)
|
||
st = td.get("status")
|
||
self.tasks[tid] = {
|
||
"id": tid,
|
||
"subject": _task_subject(
|
||
td.get("content") or td.get("activeForm")),
|
||
"status": st if st in _TASK_STATES else "pending",
|
||
}
|
||
if name == "agent" and bid:
|
||
self.agent_calls[bid] = {
|
||
"toolUseId": bid,
|
||
"agentType": inp.get("subagent_type"),
|
||
"description": _task_subject(inp["description"])
|
||
if inp.get("description") else None,
|
||
"startedAt": ts,
|
||
}
|
||
if self.full:
|
||
it = _item("assistant", "tool_use", first, out_tokens,
|
||
name=name, native=native if native != name else None,
|
||
input=raw_inp, ts=ts, model=tmodel)
|
||
# An agent call's id links it to the spawned
|
||
# subagent transcript (its meta.json `toolUseId`), so the
|
||
# detail endpoint can attach the child conversation. Every
|
||
# other call carries its id too — it's the handle the tool
|
||
# result is matched on, and useful metadata in the UI.
|
||
it["toolUseId"] = bid
|
||
if b.get("caller"):
|
||
it["script"] = b["caller"] # the Code Mode script that made it
|
||
if deploy:
|
||
it["deploy"] = deploy
|
||
if not delta_attached and nu is not None:
|
||
it["turnTokens"] = turn_tokens
|
||
it["turnCost"] = turn_cost
|
||
it["turnCacheTokens"] = turn_cache_tokens
|
||
it["turnCacheCost"] = turn_cache_cost
|
||
delta_attached = True
|
||
self._turn_item = it
|
||
if name in ("shell_kill", "shell_output"):
|
||
src = self.task_items.get(str(inp.get("task_id") or ""))
|
||
if src is not None:
|
||
it["taskRef"] = taskevents.ref(src)
|
||
elif name == "claude:SendMessage":
|
||
src = self.agent_cards.get(str(inp.get("to") or ""))
|
||
if src is not None:
|
||
it["taskRef"] = taskevents.ref(src)
|
||
elif name == "agent" and inp.get("name"):
|
||
self.agent_cards[str(inp["name"])] = it
|
||
self.thread.append(it)
|
||
self.tool_items[bid] = it
|
||
if rec_tool_item is None:
|
||
rec_tool_item = it
|
||
first = False
|
||
elif bt == "text" and b.get("paused"):
|
||
# The harness's canned no-op reply ("No response requested.")
|
||
# → hide the bubble and mark the run paused. Doesn't clear a
|
||
# trailing interrupt (an interrupt's own canned reply must stay
|
||
# "interrupted").
|
||
self.paused_trailing = True
|
||
if self.full:
|
||
self.thread.append(_item("assistant", "paused", first, 0, ts=ts))
|
||
first = False
|
||
elif bt == "text" or bt == "error":
|
||
# A text block — or, for a failed call, the error message it
|
||
# came back with (the viewer draws an error card with the fix).
|
||
self.interrupted_trailing = self.paused_trailing = False # real activity
|
||
raw = b.get("text") or ""
|
||
# A closing push block ending the message: cut out of the
|
||
# text everything reads, kept on the item + the summary.
|
||
btext, pushed = closing_notify.split(raw)
|
||
if pushed and not self.is_sidechain:
|
||
self.closing_notify = {**pushed, "uuid": b.get("id") or "",
|
||
"at": ts or ""}
|
||
self.last_assistant_text = btext # keep only the latest one
|
||
kind = b.get("kind") if bt == "error" else None
|
||
if kind is not None and ts:
|
||
self.api_error = {"kind": kind, "at": ts, "message": raw[:200]}
|
||
if kind == "rate_limit":
|
||
self.api_error["resetsAt"] = b.get("resetsAt")
|
||
mi = self._add_search("assistant", btext)
|
||
if self.full:
|
||
it = _item("assistant", "text", first, out_tokens,
|
||
mi=mi, ts=ts, model=tmodel, durationMs=turn_ms)
|
||
self._set_clipped(it, "text", btext)
|
||
if pushed:
|
||
it["notify"] = pushed
|
||
if kind is not None:
|
||
it["apiError"] = kind
|
||
if kind == "rate_limit":
|
||
# When the window reopens — the card's
|
||
# "Resume at …" (null: the text names none).
|
||
it["resetsAt"] = b.get("resetsAt")
|
||
# Surface this turn's tokens/cost on its first text bubble
|
||
# (if no tool card already claimed the delta).
|
||
if not delta_attached and nu is not None:
|
||
it["turnTokens"] = turn_tokens
|
||
it["turnCost"] = turn_cost
|
||
it["turnCacheTokens"] = turn_cache_tokens
|
||
it["turnCacheCost"] = turn_cache_cost
|
||
delta_attached = True
|
||
self._turn_item = it
|
||
self.thread.append(it)
|
||
first = False
|
||
elif bt == "thinking":
|
||
self.interrupted_trailing = self.paused_trailing = False # real activity
|
||
if self.full:
|
||
think = _item("assistant", "thinking", first, out_tokens,
|
||
ts=ts, model=tmodel, durationMs=turn_ms)
|
||
self._set_clipped(think, "text", b.get("text"))
|
||
self.thread.append(think)
|
||
first = False
|
||
if nu is not None:
|
||
bucket = turn_bucket or "msg"
|
||
# Charged to its activity at this turn's model (usage.py) —
|
||
# the context share of a first call to `context`.
|
||
turn_u, ctx_cost, own_cost, reply_cost = self.usage.charge(
|
||
bucket, turn_subkey, nu, first_ctx_u, tmodel, turn_cost)
|
||
if self.full:
|
||
# Every priced turn must carry its cost on exactly one thread
|
||
# item, or the cost-growth chart (which sums the items) lands
|
||
# below the conversation total. A turn slips through when it
|
||
# rendered nothing at all: a *redacted* thinking block is
|
||
# signature-only, so its `thinking` text is empty and no item is
|
||
# appended — yet the call was made and billed (mostly cache
|
||
# reads). Give those turns an invisible carrier item so the
|
||
# money still reaches the chart.
|
||
if not delta_attached:
|
||
it = _item("assistant", "turn", first, out_tokens, ts=ts,
|
||
model=tmodel, durationMs=turn_ms)
|
||
it["turnTokens"] = turn_tokens
|
||
it["turnCost"] = turn_cost
|
||
it["turnCacheTokens"] = turn_cache_tokens
|
||
it["turnCacheCost"] = turn_cache_cost
|
||
self.thread.append(it)
|
||
self._turn_item = it
|
||
delta_attached = True
|
||
first = False
|
||
# Colour the turn by the activity the breakdown actually charged
|
||
# it to, so the chart's legend can't drift from "cost by
|
||
# activity" (the frontend used to re-derive the bucket from the
|
||
# tool name, which has no way to know about the `context` split).
|
||
if self._turn_item is not None:
|
||
self._turn_item["turnBucket"] = bucket
|
||
if first_ctx_u is not None:
|
||
# The first call's injected-context share is its own
|
||
# bucket in the breakdown; hand the chart the same split
|
||
# (the very same numbers) so it can stack it under this
|
||
# turn rather than mis-attributing the whole call to
|
||
# `msg`.
|
||
self._turn_item["turnContextCost"] = ctx_cost
|
||
self._turn_item["turnContextTokens"] = usage_tokens(
|
||
first_ctx_u)
|
||
if call_key is not None:
|
||
c = {"bucket": bucket, "subkey": turn_subkey or "?",
|
||
"u": turn_u, "cost": own_cost,
|
||
"item": self._turn_item if self.full else None,
|
||
"carrier": bool(self.full and self._turn_item is not None
|
||
and self._turn_item.get("kind") == "turn")}
|
||
if bucket == "msg":
|
||
c["reply_cost"] = reply_cost
|
||
self._calls[call_key] = c
|
||
elif dup_call is not None:
|
||
self._rehome(dup_call, turn_bucket, turn_subkey, rec_tool_item)
|
||
elif call_key is not None and has_blocks and call_key not in self._calls:
|
||
# Content whose usage comes later (see `_unpriced`): its first
|
||
# tool card — else its first bubble — takes the delta then.
|
||
items = self.thread[rec_items_from:] if self.full else []
|
||
shown = next((i for i in items if i.get("kind") == "text"), None)
|
||
self._unpriced[call_key] = {
|
||
"bucket": turn_bucket, "subkey": turn_subkey, "ms": turn_ms,
|
||
"item": rec_tool_item or shown or (items[0] if items else None)}
|
||
|
||
def _compact_boundary(self, md: dict, ts) -> None:
|
||
"""A compaction (a ``compact`` event): the context the next call
|
||
replays is now the summary (``postTokens``) on top of the injected
|
||
context, and the thread gets a divider (the ``compact_summary`` inject
|
||
that follows fills its text)."""
|
||
post, pre = md.get("postTokens"), md.get("preTokens")
|
||
info = {k: v for k, v in (("trigger", md.get("trigger")), ("preTokens", pre),
|
||
("postTokens", post), ("durationMs", md.get("durationMs")))
|
||
if v is not None}
|
||
item = _item("user", "compact", False, 0, ts=ts, compact=info) if self.full else None
|
||
if item is not None:
|
||
self.thread.append(item)
|
||
self._compact_item = item
|
||
self.usage.compaction(md, item, ts)
|
||
|
||
def _rehome(self, call: dict, bucket, subkey, item) -> None:
|
||
"""A later step of an already-priced API call. Its usage was charged
|
||
on the call's *first* step, which is usually a thinking or text block
|
||
— so the call landed in `msg`. When this step carries the call's tool,
|
||
move the charge (and the per-turn delta badge) to that tool, which is
|
||
what the turn actually drove."""
|
||
self.usage.move_charge(call, bucket, subkey)
|
||
# The delta badge belongs on the tool card; an invisible carrier (a
|
||
# thinking-only first record) is dropped once a real card exists.
|
||
old_it = call["item"]
|
||
if item is not None and old_it is not None and old_it is not item and (
|
||
call["carrier"] or old_it.get("kind") != "tool_use"):
|
||
for k in _DELTA_KEYS:
|
||
if k in old_it:
|
||
item[k] = old_it.pop(k)
|
||
if call["carrier"]:
|
||
try:
|
||
self.thread.remove(old_it)
|
||
except ValueError:
|
||
pass
|
||
call["item"], call["carrier"] = item, False
|
||
if self._turn_item is old_it:
|
||
self._turn_item = item
|
||
|
||
def _note_written(self, path) -> None:
|
||
"""Remember the directory of a file the session wrote (absolute
|
||
paths only; capped — a codemod over a monorepo needs no more)."""
|
||
if (isinstance(path, str) and path.startswith("/")
|
||
and len(self.written_dirs) < _MAX_WRITTEN_DIRS):
|
||
self.written_dirs.add(path.rsplit("/", 1)[0] or "/")
|
||
|
||
def _note_roots(self, payload: dict | None) -> None:
|
||
"""The git roots a Bash-hook payload names (``main`` = the main
|
||
checkout of a linked worktree, from hooks that report it)."""
|
||
for r in (payload or {}).get("repos") or []:
|
||
if isinstance(r, dict) and isinstance(r.get("root"), str) and r["root"]:
|
||
if len(self.git_roots) >= _MAX_GIT_ROOTS and r["root"] not in self.git_roots:
|
||
break
|
||
main = r.get("main") if isinstance(r.get("main"), str) else None
|
||
self.git_roots[r["root"]] = main or self.git_roots.get(r["root"])
|
||
|
||
def _commits_summary(self) -> list[dict]:
|
||
out = [dict(c) for c in self.commits]
|
||
gitcommits.mark_pushed(out, self.pushes)
|
||
return out
|
||
|
||
def summary(self) -> dict:
|
||
"""Snapshot the summary (and, when ``full``, the thread) so far."""
|
||
title = self.ai_title or (self.first_user[:90] if self.first_user else None) or "(untitled)"
|
||
um = self.usage
|
||
summary = {
|
||
"sessionId": self.session_id,
|
||
"cwd": self.cwd,
|
||
"project": _project_name(self.cwd, self.path),
|
||
"gitBranch": self.git_branch,
|
||
"model": self.model or "claude-opus-4-8",
|
||
# All models that produced a turn, busiest first — the conversation's
|
||
# model tags. Usually one; more when the session switched mid-thread.
|
||
"models": [m for m, _ in sorted(self.model_turns.items(),
|
||
key=lambda kv: -kv[1])],
|
||
# The `--effort` level(s) the turns actually ran at, busiest first.
|
||
# Empty for pi runs and for transcripts predating the CLI flag.
|
||
"efforts": [e for e, _ in sorted(self.effort_turns.items(),
|
||
key=lambda kv: -kv[1])],
|
||
# "opencode" / "agy" when the transcript says which harness wrote it
|
||
# (the mirrors' records); None for Claude Code's own and pi's.
|
||
"harness": self.harness,
|
||
# Started in Claude Code's Code Mode (a `repl-mode` record): only an
|
||
# interactive run in it can continue the session.
|
||
"codeMode": self.code_mode_on or None,
|
||
# model id -> the 5-minute bins this run produced a turn in, sorted.
|
||
# Small by construction (bins are 5 min wide and runs are short), so
|
||
# it rides along in the stored summary rather than costing a re-walk.
|
||
"activeBins": {m: sorted(b) for m, b in self.active_bins.items()},
|
||
"title": title,
|
||
# The opening ask, for the Haiku call that labels what the
|
||
# conversation does (conversations/look.py). Capped: cards never
|
||
# carry it, it only rides in the stored summary.
|
||
"firstPrompt": (self.first_user or "")[:1500] or None,
|
||
"userTurns": self.user_turns,
|
||
"assistantTurns": self.assistant_turns,
|
||
"messages": self.user_turns + self.assistant_turns,
|
||
"startedAt": self.started,
|
||
"endedAt": self.ended,
|
||
# The API error the session ended on (none once a model answered
|
||
# after it) and its last real answer — accounts/health.py reads
|
||
# both to tell a signed-out account from a working one.
|
||
"lastApiError": (self.api_error if self.api_error and (
|
||
not self.reply_at or self.api_error["at"] > self.reply_at) else None),
|
||
"lastReplyAt": self.reply_at,
|
||
# Follow-ups a live run took through its inbox and hasn't read yet
|
||
# (meaningful only while it runs — a dead run's queue died with it).
|
||
"queued": self.queued_followups(),
|
||
"stepSince": self.turn_state.step_since,
|
||
"tokens": usage_tokens(um.agg),
|
||
"cost": um.cost_total,
|
||
"usage": um.agg,
|
||
# What the subscription's limits count (pricing.plan_units), the
|
||
# price book every figure here was computed with, and the split of
|
||
# cost / tokens / plan units per model id and per effort level.
|
||
"planUnits": um.plan_units,
|
||
"priceBook": pricing.price_book(),
|
||
"fastCalls": um.fast_calls,
|
||
# The EVOX2's time behind `cost` — set only when a local model ran.
|
||
"local": dict(um.local) if um.local["seconds"] > 0 else None,
|
||
"byModel": {
|
||
m: {"turns": d["turns"], "tokens": usage_tokens(d["usage"]),
|
||
"cost": d["cost"], "planUnits": d["planUnits"],
|
||
"usage": d["usage"], "efforts": d["efforts"]}
|
||
for m, d in sorted(um.by_model.items(), key=lambda kv: -kv[1]["cost"])
|
||
},
|
||
# epoch hour -> [list $, plan units]: the calibration's input
|
||
# (backend/usage/), stored so it never has to re-walk transcripts.
|
||
"meterBins": {str(h): [round(v[0], 6), round(v[1], 6)]
|
||
for h, v in sorted(um.meter_bins.items())},
|
||
"contextTokens": um.context_tokens or None,
|
||
"contextModel": um.context_model,
|
||
"lastCallAt": um.last_call_at,
|
||
"cacheTtl": um.cache_ttl,
|
||
"compactions": um.compactions or None,
|
||
# First API call's input side, split into injected context
|
||
# (system prompt, CLAUDE.md, memories, …) vs the user's actual
|
||
# first message (length-estimated — the API only reports the total).
|
||
"firstContextTokens": um.first_context_tokens,
|
||
"firstMessageTokens": um.first_message_tokens,
|
||
# Costs come from the meter's `by_tool_cost` — accumulated per turn at that turn's
|
||
# own model — not from re-pricing the summed usage with `self.model`,
|
||
# which overcharged every mixed-model session and left the breakdown
|
||
# disagreeing with the conversation total.
|
||
"byTool": {
|
||
b: {"tokens": usage_tokens(u),
|
||
"cost": um.by_tool_cost.get(b, 0.0),
|
||
"output": u["output"]}
|
||
for b, u in sorted(
|
||
um.by_tool.items(),
|
||
key=lambda kv: TOOL_BUCKET_ORDER.index(kv[0])
|
||
if kv[0] in TOOL_BUCKET_ORDER else 99)
|
||
},
|
||
# Same buckets, one level deeper (bash→program, read/edit→ext, msg→
|
||
# prompt/replies, tool buckets→tool name), each sub sorted by tokens desc.
|
||
"byToolSub": {
|
||
b: {
|
||
sk: {"tokens": usage_tokens(u),
|
||
"cost": um.by_tool_sub_cost.get(b, {}).get(sk, 0.0),
|
||
"output": u["output"]}
|
||
for sk, u in sorted(subs.items(),
|
||
key=lambda kv: usage_tokens(kv[1]),
|
||
reverse=True)
|
||
}
|
||
for b, subs in sorted(
|
||
um.by_tool_sub.items(),
|
||
key=lambda kv: TOOL_BUCKET_ORDER.index(kv[0])
|
||
if kv[0] in TOOL_BUCKET_ORDER else 99)
|
||
},
|
||
"projectsAuto": sorted(self.projects),
|
||
"writtenDirsAuto": sorted(self.written_dirs),
|
||
"gitRootsAuto": [{"root": r, "main": m} if m else {"root": r}
|
||
for r, m in sorted(self.git_roots.items())],
|
||
"worktreeAddsAuto": self.worktree_adds,
|
||
"servicesAuto": sorted(self.services),
|
||
"worktreesAuto": list(self.worktrees.values()),
|
||
"commitsAuto": self._commits_summary(),
|
||
# Bash calls that could commit (git commit/merge/…, a commit skill):
|
||
# none ⇒ the conversation committed nothing, whatever a time
|
||
# window over its repos would find.
|
||
"commitCalls": len(self.commit_calls),
|
||
"tasks": list(self.tasks.values()),
|
||
"runningAgents": list(self.agent_calls.values()),
|
||
"deploying": bool(self.deploying_since),
|
||
"lifecycleAuto": self.lifecycle,
|
||
"memoriesRead": sorted(self.memories_read),
|
||
"doneMarker": bool(_DONE_RE.search(self.last_assistant_text)),
|
||
"completedMarker": bool(_COMPLETED_RE.search(self.last_assistant_text)),
|
||
# Popped by the indexer (never stored): what it pushes, once.
|
||
"closingNotify": self.closing_notify,
|
||
"interruptedByUser": self.interrupted_trailing,
|
||
"pausedByUser": self.paused_trailing,
|
||
"waitingForTrigger": self.waiting_trailing,
|
||
# …not while a background agent it launched is still at work: the
|
||
# CLI waits for it, and its notification starts the next turn.
|
||
"turnEnded": self.turn_state.turn_ended and not any(
|
||
c.get("background") for c in self.agent_calls.values()),
|
||
"isSidechain": self.is_sidechain,
|
||
"agentId": self.agent_id,
|
||
"skills": self.skills,
|
||
"searchMsgs": self.search_msgs,
|
||
# resourcesAuto / resourceInfo / resourceTeams / slackChannels —
|
||
# what the conversation is about (resources.py); profile-agnostic,
|
||
# cards.py decides who shows them.
|
||
**self.res.summary(),
|
||
}
|
||
if self.full:
|
||
summary["thread"] = self.thread
|
||
summary["turns"] = self.turns
|
||
else:
|
||
# Indexer-only (popped before the summary is stored): feeds the
|
||
# skills catalog's latest-prompt table. The detail parse already
|
||
# carries each prompt on its card.
|
||
summary["skillPrompts"] = self.skill_prompts
|
||
return summary
|
||
|
||
|
||
_APPLY = {
|
||
"session": ParserState._on_session,
|
||
"prompt": ParserState._on_prompt,
|
||
"inject": ParserState._on_inject,
|
||
"call": ParserState._on_call,
|
||
"tool_result": ParserState._on_tool_result,
|
||
"tool_settled": ParserState._on_tool_settled,
|
||
"turn_end": ParserState._on_turn_end,
|
||
"queue": ParserState._on_queue,
|
||
"compact": ParserState._on_compact,
|
||
"meta": ParserState._on_meta,
|
||
"tick": ParserState._on_tick,
|
||
}
|
||
|
||
|
||
def parse_conversation(path: pathlib.Path, full: bool = False) -> dict:
|
||
"""Walk one transcript. Returns a summary; with full=True also the thread."""
|
||
st = ParserState(path, full=full)
|
||
for o in _iter_records(path):
|
||
st.feed(o)
|
||
return st.summary()
|
||
|
||
|
||
def _project_name(cwd: str | None, path: pathlib.Path) -> str:
|
||
"""A short human label for the conversation's project."""
|
||
if cwd:
|
||
return "/".join(p for p in cwd.split("/")[-2:] if p)
|
||
# fall back to the encoded directory name (…-homelab-projects-foo)
|
||
return path.parent.name
|