"""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 docs for a directory of documentation (the Source Reference Bundle), per file and per group of the profile's `doc_groups`: _tokens size of the group (e.g. quick_reference_tokens, source_docs_tokens, air_docs_tokens) full_source_docs_tokens every group except air_docs read_tokens_by_group tokens of the group's lines the agent saw coverage_by_section per file: fraction of its distinctive lines (in no other file of the mount) seen files_opened files named in a tool input: by /docs path, by path relative to /docs, or by file name as a whole token (`cd /docs/language; cat syntax.md`) unique_docs_read how many files were opened 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?") # grep/ripgrep output and the agents' grep tools: `path:12:text`, context # lines `path-12-text`, and `path:text` when several files are searched. _GREP = re.compile(r"^(?:/docs/\S+?|\S+\.md)(?::\d+[:-]|-\d+-|:)") 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("", _GREP.sub("", line, count=1)).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 _doc_files(docs): """[(path under /docs, host path)] of every file in the mounts.""" out = [] for name, p in docs: if os.path.isfile(p): out.append((name or os.path.basename(p), p)) continue for d, _, files in os.walk(p): for f in sorted(files): hp = os.path.join(d, f) rel = os.path.relpath(hp, p) out.append((os.path.join(name, rel) if name else rel, hp)) return sorted(out) def _named(rel, inputs): """Whether a tool input names the file: `/docs/`, ``, or its file name as a whole token.""" for name in {rel, os.path.basename(rel)}: if re.search(r"(?