"""Context metrics (protocol §16), the same for both tracks. provider_input_tokens what the model provider counted: input, cached and uncached separately cumulative_context_tokens the text returned to the agent through its tool loop (every tool output, plus the task message), counted each time it was returned unique_reference_tokens the distinct documentation text the agent actually saw: distinct lines in the outputs of tool calls that touched /docs reference_coverage for a single-file reference (the Aji Agent Reference Bundle): the fraction of its non-empty lines that appeared in those outputs The gap between them shows where context is amplified: rereading the same documentation, verbose tool output, or the provider resending history. Tokens are counted with tiktoken `cl100k_base` when it is installed, otherwise estimated as bytes / 4; the record says which. """ import json import os import re from . import util _PREFIX = re.compile(r"^\s*\d+\s*[:\t→│|]\s?") def _tokenizer(): try: import tiktoken enc = tiktoken.get_encoding("cl100k_base") return "cl100k_base", lambda s: len(enc.encode(s, disallowed_special=())) except Exception: return "estimate(bytes/4)", lambda s: util.estimate_tokens(len(s.encode())) def _norm(line): return _PREFIX.sub("", line).strip() def tool_events_track_a(events_path): """(input text, output text) per tool call from a Track A event log.""" out = [] for line in open(events_path, encoding="utf-8"): e = json.loads(line) if e["event"] == "command": out.append((e["command"], e.get("output") or "")) elif e["event"] == "tool" and e["name"] != "run": out.append((json.dumps(e.get("input")), e.get("output") or "")) return out def tool_events_native(agent_name, transcript_path): """(input text, output text) per tool call from a native CLI transcript.""" out = [] pending = {} for line in open(transcript_path, encoding="utf-8", errors="replace"): line = line.strip() if not line.startswith("{"): continue try: e = json.loads(line) except json.JSONDecodeError: continue if agent_name == "codex": item = e.get("item") or {} if e.get("type") == "item.completed" and item.get("type") == "command_execution": out.append((item.get("command") or "", item.get("aggregated_output") or "")) elif agent_name == "claude": msg = e.get("message") or {} for b in msg.get("content", []) if isinstance(msg.get("content"), list) else []: if b.get("type") == "tool_use": pending[b.get("id")] = json.dumps(b.get("input")) elif b.get("type") == "tool_result": c = b.get("content") text = c if isinstance(c, str) else "\n".join(x.get("text", "") for x in (c or []) if isinstance(x, dict)) out.append((pending.pop(b.get("tool_use_id"), ""), text)) elif agent_name == "opencode": part = e.get("part") or {} if e.get("type") == "tool_use": st = part.get("state") or {} out.append((json.dumps(st.get("input")), st.get("output") or "")) return out def metrics(tool_events, task_message, docs, provider): """`docs` is [(mount name, host path)]; `provider` holds input, output, cached_input as counted by the provider (None when unknown).""" name, count = _tokenizer() cumulative = count(task_message) + sum(count(o) for _, o in tool_events) seen = set() for inp, outp in tool_events: if "/docs" in inp: for line in outp.splitlines(): n = _norm(line) if n: seen.add(n) unique = count("\n".join(sorted(seen))) coverage = None files = [p for _, p in docs if os.path.isfile(p)] if len(files) == 1 and len(docs) == 1: with open(files[0], encoding="utf-8", errors="replace") as f: ref = {_norm(x) for x in f.read().splitlines() if _norm(x)} coverage = round(len(ref & seen) / len(ref), 4) if ref else None inp, cached = provider.get("input"), provider.get("cached_input") return { "tokenizer": name, "provider_input_tokens": {"total": inp, "cached": cached, "uncached": None if inp is None or cached is None else inp - cached, "output": provider.get("output")}, "cumulative_context_tokens": cumulative, "unique_reference_tokens": unique, "reference_coverage": coverage, "tool_outputs": len(tool_events), }