agent-blackbox-cli 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. agent_blackbox_cli-0.3.0.dist-info/METADATA +623 -0
  2. agent_blackbox_cli-0.3.0.dist-info/RECORD +43 -0
  3. agent_blackbox_cli-0.3.0.dist-info/WHEEL +5 -0
  4. agent_blackbox_cli-0.3.0.dist-info/entry_points.txt +2 -0
  5. agent_blackbox_cli-0.3.0.dist-info/licenses/LICENSE +21 -0
  6. agent_blackbox_cli-0.3.0.dist-info/top_level.txt +1 -0
  7. blackbox/__init__.py +61 -0
  8. blackbox/__main__.py +6 -0
  9. blackbox/adapters/__init__.py +0 -0
  10. blackbox/adapters/_linking.py +31 -0
  11. blackbox/adapters/base.py +38 -0
  12. blackbox/adapters/claude_code.py +341 -0
  13. blackbox/adapters/codex.py +318 -0
  14. blackbox/adapters/labelled_turns.py +371 -0
  15. blackbox/adapters/registry.py +30 -0
  16. blackbox/aggregate.py +119 -0
  17. blackbox/analysis.py +325 -0
  18. blackbox/bench.py +466 -0
  19. blackbox/cli.py +405 -0
  20. blackbox/cost.py +138 -0
  21. blackbox/describe.py +116 -0
  22. blackbox/detectors/__init__.py +32 -0
  23. blackbox/detectors/base.py +83 -0
  24. blackbox/detectors/context_bloat.py +137 -0
  25. blackbox/detectors/contradictions.py +180 -0
  26. blackbox/detectors/error_clusters.py +114 -0
  27. blackbox/detectors/retry_loops.py +98 -0
  28. blackbox/detectors/stalls.py +117 -0
  29. blackbox/detectors/thrash.py +86 -0
  30. blackbox/diff.py +123 -0
  31. blackbox/discover.py +189 -0
  32. blackbox/events.py +163 -0
  33. blackbox/graph.py +150 -0
  34. blackbox/guard.py +528 -0
  35. blackbox/guard_cli.py +349 -0
  36. blackbox/pricing.py +137 -0
  37. blackbox/py.typed +0 -0
  38. blackbox/replay.py +65 -0
  39. blackbox/report/__init__.py +0 -0
  40. blackbox/report/html.py +375 -0
  41. blackbox/report/text.py +287 -0
  42. blackbox/store.py +215 -0
  43. blackbox/toolinfo.py +336 -0
@@ -0,0 +1,117 @@
1
+ """Detect calls that took a long time to come back -- and say which kind.
2
+
3
+ The measurement is wall-clock between a tool call being issued and its result
4
+ arriving, read off the re-parented graph edge so parallel calls are attributed
5
+ correctly.
6
+
7
+ A long gap has two very different causes, and conflating them makes the whole
8
+ report untrustworthy:
9
+
10
+ * a **stall** -- the tool itself ran long (a hung test runner, a slow network
11
+ call). Bounded by what a tool plausibly does.
12
+ * an **idle gap** -- the session was paused: waiting on a human approval, or
13
+ simply left overnight. These can run to hours and say nothing about the
14
+ agent's behaviour.
15
+
16
+ Gaps past ``idle_seconds`` are reported as idle gaps at low severity and never
17
+ counted as stalls.
18
+
19
+ Excluded entirely:
20
+
21
+ * calls the user interrupted;
22
+ * **tools whose whole purpose is to wait for a human** -- asking a question and
23
+ waiting for an answer is the tool working, and timing the human's reading and
24
+ typing adds nothing but noise. That time is reported as a run-level total
25
+ instead, where it belongs.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ from blackbox.detectors.base import HIGH, LOW, MEDIUM, Config, Finding
31
+ from blackbox.graph import Graph
32
+ from blackbox.toolinfo import is_human_in_the_loop
33
+
34
+ NAME = "stall"
35
+
36
+
37
+ def run(graph: Graph, config: Config) -> list[Finding]:
38
+ findings: list[Finding] = []
39
+
40
+ for call in graph.tool_calls():
41
+ result = graph.result_for(call)
42
+ if result is None or call.ts is None or result.ts is None:
43
+ continue
44
+ if "interrupted" in result.flags or "declined" in result.flags:
45
+ continue
46
+ if is_human_in_the_loop(call.tool_name):
47
+ continue # that gap is a person reading and typing, not a stall
48
+
49
+ seconds = (result.ts - call.ts).total_seconds()
50
+ if seconds < config.stall_seconds:
51
+ continue
52
+
53
+ tool = call.tool_name or "tool"
54
+
55
+ if seconds >= config.idle_seconds:
56
+ findings.append(
57
+ Finding(
58
+ detector=NAME,
59
+ severity=LOW,
60
+ title=f"idle gap of {_human(seconds)} at {tool}",
61
+ detail=(
62
+ f"{_human(seconds)} passed between this {tool} call and its "
63
+ f"result -- far longer than any tool runs. The session was "
64
+ f"almost certainly paused here, waiting on a human or simply "
65
+ f"left running. Counted as idle time, not as a stall."
66
+ ),
67
+ key=f"idle:{call.seq:08d}",
68
+ branch=call.branch,
69
+ evidence=(call.uid, result.uid),
70
+ metrics={
71
+ "seconds": round(seconds, 2),
72
+ "tool": tool,
73
+ "seq": call.seq,
74
+ "kind": "idle_gap",
75
+ },
76
+ )
77
+ )
78
+ continue
79
+
80
+ if seconds >= config.stall_seconds * 5:
81
+ severity = HIGH
82
+ elif seconds >= config.stall_seconds * 2:
83
+ severity = MEDIUM
84
+ else:
85
+ severity = LOW
86
+
87
+ findings.append(
88
+ Finding(
89
+ detector=NAME,
90
+ severity=severity,
91
+ title=f"{tool} took {_human(seconds)} to return",
92
+ detail=(
93
+ f"{_human(seconds)} of wall-clock passed between this {tool} call "
94
+ f"and its result. The gap includes any wait for human approval, so "
95
+ f"treat it as an upper bound on execution time."
96
+ ),
97
+ key=f"stall:{call.seq:08d}",
98
+ branch=call.branch,
99
+ evidence=(call.uid, result.uid),
100
+ metrics={
101
+ "seconds": round(seconds, 2),
102
+ "tool": tool,
103
+ "seq": call.seq,
104
+ "kind": "stall",
105
+ },
106
+ )
107
+ )
108
+
109
+ return findings
110
+
111
+
112
+ def _human(seconds: float) -> str:
113
+ if seconds < 90:
114
+ return f"{seconds:.0f}s"
115
+ if seconds < 5400:
116
+ return f"{seconds / 60:.1f}min"
117
+ return f"{seconds / 3600:.1f}h"
@@ -0,0 +1,86 @@
1
+ """Detect files the agent kept rewriting *in a burst*.
2
+
3
+ Repeated writes to one file usually mean the agent could not settle: each edit
4
+ fixes what the last one broke. But the signal is density, not lifetime count.
5
+ Touching ``README.md`` three times across a six-hour build is ordinary
6
+ iterative work; touching it four times inside twenty tool calls is thrashing.
7
+
8
+ The first version of this detector counted writes across the whole session with
9
+ no window, and duly reported every substantial file in a long build. Like
10
+ :mod:`blackbox.detectors.retry_loops`, it now clusters by proximity and reports
11
+ each burst separately, with the span it occupied so the reader can judge.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from blackbox.detectors.base import HIGH, LOW, MEDIUM, Config, Finding
17
+ from blackbox.events import TOOL_CALL
18
+ from blackbox.graph import Graph
19
+ from blackbox import toolinfo
20
+
21
+ NAME = "thrash"
22
+
23
+
24
+ def run(graph: Graph, config: Config) -> list[Finding]:
25
+ findings: list[Finding] = []
26
+
27
+ for branch in graph.branches:
28
+ calls = graph.tool_calls(branch.name)
29
+ positions: dict[str, list[int]] = {}
30
+ for index, call in enumerate(calls):
31
+ for path, kind in toolinfo.file_operations(call.tool_name, call.tool_input):
32
+ if kind in (toolinfo.WRITE, toolinfo.EDIT):
33
+ positions.setdefault(path, []).append(index)
34
+
35
+ for path in sorted(positions):
36
+ for cluster in _cluster(positions[path], config.thrash_window):
37
+ if len(cluster) < config.thrash_min_edits:
38
+ continue
39
+ events = [calls[i] for i in cluster]
40
+ span = cluster[-1] - cluster[0] + 1
41
+ severity = HIGH if len(cluster) >= 8 else MEDIUM if len(cluster) >= 5 else LOW
42
+ findings.append(
43
+ Finding(
44
+ detector=NAME,
45
+ severity=severity,
46
+ title=f"{_short(path)} written {len(cluster)}x in {span} tool calls",
47
+ detail=(
48
+ f"{path} was written {len(cluster)} times inside a span of "
49
+ f"{span} tool calls. Edits that tightly packed usually mean "
50
+ f"each change was fixing the last one."
51
+ ),
52
+ key=f"{path}:{events[0].seq:08d}",
53
+ branch=branch.name,
54
+ count=len(cluster),
55
+ evidence=tuple(e.uid for e in events),
56
+ metrics={
57
+ "path": path,
58
+ "writes": len(cluster),
59
+ "window_span": span,
60
+ "first_seq": events[0].seq,
61
+ "last_seq": events[-1].seq,
62
+ },
63
+ )
64
+ )
65
+ return findings
66
+
67
+
68
+ def _cluster(indices: list[int], window: int) -> list[list[int]]:
69
+ """Split positions into runs where each write is within ``window`` of the last."""
70
+ if not indices:
71
+ return []
72
+ clusters: list[list[int]] = []
73
+ current = [indices[0]]
74
+ for index in indices[1:]:
75
+ if index - current[-1] <= window:
76
+ current.append(index)
77
+ else:
78
+ clusters.append(current)
79
+ current = [index]
80
+ clusters.append(current)
81
+ return clusters
82
+
83
+
84
+ def _short(path: str, keep: int = 2) -> str:
85
+ parts = [p for p in path.split("/") if p]
86
+ return "/".join(parts[-keep:]) if parts else path
blackbox/diff.py ADDED
@@ -0,0 +1,123 @@
1
+ """Comparing two sets of runs.
2
+
3
+ The question people actually have when they change an agent is not "what did
4
+ this run cost" but "did that change help". Nobody can answer it today, so
5
+ prompt and tooling changes get made on vibes: you tweak the system prompt, run
6
+ it again, and decide it feels better.
7
+
8
+ A diff makes the question answerable. Because everything upstream is
9
+ deterministic, the same traces always produce the same comparison, so a
10
+ difference is a difference in the agent, never in the measurement.
11
+
12
+ Run counts are allowed to differ -- in practice "before" is one run and
13
+ "after" is three -- so every rate is compared directly and every total is also
14
+ reported per run, which is the only honest way to line up uneven sides.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from dataclasses import dataclass
20
+ from typing import Any
21
+
22
+ from blackbox.aggregate import Corpus
23
+
24
+ LOWER = "lower"
25
+ HIGHER = "higher"
26
+ NEUTRAL = "neutral"
27
+
28
+ USD = "usd"
29
+ RATE = "rate"
30
+ COUNT = "count"
31
+ DURATION = "duration"
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class Metric:
36
+ key: str
37
+ label: str
38
+ unit: str
39
+ better: str
40
+ per_run: bool = False
41
+
42
+
43
+ # Ordered as they are read: money first, then what caused it, then volume.
44
+ METRICS: tuple[Metric, ...] = (
45
+ Metric("total_usd", "cost", USD, LOWER, per_run=True),
46
+ Metric("wasted_usd", "wasted", USD, LOWER, per_run=True),
47
+ Metric("wasted_share", "wasted share", RATE, LOWER),
48
+ Metric("cache_hit_rate", "cache hit rate", RATE, HIGHER),
49
+ Metric("failure_rate", "tool failure rate", RATE, LOWER),
50
+ Metric("findings", "findings", COUNT, LOWER, per_run=True),
51
+ Metric("tool_calls", "tool calls", COUNT, NEUTRAL, per_run=True),
52
+ Metric("active_seconds", "active time", DURATION, NEUTRAL, per_run=True),
53
+ )
54
+
55
+
56
+ def _verdict(metric: Metric, delta: float) -> str:
57
+ if abs(delta) < 1e-9 or metric.better == NEUTRAL:
58
+ return ""
59
+ improved = delta < 0 if metric.better == LOWER else delta > 0
60
+ return "better" if improved else "worse"
61
+
62
+
63
+ def compare(before: Corpus, after: Corpus) -> dict[str, Any]:
64
+ """Line up two corpora metric by metric."""
65
+ left = before.summary()
66
+ right = after.summary()
67
+ left_runs = max(left["runs"], 1)
68
+ right_runs = max(right["runs"], 1)
69
+
70
+ rows = []
71
+ for metric in METRICS:
72
+ a = float(left.get(metric.key) or 0.0)
73
+ b = float(right.get(metric.key) or 0.0)
74
+ delta = b - a
75
+ row: dict[str, Any] = {
76
+ "key": metric.key,
77
+ "label": metric.label,
78
+ "unit": metric.unit,
79
+ "before": a,
80
+ "after": b,
81
+ "delta": delta,
82
+ "pct_change": (delta / a) if a else None,
83
+ "verdict": _verdict(metric, delta),
84
+ }
85
+ if metric.per_run:
86
+ per_a = a / left_runs
87
+ per_b = b / right_runs
88
+ row["before_per_run"] = per_a
89
+ row["after_per_run"] = per_b
90
+ row["delta_per_run"] = per_b - per_a
91
+ # With uneven sides the per-run figure is the comparable one, so
92
+ # the verdict follows it rather than the raw total.
93
+ if left_runs != right_runs:
94
+ row["verdict"] = _verdict(metric, per_b - per_a)
95
+ rows.append(row)
96
+
97
+ detectors = sorted(set(left["by_detector"]) | set(right["by_detector"]))
98
+ by_detector = []
99
+ for name in detectors:
100
+ a = left["by_detector"].get(name, 0)
101
+ b = right["by_detector"].get(name, 0)
102
+ by_detector.append(
103
+ {
104
+ "detector": name,
105
+ "before": a,
106
+ "after": b,
107
+ "delta": b - a,
108
+ "before_per_run": a / left_runs,
109
+ "after_per_run": b / right_runs,
110
+ "verdict": _verdict(Metric(name, name, COUNT, LOWER), (b / right_runs) - (a / left_runs)),
111
+ }
112
+ )
113
+
114
+ return {
115
+ "runs": {"before": left["runs"], "after": right["runs"]},
116
+ "uneven": left["runs"] != right["runs"],
117
+ "metrics": rows,
118
+ "by_detector": by_detector,
119
+ "unpriced": {
120
+ "before": left["total_usd"] == 0 and left["tokens"] > 0,
121
+ "after": right["total_usd"] == 0 and right["tokens"] > 0,
122
+ },
123
+ }
blackbox/discover.py ADDED
@@ -0,0 +1,189 @@
1
+ """Finding trace files, so nobody has to know a UUID.
2
+
3
+ Agent transcripts live at ``~/.claude/projects/<encoded-cwd>/<session-id>.jsonl``.
4
+ Nobody remembers the session id of the run they just finished, and requiring it
5
+ is the difference between a tool people try once and a tool people use.
6
+
7
+ The directory name is the working directory with every non-alphanumeric
8
+ character replaced by a hyphen. That rule is derived, not assumed: it was
9
+ checked against every project directory on the machine this was written on by
10
+ comparing each directory name to the ``cwd`` recorded inside its transcripts.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import glob
16
+ import json
17
+ import os
18
+ import re
19
+ from dataclasses import dataclass
20
+
21
+ DEFAULT_ROOT = os.path.expanduser("~/.claude/projects")
22
+
23
+ # Other agents keep their transcripts elsewhere and encode the project
24
+ # differently -- Codex files record the working directory inside the file
25
+ # rather than in the path. Discovery handles both so "which agent wrote this"
26
+ # is never a question the user has to answer.
27
+ CODEX_ROOTS = (
28
+ os.path.expanduser("~/.codex/sessions"),
29
+ os.path.expanduser("~/.codex/archived_sessions"),
30
+ )
31
+
32
+
33
+ def all_roots() -> list[str]:
34
+ """Every transcript root that exists on this machine."""
35
+ roots = [DEFAULT_ROOT, *CODEX_ROOTS]
36
+ return [r for r in roots if os.path.isdir(r)]
37
+
38
+ _NON_ALNUM = re.compile(r"[^A-Za-z0-9]")
39
+
40
+
41
+ def encode_cwd(path: str) -> str:
42
+ """The project directory name a working directory maps to."""
43
+ return _NON_ALNUM.sub("-", os.path.abspath(path))
44
+
45
+
46
+ @dataclass
47
+ class Session:
48
+ path: str
49
+ project: str
50
+ modified: float
51
+ size: int
52
+ cwd: str | None = None
53
+
54
+ @property
55
+ def session_id(self) -> str:
56
+ return os.path.splitext(os.path.basename(self.path))[0]
57
+
58
+ @property
59
+ def label(self) -> str:
60
+ """A readable project name, however the vendor recorded it."""
61
+ if self.cwd:
62
+ return self.cwd
63
+ return decode_project(self.project)
64
+
65
+
66
+ def _session(path: str) -> Session:
67
+ stat = os.stat(path)
68
+ return Session(
69
+ path=path,
70
+ project=os.path.basename(os.path.dirname(path)),
71
+ modified=stat.st_mtime,
72
+ size=stat.st_size,
73
+ cwd=recorded_cwd(path),
74
+ )
75
+
76
+
77
+ def recorded_cwd(path: str, max_lines: int = 6) -> str | None:
78
+ """The working directory a transcript names inside itself, if it does.
79
+
80
+ Codex records it in a header row instead of encoding it into the path.
81
+ Only the first few lines are read, so this stays cheap enough to run
82
+ across every transcript on the machine.
83
+ """
84
+ try:
85
+ with open(path, "r", encoding="utf-8", errors="replace") as fh:
86
+ for _ in range(max_lines):
87
+ line = fh.readline()
88
+ if not line:
89
+ return None
90
+ line = line.strip()
91
+ if not line:
92
+ continue
93
+ try:
94
+ row = json.loads(line)
95
+ except json.JSONDecodeError:
96
+ return None
97
+ if not isinstance(row, dict):
98
+ return None
99
+ payload = row.get("payload")
100
+ if isinstance(payload, dict) and isinstance(payload.get("cwd"), str):
101
+ return payload["cwd"]
102
+ if isinstance(row.get("cwd"), str):
103
+ return row["cwd"]
104
+ except OSError:
105
+ return None
106
+ return None
107
+
108
+
109
+ def traces_in(path: str) -> list[str]:
110
+ """Every trace under ``path``, which may be a file, a directory or a glob."""
111
+ if os.path.isfile(path):
112
+ return [path]
113
+ if os.path.isdir(path):
114
+ return sorted(glob.glob(os.path.join(path, "**", "*.jsonl"), recursive=True))
115
+ return sorted(glob.glob(path, recursive=True))
116
+
117
+
118
+ def candidate_dirs(cwd: str | None = None, root: str | None = None) -> list[str]:
119
+ """Every project directory this working directory could be recorded under.
120
+
121
+ A path and its symlink-resolved form encode differently -- on macOS
122
+ ``/tmp/x`` resolves to ``/private/tmp/x`` -- and the agent recorded
123
+ whichever one it saw. Checking both is the difference between finding a
124
+ session and reporting that none exists.
125
+ """
126
+ root = root or DEFAULT_ROOT
127
+ base = cwd or os.getcwd()
128
+ names = []
129
+ for variant in (os.path.abspath(base), os.path.realpath(base)):
130
+ name = encode_cwd(variant)
131
+ if name not in names:
132
+ names.append(name)
133
+ return [os.path.join(root, name) for name in names]
134
+
135
+
136
+ def sessions_for_cwd(cwd: str | None = None, root: str | None = None) -> list[Session]:
137
+ """Sessions recorded for one working directory, newest first."""
138
+ found: dict[str, Session] = {}
139
+
140
+ # Path-encoded projects (Claude Code).
141
+ for directory in candidate_dirs(cwd, root or DEFAULT_ROOT):
142
+ if not os.path.isdir(directory):
143
+ continue
144
+ for path in glob.glob(os.path.join(directory, "*.jsonl")):
145
+ found.setdefault(os.path.realpath(path), _session(path))
146
+
147
+ # Transcripts that record their working directory inside the file.
148
+ if root is None:
149
+ wanted = {os.path.abspath(cwd or os.getcwd()), os.path.realpath(cwd or os.getcwd())}
150
+ for codex_root in CODEX_ROOTS:
151
+ if not os.path.isdir(codex_root):
152
+ continue
153
+ for path in glob.glob(os.path.join(codex_root, "**", "*.jsonl"), recursive=True):
154
+ real = os.path.realpath(path)
155
+ if real in found:
156
+ continue
157
+ recorded = recorded_cwd(path)
158
+ if recorded and (
159
+ os.path.abspath(recorded) in wanted or os.path.realpath(recorded) in wanted
160
+ ):
161
+ found[real] = _session(path)
162
+
163
+ return sorted(found.values(), key=lambda s: s.modified, reverse=True)
164
+
165
+
166
+ def latest_for_cwd(cwd: str | None = None, root: str | None = None) -> Session | None:
167
+ """The most recently written session for this working directory."""
168
+ found = sessions_for_cwd(cwd, root)
169
+ return found[0] if found else None
170
+
171
+
172
+ def recent_sessions(root: str | None = None, limit: int = 20) -> list[Session]:
173
+ """The most recently written sessions across every project."""
174
+ roots = [root] if root else all_roots()
175
+ seen: dict[str, Session] = {}
176
+ for base in roots:
177
+ for path in glob.glob(os.path.join(base, "**", "*.jsonl"), recursive=True):
178
+ seen.setdefault(os.path.realpath(path), _session(path))
179
+ found = sorted(seen.values(), key=lambda s: s.modified, reverse=True)
180
+ return found[:limit]
181
+
182
+
183
+ def decode_project(name: str) -> str:
184
+ """A readable label for an encoded project directory name.
185
+
186
+ The encoding is lossy -- a hyphen could have been a slash, a space or a
187
+ dot -- so this is presentation only and never used to resolve a path.
188
+ """
189
+ return name.replace("-", "/").lstrip("/") or name
blackbox/events.py ADDED
@@ -0,0 +1,163 @@
1
+ """Canonical event model.
2
+
3
+ Every adapter turns its native trace format into a list of :class:`Event`.
4
+ Nothing downstream -- graph, cost, detectors, reports -- knows which agent
5
+ framework produced the trace. That boundary is the whole point of this module:
6
+ when a vendor changes their log format, only an adapter changes.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ from dataclasses import asdict, dataclass, field
14
+ from datetime import datetime, timezone
15
+ from typing import Any
16
+
17
+ # --- event kinds ----------------------------------------------------------
18
+
19
+ USER_MESSAGE = "user_message"
20
+ ASSISTANT_MESSAGE = "assistant_message"
21
+ TOOL_CALL = "tool_call"
22
+ TOOL_RESULT = "tool_result"
23
+ META = "meta"
24
+
25
+ KINDS = (USER_MESSAGE, ASSISTANT_MESSAGE, TOOL_CALL, TOOL_RESULT, META)
26
+
27
+ MAIN_BRANCH = "main"
28
+
29
+
30
+ def parse_ts(value: Any) -> datetime | None:
31
+ """Parse an ISO-8601 timestamp, tolerating a trailing ``Z``."""
32
+ if not isinstance(value, str) or not value:
33
+ return None
34
+ try:
35
+ dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
36
+ except ValueError:
37
+ return None
38
+ if dt.tzinfo is None:
39
+ dt = dt.replace(tzinfo=timezone.utc)
40
+ return dt.astimezone(timezone.utc)
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class Usage:
45
+ """Token usage for one model call, with the cache tiers kept apart.
46
+
47
+ The cache split matters: a 5-minute cache write and a 1-hour cache write
48
+ are billed at different multiples of the input rate, and a cache *read* is
49
+ an order of magnitude cheaper than either. Collapsing these into one
50
+ "input tokens" number is how an agent's real cost gets hidden.
51
+ """
52
+
53
+ input_tokens: int = 0
54
+ output_tokens: int = 0
55
+ cache_read_tokens: int = 0
56
+ cache_write_5m_tokens: int = 0
57
+ cache_write_1h_tokens: int = 0
58
+ thinking_tokens: int = 0
59
+
60
+ @property
61
+ def cache_write_tokens(self) -> int:
62
+ return self.cache_write_5m_tokens + self.cache_write_1h_tokens
63
+
64
+ @property
65
+ def billed_input_tokens(self) -> int:
66
+ return self.input_tokens + self.cache_read_tokens + self.cache_write_tokens
67
+
68
+ @property
69
+ def total_tokens(self) -> int:
70
+ return self.billed_input_tokens + self.output_tokens
71
+
72
+ def __add__(self, other: "Usage") -> "Usage":
73
+ return Usage(
74
+ input_tokens=self.input_tokens + other.input_tokens,
75
+ output_tokens=self.output_tokens + other.output_tokens,
76
+ cache_read_tokens=self.cache_read_tokens + other.cache_read_tokens,
77
+ cache_write_5m_tokens=self.cache_write_5m_tokens + other.cache_write_5m_tokens,
78
+ cache_write_1h_tokens=self.cache_write_1h_tokens + other.cache_write_1h_tokens,
79
+ thinking_tokens=self.thinking_tokens + other.thinking_tokens,
80
+ )
81
+
82
+ def is_empty(self) -> bool:
83
+ return self.total_tokens == 0
84
+
85
+
86
+ ZERO_USAGE = Usage()
87
+
88
+
89
+ @dataclass(frozen=True)
90
+ class Event:
91
+ """One thing that happened in an agent run.
92
+
93
+ ``seq`` is the authoritative order (source line order). Timestamps are
94
+ advisory: they can be absent, and in long-lived sessions they can jump.
95
+ Every downstream pass orders by ``seq`` so results never depend on clocks.
96
+ """
97
+
98
+ uid: str
99
+ seq: int
100
+ kind: str
101
+ parent_uid: str | None = None
102
+ ts: datetime | None = None
103
+ is_sidechain: bool = False
104
+ branch: str = MAIN_BRANCH
105
+
106
+ model: str | None = None
107
+ usage: Usage = ZERO_USAGE
108
+
109
+ tool_name: str | None = None
110
+ tool_use_id: str | None = None
111
+ tool_input: dict[str, Any] = field(default_factory=dict)
112
+ tool_ok: bool | None = None
113
+ tool_output: str = ""
114
+
115
+ text: str = ""
116
+ flags: tuple[str, ...] = ()
117
+ raw_type: str = ""
118
+ source_line: int = 0
119
+
120
+ # -- derived helpers ---------------------------------------------------
121
+
122
+ @property
123
+ def is_tool(self) -> bool:
124
+ return self.kind in (TOOL_CALL, TOOL_RESULT)
125
+
126
+ def output_digest(self) -> str:
127
+ """Stable digest of a tool result's payload, for contradiction checks."""
128
+ return hashlib.sha256(self.tool_output.encode("utf-8", "replace")).hexdigest()[:16]
129
+
130
+ def input_digest(self) -> str:
131
+ """Stable digest of a tool call's *meaningful* input.
132
+
133
+ Keys that describe rather than determine the call are dropped, so that
134
+ two invocations which do the same work collapse to the same digest even
135
+ when their prose differs.
136
+ """
137
+ ignored = {"description", "action_summary", "label", "reason", "explanation"}
138
+ payload = {k: v for k, v in sorted(self.tool_input.items()) if k not in ignored}
139
+ blob = json.dumps(payload, sort_keys=True, default=str, ensure_ascii=True)
140
+ return hashlib.sha256(blob.encode("utf-8")).hexdigest()[:16]
141
+
142
+ def to_row(self) -> dict[str, Any]:
143
+ """Flat dict for the DuckDB event table."""
144
+ d = asdict(self)
145
+ d.pop("usage")
146
+ d["ts"] = self.ts.isoformat() if self.ts else None
147
+ d["tool_input"] = json.dumps(self.tool_input, sort_keys=True, default=str)
148
+ d["flags"] = ",".join(self.flags)
149
+ # Stored in full on purpose: the contradiction detector hashes tool
150
+ # output, so a truncated copy would make a replay disagree with the
151
+ # original pass. Truncation belongs in the renderers, not the store.
152
+ d["tool_output"] = self.tool_output
153
+ d["text"] = self.text
154
+ for name in (
155
+ "input_tokens",
156
+ "output_tokens",
157
+ "cache_read_tokens",
158
+ "cache_write_5m_tokens",
159
+ "cache_write_1h_tokens",
160
+ "thinking_tokens",
161
+ ):
162
+ d[name] = getattr(self.usage, name)
163
+ return d