96 lines
4.9 KiB
Python
96 lines
4.9 KiB
Python
"""What a stretch of the chunk's work spent, in raw tokens by model and kind, which the archive records beside each verdict, interrupt and quoted answer: docs/decisions.md → `loop-claude: each verdict records the setup, the spend and the reversals…`.
|
|
|
|
A stretch runs from the previous outcome that recorded a spend, or from the chunk's start, to the ruling. It counts the worker's main thread, each subagent and the judge run that ruled, each message once. Dollars are left to be derived from the model and the tokens, at the prices recorded beside them.
|
|
"""
|
|
import datetime
|
|
import json
|
|
import pathlib
|
|
import typing
|
|
|
|
from claude_code.entries import AssistantTurn, Entry
|
|
from claude_code.tokens import Tokens, tokens_of
|
|
from claude_code.transcript import read_transcript
|
|
from failure import Failure
|
|
from routing_figures.prices import PRICES
|
|
from transcript_archive.outcomes import SPENT
|
|
|
|
KINDS = "input, cache write 5m, cache write 1h, cache read, output"
|
|
# Who spent, such as `worker`, `judge` or `Explore "Search the hooks"`, and the model they ran on.
|
|
Spender = tuple[str, str]
|
|
WORKER = "worker"
|
|
JUDGE = "judge"
|
|
|
|
|
|
class Subagent(typing.NamedTuple):
|
|
"""A subagent's transcript, named by the agent type and the description its .meta.json gives: {"agentType": "Explore", "description": "Search the hooks", ...}."""
|
|
name: str
|
|
entries: list[Entry]
|
|
|
|
|
|
def spent(since: str, worker: list[Entry], subagents: list[Subagent], judge_model: str, judge: Tokens) -> dict[Spender, Tokens]:
|
|
"""The tokens each spender spent after since, a UTC stamp, or in the whole transcript where since is empty."""
|
|
found: dict[Spender, Tokens] = {}
|
|
for name, entries in ((WORKER, worker), *subagents):
|
|
for model, tokens in thread_spend(entries, since).items():
|
|
found[name, model] = found.get((name, model), Tokens()).plus(tokens)
|
|
found[JUDGE, judge_model] = judge
|
|
return {spender: tokens for spender, tokens in found.items() if tokens != Tokens()}
|
|
|
|
|
|
def thread_spend(entries: list[Entry], since: str) -> dict[str, Tokens]:
|
|
"""Each model's tokens in one transcript's messages written after since. A message's usage repeats in each entry of it, so each message counts once, by its id."""
|
|
start = moment(since) if since else None
|
|
counted: dict[str, AssistantTurn] = {}
|
|
for entry in entries:
|
|
if isinstance(entry, AssistantTurn) and entry.model and (start is None or later(entry.timestamp, start)):
|
|
counted.setdefault(entry.message_id or entry.uuid, entry)
|
|
found: dict[str, Tokens] = {}
|
|
for turn in counted.values():
|
|
found[turn.model] = found.get(turn.model, Tokens()).plus(tokens_of(turn.usage))
|
|
return found
|
|
|
|
|
|
def moment(stamp: str) -> datetime.datetime:
|
|
return datetime.datetime.fromisoformat(stamp)
|
|
|
|
|
|
# The outcome's stamp runs to the second, so a message written in the second it was stamped, before it, counts again; the judge runs for seconds after the worker exits, so none is.
|
|
def later(timestamp: str, start: datetime.datetime) -> bool:
|
|
try:
|
|
return moment(timestamp) > start
|
|
except ValueError:
|
|
return False
|
|
|
|
|
|
def subagents(transcript_path: str) -> list[Subagent] | Failure:
|
|
"""The subagents' transcripts Claude Code keeps beside the worker's: <session>/subagents/agent-<id>.jsonl, each with its .meta.json."""
|
|
found = []
|
|
for path in sorted(pathlib.Path(transcript_path.removesuffix(".jsonl"), "subagents").glob("*.jsonl")):
|
|
entries = read_transcript(str(path))
|
|
if isinstance(entries, Failure):
|
|
return entries
|
|
found.append(Subagent(subagent_name(path), entries))
|
|
return found
|
|
|
|
|
|
def subagent_name(transcript: pathlib.Path) -> str:
|
|
"""The agent type and the quoted description; `subagent` where the meta is missing or names neither."""
|
|
try:
|
|
meta = json.loads(transcript.with_name(transcript.name.removesuffix(".jsonl") + ".meta.json").read_text(encoding="utf-8"))
|
|
except (OSError, UnicodeDecodeError, ValueError):
|
|
meta = {}
|
|
meta = meta if isinstance(meta, dict) else {}
|
|
# One line for the type, since a line break could forge an archive line such as `Config: `; json.dumps escapes the description's.
|
|
kind, description = " ".join(str(meta.get("agentType") or "subagent").split()), str(meta.get("description") or "")
|
|
return f"{kind} {json.dumps(description, ensure_ascii=False)}" if description else kind
|
|
|
|
|
|
def spent_block(since: str, found: dict[Spender, Tokens]) -> str:
|
|
"""The archive's block for what the stretch spent, then the list prices in force for each model in it; empty where nothing was spent."""
|
|
if not found:
|
|
return ""
|
|
spenders = [f"- {name}, {model}: {', '.join(map(str, (tokens.input, tokens.write_5m, tokens.write_1h, tokens.read, tokens.output)))}" for (name, model), tokens in found.items()]
|
|
priced = [f"- {model}: {price.input:g}, {price.write_5m:g}, {price.write_1h:g}, {price.read:g}, {price.output:g}" for model in dict.fromkeys(model for _, model in found) if (price := PRICES.get(model))]
|
|
prices = ["", f"List prices in dollars per million tokens of {KINDS}:", *priced] if priced else []
|
|
return "\n".join([f"{SPENT}{since or 'the chunk began'}, in tokens of {KINDS}:", *spenders, *prices])
|