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.
- agent_blackbox_cli-0.3.0.dist-info/METADATA +623 -0
- agent_blackbox_cli-0.3.0.dist-info/RECORD +43 -0
- agent_blackbox_cli-0.3.0.dist-info/WHEEL +5 -0
- agent_blackbox_cli-0.3.0.dist-info/entry_points.txt +2 -0
- agent_blackbox_cli-0.3.0.dist-info/licenses/LICENSE +21 -0
- agent_blackbox_cli-0.3.0.dist-info/top_level.txt +1 -0
- blackbox/__init__.py +61 -0
- blackbox/__main__.py +6 -0
- blackbox/adapters/__init__.py +0 -0
- blackbox/adapters/_linking.py +31 -0
- blackbox/adapters/base.py +38 -0
- blackbox/adapters/claude_code.py +341 -0
- blackbox/adapters/codex.py +318 -0
- blackbox/adapters/labelled_turns.py +371 -0
- blackbox/adapters/registry.py +30 -0
- blackbox/aggregate.py +119 -0
- blackbox/analysis.py +325 -0
- blackbox/bench.py +466 -0
- blackbox/cli.py +405 -0
- blackbox/cost.py +138 -0
- blackbox/describe.py +116 -0
- blackbox/detectors/__init__.py +32 -0
- blackbox/detectors/base.py +83 -0
- blackbox/detectors/context_bloat.py +137 -0
- blackbox/detectors/contradictions.py +180 -0
- blackbox/detectors/error_clusters.py +114 -0
- blackbox/detectors/retry_loops.py +98 -0
- blackbox/detectors/stalls.py +117 -0
- blackbox/detectors/thrash.py +86 -0
- blackbox/diff.py +123 -0
- blackbox/discover.py +189 -0
- blackbox/events.py +163 -0
- blackbox/graph.py +150 -0
- blackbox/guard.py +528 -0
- blackbox/guard_cli.py +349 -0
- blackbox/pricing.py +137 -0
- blackbox/py.typed +0 -0
- blackbox/replay.py +65 -0
- blackbox/report/__init__.py +0 -0
- blackbox/report/html.py +375 -0
- blackbox/report/text.py +287 -0
- blackbox/store.py +215 -0
- blackbox/toolinfo.py +336 -0
blackbox/cli.py
ADDED
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
"""Command line interface.
|
|
2
|
+
|
|
3
|
+
blackbox # the latest run in this directory
|
|
4
|
+
blackbox run.jsonl # one specific trace
|
|
5
|
+
blackbox ~/.claude/projects/my-app/ # every run for one project
|
|
6
|
+
blackbox ls # recent sessions, newest first
|
|
7
|
+
blackbox scan # every local run, aggregated
|
|
8
|
+
blackbox diff before.jsonl after.jsonl # did that change help?
|
|
9
|
+
blackbox guard install # stop loops while the agent runs
|
|
10
|
+
blackbox guard replay run.jsonl # what the guard would have done
|
|
11
|
+
blackbox run.jsonl --html report.html # self-contained page
|
|
12
|
+
blackbox run.jsonl --db run.duckdb # queryable event store
|
|
13
|
+
blackbox run.jsonl --verify # prove the findings replay exactly
|
|
14
|
+
blackbox --replay run.duckdb # re-derive from a stored run
|
|
15
|
+
blackbox bench data/ # score detectors against labelled waste
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import argparse
|
|
21
|
+
import json
|
|
22
|
+
import os
|
|
23
|
+
import sys
|
|
24
|
+
import tempfile
|
|
25
|
+
|
|
26
|
+
from blackbox import discover
|
|
27
|
+
from blackbox.adapters.registry import ADAPTERS, NoAdapterError
|
|
28
|
+
from blackbox.analysis import analyze
|
|
29
|
+
from blackbox.detectors.base import Config
|
|
30
|
+
from blackbox.pricing import PRICING_AS_OF
|
|
31
|
+
from blackbox.report import html as html_report
|
|
32
|
+
from blackbox.report import text as text_report
|
|
33
|
+
|
|
34
|
+
from blackbox import __version__ as VERSION
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
38
|
+
parser = argparse.ArgumentParser(
|
|
39
|
+
prog="blackbox",
|
|
40
|
+
description=(
|
|
41
|
+
"Structured analytics for one agent run. Drop in a trace file; get cost "
|
|
42
|
+
"attribution, failure clusters and a deterministic replay. No SDK, no "
|
|
43
|
+
"vendor, no model calls."
|
|
44
|
+
),
|
|
45
|
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
|
46
|
+
epilog=f"adapters: {', '.join(m.NAME for m in ADAPTERS)} · prices as of {PRICING_AS_OF}",
|
|
47
|
+
)
|
|
48
|
+
parser.add_argument(
|
|
49
|
+
"trace",
|
|
50
|
+
nargs="?",
|
|
51
|
+
help=(
|
|
52
|
+
"a trace file, a directory of traces, or one of: "
|
|
53
|
+
"'ls' (recent sessions), 'scan' (every local run). "
|
|
54
|
+
"Omit it to use the latest run for the current directory."
|
|
55
|
+
),
|
|
56
|
+
)
|
|
57
|
+
parser.add_argument(
|
|
58
|
+
"root",
|
|
59
|
+
nargs="?",
|
|
60
|
+
help="for 'scan' and 'ls': where to look. For 'diff': the BEFORE side",
|
|
61
|
+
)
|
|
62
|
+
parser.add_argument(
|
|
63
|
+
"against",
|
|
64
|
+
nargs="?",
|
|
65
|
+
help="for 'diff': the AFTER side (a trace, a directory or a glob)",
|
|
66
|
+
)
|
|
67
|
+
parser.add_argument("--limit", type=int, default=20, help="rows for 'ls' (default 20)")
|
|
68
|
+
parser.add_argument("--replay", metavar="DB", help="re-derive the report from a stored run")
|
|
69
|
+
parser.add_argument("--adapter", help="force an adapter instead of sniffing")
|
|
70
|
+
parser.add_argument(
|
|
71
|
+
"--prices",
|
|
72
|
+
metavar="FILE",
|
|
73
|
+
help=(
|
|
74
|
+
"JSON of {model: {input, output, cache_read?}} in dollars per million "
|
|
75
|
+
"tokens, for models this build does not ship rates for"
|
|
76
|
+
),
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
out = parser.add_argument_group("output")
|
|
80
|
+
out.add_argument("--html", metavar="PATH", help="write a self-contained HTML report")
|
|
81
|
+
out.add_argument("--json", metavar="PATH", help="write the canonical payload as JSON")
|
|
82
|
+
out.add_argument("--db", metavar="PATH", help="write the DuckDB event store")
|
|
83
|
+
out.add_argument("-q", "--quiet", action="store_true", help="suppress the stdout report")
|
|
84
|
+
out.add_argument(
|
|
85
|
+
"--max-findings",
|
|
86
|
+
metavar="N",
|
|
87
|
+
default="25",
|
|
88
|
+
help="findings to print: a number or 'all' (default 25)",
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
thresholds = parser.add_argument_group("thresholds")
|
|
92
|
+
thresholds.add_argument("--stall-seconds", type=float, default=Config.stall_seconds)
|
|
93
|
+
thresholds.add_argument("--idle-seconds", type=float, default=Config.idle_seconds)
|
|
94
|
+
thresholds.add_argument("--retry-min-repeats", type=int, default=Config.retry_min_repeats)
|
|
95
|
+
thresholds.add_argument("--retry-window", type=int, default=Config.retry_window)
|
|
96
|
+
thresholds.add_argument("--thrash-min-edits", type=int, default=Config.thrash_min_edits)
|
|
97
|
+
thresholds.add_argument("--thrash-window", type=int, default=Config.thrash_window)
|
|
98
|
+
thresholds.add_argument("--error-cluster-min", type=int, default=Config.error_cluster_min)
|
|
99
|
+
thresholds.add_argument("--bloat-min-tokens", type=int, default=Config.bloat_min_tokens)
|
|
100
|
+
thresholds.add_argument("--bloat-min-usd", type=float, default=Config.bloat_min_usd)
|
|
101
|
+
|
|
102
|
+
parser.add_argument(
|
|
103
|
+
"--verify",
|
|
104
|
+
action="store_true",
|
|
105
|
+
help="store the run, replay it, and check the findings are byte-identical",
|
|
106
|
+
)
|
|
107
|
+
parser.add_argument("--version", action="version", version=f"blackbox {VERSION}")
|
|
108
|
+
return parser
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _max_findings(raw: str) -> int | None:
|
|
112
|
+
if raw.lower() == "all":
|
|
113
|
+
return None
|
|
114
|
+
try:
|
|
115
|
+
return max(0, int(raw))
|
|
116
|
+
except ValueError:
|
|
117
|
+
raise SystemExit(f"--max-findings expects a number or 'all', got {raw!r}")
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _bench(argv: list[str]) -> int:
|
|
121
|
+
"""``blackbox bench``: score the detectors against labelled waste."""
|
|
122
|
+
from blackbox import bench
|
|
123
|
+
|
|
124
|
+
parser = argparse.ArgumentParser(
|
|
125
|
+
prog="blackbox bench",
|
|
126
|
+
description=(
|
|
127
|
+
"Score the detectors against the labelled trajectories released with "
|
|
128
|
+
"'How Do AI Agents Waste Your Money?' (arXiv 2611.07238). No model calls."
|
|
129
|
+
),
|
|
130
|
+
)
|
|
131
|
+
parser.add_argument("paths", nargs="+", help=".jsonl files or folders of them")
|
|
132
|
+
parser.add_argument("--json", metavar="PATH", help="write the full results here")
|
|
133
|
+
parser.add_argument("--markdown", metavar="PATH", help="write the README section here")
|
|
134
|
+
parser.add_argument(
|
|
135
|
+
"--update-readme",
|
|
136
|
+
metavar="README",
|
|
137
|
+
help="replace the README's benchmark block with the new results",
|
|
138
|
+
)
|
|
139
|
+
parser.add_argument("--limit", type=int, default=None, help="stop after N trajectories")
|
|
140
|
+
args = parser.parse_args(argv)
|
|
141
|
+
|
|
142
|
+
files = bench.jsonl_files(args.paths)
|
|
143
|
+
if not files:
|
|
144
|
+
print("error: no .jsonl files found under " + ", ".join(args.paths), file=sys.stderr)
|
|
145
|
+
return 1
|
|
146
|
+
results = bench.run(files, limit=args.limit)
|
|
147
|
+
if results["totals"]["trajectories"] == 0:
|
|
148
|
+
print("error: no labelled trajectories in those files", file=sys.stderr)
|
|
149
|
+
return 1
|
|
150
|
+
section = bench.markdown(results)
|
|
151
|
+
print(section)
|
|
152
|
+
if args.json:
|
|
153
|
+
with open(args.json, "w", encoding="utf-8") as fh:
|
|
154
|
+
json.dump(results, fh, indent=2, sort_keys=True)
|
|
155
|
+
fh.write("\n")
|
|
156
|
+
print(f"wrote results {args.json}")
|
|
157
|
+
if args.markdown:
|
|
158
|
+
with open(args.markdown, "w", encoding="utf-8") as fh:
|
|
159
|
+
fh.write(section)
|
|
160
|
+
print(f"wrote section {args.markdown}")
|
|
161
|
+
if args.update_readme:
|
|
162
|
+
with open(args.update_readme, "r", encoding="utf-8") as fh:
|
|
163
|
+
readme = fh.read()
|
|
164
|
+
try:
|
|
165
|
+
updated = bench.update_readme(readme, section)
|
|
166
|
+
except ValueError as exc:
|
|
167
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
168
|
+
return 1
|
|
169
|
+
with open(args.update_readme, "w", encoding="utf-8") as fh:
|
|
170
|
+
fh.write(updated)
|
|
171
|
+
print(f"updated {args.update_readme}")
|
|
172
|
+
return 0
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def main(argv: list[str] | None = None) -> int:
|
|
176
|
+
raw = list(sys.argv[1:] if argv is None else argv)
|
|
177
|
+
if raw[:1] == ["bench"]:
|
|
178
|
+
return _bench(raw[1:])
|
|
179
|
+
if raw and raw[0] == "guard":
|
|
180
|
+
# The guard has its own subcommands and flags; keep it out of the
|
|
181
|
+
# report's positional grammar.
|
|
182
|
+
from blackbox import guard_cli
|
|
183
|
+
|
|
184
|
+
return guard_cli.main(raw[1:])
|
|
185
|
+
|
|
186
|
+
parser = build_parser()
|
|
187
|
+
args = parser.parse_args(argv)
|
|
188
|
+
|
|
189
|
+
if args.trace == "ls":
|
|
190
|
+
return _list_sessions(args.root, args.limit)
|
|
191
|
+
if args.trace and args.replay:
|
|
192
|
+
print("error: pass a trace file or --replay, not both", file=sys.stderr)
|
|
193
|
+
return 2
|
|
194
|
+
|
|
195
|
+
config = Config(
|
|
196
|
+
stall_seconds=args.stall_seconds,
|
|
197
|
+
idle_seconds=args.idle_seconds,
|
|
198
|
+
retry_min_repeats=args.retry_min_repeats,
|
|
199
|
+
retry_window=args.retry_window,
|
|
200
|
+
thrash_min_edits=args.thrash_min_edits,
|
|
201
|
+
thrash_window=args.thrash_window,
|
|
202
|
+
error_cluster_min=args.error_cluster_min,
|
|
203
|
+
bloat_min_tokens=args.bloat_min_tokens,
|
|
204
|
+
bloat_min_usd=args.bloat_min_usd,
|
|
205
|
+
)
|
|
206
|
+
|
|
207
|
+
overrides = {}
|
|
208
|
+
if args.prices:
|
|
209
|
+
try:
|
|
210
|
+
with open(args.prices, "r", encoding="utf-8") as fh:
|
|
211
|
+
overrides = json.load(fh)
|
|
212
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
213
|
+
print(f"error: could not read --prices {args.prices}: {exc}", file=sys.stderr)
|
|
214
|
+
return 2
|
|
215
|
+
|
|
216
|
+
if args.trace == "scan":
|
|
217
|
+
return _scan(args.root, config, args, overrides)
|
|
218
|
+
|
|
219
|
+
if args.trace == "diff":
|
|
220
|
+
if not args.root or not args.against:
|
|
221
|
+
print("usage: blackbox diff BEFORE AFTER", file=sys.stderr)
|
|
222
|
+
return 2
|
|
223
|
+
return _diff(args.root, args.against, config, args, overrides)
|
|
224
|
+
|
|
225
|
+
target = args.trace
|
|
226
|
+
if not target and not args.replay:
|
|
227
|
+
session = discover.latest_for_cwd()
|
|
228
|
+
if session is None:
|
|
229
|
+
print(
|
|
230
|
+
"No agent transcripts found for this directory.\n"
|
|
231
|
+
+ "".join(f" Looked in: {d}\n" for d in discover.candidate_dirs())
|
|
232
|
+
+ " Try 'blackbox ls' to see recent sessions, or pass a trace file.",
|
|
233
|
+
file=sys.stderr,
|
|
234
|
+
)
|
|
235
|
+
return 1
|
|
236
|
+
target = session.path
|
|
237
|
+
print(f"using latest session for this directory: {os.path.basename(target)}")
|
|
238
|
+
|
|
239
|
+
if target and os.path.isdir(target):
|
|
240
|
+
return _aggregate(discover.traces_in(target), config, args, title=target, overrides=overrides)
|
|
241
|
+
|
|
242
|
+
try:
|
|
243
|
+
if args.replay:
|
|
244
|
+
from blackbox.replay import replay as replay_run
|
|
245
|
+
|
|
246
|
+
if not os.path.exists(args.replay):
|
|
247
|
+
print(f"error: no such store: {args.replay}", file=sys.stderr)
|
|
248
|
+
return 1
|
|
249
|
+
analysis = replay_run(args.replay)
|
|
250
|
+
else:
|
|
251
|
+
if not os.path.exists(target):
|
|
252
|
+
print(f"error: no such file: {target}", file=sys.stderr)
|
|
253
|
+
return 1
|
|
254
|
+
analysis = analyze(
|
|
255
|
+
target, config=config, adapter=args.adapter, price_overrides=overrides
|
|
256
|
+
)
|
|
257
|
+
except NoAdapterError as exc:
|
|
258
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
259
|
+
return 1
|
|
260
|
+
|
|
261
|
+
if not args.quiet:
|
|
262
|
+
print(text_report.render(analysis, max_findings=_max_findings(args.max_findings)))
|
|
263
|
+
|
|
264
|
+
if args.db:
|
|
265
|
+
from blackbox import store
|
|
266
|
+
|
|
267
|
+
store.write(args.db, analysis)
|
|
268
|
+
print(f"wrote event store {args.db}")
|
|
269
|
+
|
|
270
|
+
if args.html:
|
|
271
|
+
with open(args.html, "w", encoding="utf-8") as fh:
|
|
272
|
+
fh.write(html_report.render(analysis))
|
|
273
|
+
print(f"wrote html report {args.html}")
|
|
274
|
+
|
|
275
|
+
if args.json:
|
|
276
|
+
with open(args.json, "w", encoding="utf-8") as fh:
|
|
277
|
+
json.dump(analysis.payload(), fh, indent=2, sort_keys=True, default=str)
|
|
278
|
+
fh.write("\n")
|
|
279
|
+
print(f"wrote json payload {args.json}")
|
|
280
|
+
|
|
281
|
+
if args.verify:
|
|
282
|
+
return _verify(analysis)
|
|
283
|
+
|
|
284
|
+
return 0
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _list_sessions(root: str | None, limit: int) -> int:
|
|
288
|
+
import datetime
|
|
289
|
+
|
|
290
|
+
sessions = discover.recent_sessions(root, limit)
|
|
291
|
+
if not sessions:
|
|
292
|
+
where = root or ", ".join(discover.all_roots()) or "any known location"
|
|
293
|
+
print(f"no transcripts found under {where}", file=sys.stderr)
|
|
294
|
+
return 1
|
|
295
|
+
print(f"{'modified':<17}{'size':>9} {'session':<14} project")
|
|
296
|
+
for session in sessions:
|
|
297
|
+
when = datetime.datetime.fromtimestamp(session.modified).strftime("%Y-%m-%d %H:%M")
|
|
298
|
+
print(
|
|
299
|
+
f"{when:<17}{session.size / 1024:>8.0f}K "
|
|
300
|
+
f"{session.session_id[:12]:<14} {session.label}"
|
|
301
|
+
)
|
|
302
|
+
return 0
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _aggregate(
|
|
306
|
+
paths: list[str], config: Config, args, title: str, overrides: dict | None = None
|
|
307
|
+
) -> int:
|
|
308
|
+
from blackbox import aggregate
|
|
309
|
+
from blackbox.report import text as text_report_mod
|
|
310
|
+
|
|
311
|
+
if not paths:
|
|
312
|
+
print(f"no traces found under {title}", file=sys.stderr)
|
|
313
|
+
return 1
|
|
314
|
+
|
|
315
|
+
corpus = aggregate.load(paths, config=config, price_overrides=overrides)
|
|
316
|
+
if not corpus.runs:
|
|
317
|
+
print("no traces could be read", file=sys.stderr)
|
|
318
|
+
return 1
|
|
319
|
+
|
|
320
|
+
if not args.quiet:
|
|
321
|
+
print(text_report_mod.render_corpus(corpus, title=title))
|
|
322
|
+
for path, reason in corpus.failed:
|
|
323
|
+
print(f" skipped {os.path.basename(path)}: {reason}", file=sys.stderr)
|
|
324
|
+
|
|
325
|
+
if args.json:
|
|
326
|
+
with open(args.json, "w", encoding="utf-8") as fh:
|
|
327
|
+
json.dump(corpus.summary(), fh, indent=2, sort_keys=True, default=str)
|
|
328
|
+
fh.write("\n")
|
|
329
|
+
print(f"wrote json summary {args.json}")
|
|
330
|
+
return 0
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _scan(root: str | None, config: Config, args, overrides: dict) -> int:
|
|
334
|
+
if root:
|
|
335
|
+
roots = [root]
|
|
336
|
+
title = f"every run under {root}"
|
|
337
|
+
else:
|
|
338
|
+
roots = discover.all_roots()
|
|
339
|
+
title = "every run on this machine"
|
|
340
|
+
if not roots:
|
|
341
|
+
print("no transcript directories found", file=sys.stderr)
|
|
342
|
+
return 1
|
|
343
|
+
paths: list[str] = []
|
|
344
|
+
for base in roots:
|
|
345
|
+
paths.extend(discover.traces_in(base))
|
|
346
|
+
return _aggregate(paths, config, args, title=title, overrides=overrides)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _diff(before: str, after: str, config: Config, args, overrides: dict) -> int:
|
|
350
|
+
"""Compare two sets of runs: did a change to the agent help?"""
|
|
351
|
+
from blackbox import aggregate, diff
|
|
352
|
+
from blackbox.report import text as text_report_mod
|
|
353
|
+
|
|
354
|
+
sides = {}
|
|
355
|
+
for label, target in (("before", before), ("after", after)):
|
|
356
|
+
paths = discover.traces_in(target)
|
|
357
|
+
if not paths:
|
|
358
|
+
print(f"error: no traces found for {label}: {target}", file=sys.stderr)
|
|
359
|
+
return 1
|
|
360
|
+
corpus = aggregate.load(paths, config=config, price_overrides=overrides)
|
|
361
|
+
if not corpus.runs:
|
|
362
|
+
print(f"error: no traces could be read for {label}: {target}", file=sys.stderr)
|
|
363
|
+
return 1
|
|
364
|
+
for path, reason in corpus.failed:
|
|
365
|
+
print(f" skipped {os.path.basename(path)}: {reason}", file=sys.stderr)
|
|
366
|
+
sides[label] = corpus
|
|
367
|
+
|
|
368
|
+
result = diff.compare(sides["before"], sides["after"])
|
|
369
|
+
|
|
370
|
+
if not args.quiet:
|
|
371
|
+
print(text_report_mod.render_diff(result, os.path.basename(before.rstrip("/")),
|
|
372
|
+
os.path.basename(after.rstrip("/"))))
|
|
373
|
+
|
|
374
|
+
if args.json:
|
|
375
|
+
with open(args.json, "w", encoding="utf-8") as fh:
|
|
376
|
+
json.dump(result, fh, indent=2, sort_keys=True, default=str)
|
|
377
|
+
fh.write("\n")
|
|
378
|
+
print(f"wrote json diff {args.json}")
|
|
379
|
+
return 0
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _verify(analysis) -> int:
|
|
383
|
+
"""Store, replay and compare -- the determinism claim, checked on real input."""
|
|
384
|
+
from blackbox import store
|
|
385
|
+
from blackbox.replay import replay as replay_run
|
|
386
|
+
|
|
387
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
388
|
+
db = os.path.join(tmp, "verify.duckdb")
|
|
389
|
+
store.write(db, analysis)
|
|
390
|
+
again = replay_run(db)
|
|
391
|
+
|
|
392
|
+
original = analysis.digest()
|
|
393
|
+
replayed = again.digest()
|
|
394
|
+
if original == replayed:
|
|
395
|
+
print(
|
|
396
|
+
f"verify OK {len(analysis.findings)} findings replayed byte-identical "
|
|
397
|
+
f"from the event store, with no model calls\n"
|
|
398
|
+
f" digest {original}"
|
|
399
|
+
)
|
|
400
|
+
return 0
|
|
401
|
+
|
|
402
|
+
print("verify FAILED replay did not reproduce the original payload", file=sys.stderr)
|
|
403
|
+
print(f" original {original}", file=sys.stderr)
|
|
404
|
+
print(f" replayed {replayed}", file=sys.stderr)
|
|
405
|
+
return 1
|
blackbox/cost.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""Cost attribution.
|
|
2
|
+
|
|
3
|
+
Tokens are counted per model and per branch, then priced. Three things this
|
|
4
|
+
does that a flat token total does not:
|
|
5
|
+
|
|
6
|
+
* **Separates the cache tiers.** A cache read is ~10x cheaper than fresh
|
|
7
|
+
input; a cache write is *more* expensive, and a 1-hour write more again.
|
|
8
|
+
* **Attributes to branches.** Subagent spend is reported as its own line, so
|
|
9
|
+
the main thread's cost is the main thread's cost.
|
|
10
|
+
* **Refuses to guess.** Tokens on a model missing from the price table are
|
|
11
|
+
counted and reported as unpriced. The total then carries an explicit
|
|
12
|
+
"at least" marker rather than a confident wrong number.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
|
|
19
|
+
from blackbox.events import MAIN_BRANCH, Event, Usage
|
|
20
|
+
from blackbox.pricing import PRICING_AS_OF, lookup
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class ModelCost:
|
|
25
|
+
model: str
|
|
26
|
+
usage: Usage
|
|
27
|
+
calls: int = 0
|
|
28
|
+
priced: bool = True
|
|
29
|
+
|
|
30
|
+
input_usd: float = 0.0
|
|
31
|
+
output_usd: float = 0.0
|
|
32
|
+
cache_read_usd: float = 0.0
|
|
33
|
+
cache_write_usd: float = 0.0
|
|
34
|
+
|
|
35
|
+
@property
|
|
36
|
+
def total_usd(self) -> float:
|
|
37
|
+
return self.input_usd + self.output_usd + self.cache_read_usd + self.cache_write_usd
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass
|
|
41
|
+
class CostReport:
|
|
42
|
+
by_model: list[ModelCost] = field(default_factory=list)
|
|
43
|
+
by_branch: dict[str, float] = field(default_factory=dict)
|
|
44
|
+
tokens_by_branch: dict[str, Usage] = field(default_factory=dict)
|
|
45
|
+
total_usd: float = 0.0
|
|
46
|
+
unpriced_models: list[str] = field(default_factory=list)
|
|
47
|
+
unpriced_tokens: int = 0
|
|
48
|
+
pricing_as_of: str = PRICING_AS_OF
|
|
49
|
+
|
|
50
|
+
@property
|
|
51
|
+
def is_complete(self) -> bool:
|
|
52
|
+
return not self.unpriced_models
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def total_usage(self) -> Usage:
|
|
56
|
+
total = Usage()
|
|
57
|
+
for mc in self.by_model:
|
|
58
|
+
total = total + mc.usage
|
|
59
|
+
return total
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def cache_write_1h_usd_share(self) -> float:
|
|
63
|
+
"""Fraction of spend going to 1-hour cache writes.
|
|
64
|
+
|
|
65
|
+
High values mean a long cached prefix is being rebuilt repeatedly --
|
|
66
|
+
the most common way an agent run costs more than it looks like it should.
|
|
67
|
+
"""
|
|
68
|
+
if self.total_usd <= 0:
|
|
69
|
+
return 0.0
|
|
70
|
+
spend = 0.0
|
|
71
|
+
for mc in self.by_model:
|
|
72
|
+
price = lookup(mc.model)
|
|
73
|
+
if price is None:
|
|
74
|
+
continue
|
|
75
|
+
spend += mc.usage.cache_write_1h_tokens / 1e6 * price.write_1h_rate()
|
|
76
|
+
return spend / self.total_usd
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _price_model(model: str, usage: Usage, calls: int) -> ModelCost:
|
|
80
|
+
price = lookup(model)
|
|
81
|
+
if price is None:
|
|
82
|
+
return ModelCost(model=model, usage=usage, calls=calls, priced=False)
|
|
83
|
+
return ModelCost(
|
|
84
|
+
model=model,
|
|
85
|
+
usage=usage,
|
|
86
|
+
calls=calls,
|
|
87
|
+
priced=True,
|
|
88
|
+
input_usd=usage.input_tokens / 1e6 * price.input,
|
|
89
|
+
output_usd=usage.output_tokens / 1e6 * price.output,
|
|
90
|
+
cache_read_usd=usage.cache_read_tokens / 1e6 * price.read_rate(),
|
|
91
|
+
cache_write_usd=(
|
|
92
|
+
usage.cache_write_5m_tokens / 1e6 * price.write_5m_rate()
|
|
93
|
+
+ usage.cache_write_1h_tokens / 1e6 * price.write_1h_rate()
|
|
94
|
+
),
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def event_usd(event: Event) -> float:
|
|
99
|
+
"""What one model turn cost. Zero for events that carry no usage."""
|
|
100
|
+
if event.usage.is_empty():
|
|
101
|
+
return 0.0
|
|
102
|
+
return _price_model(event.model or "unknown", event.usage, 1).total_usd
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def compute(events: list[Event]) -> CostReport:
|
|
106
|
+
per_model: dict[str, Usage] = {}
|
|
107
|
+
per_model_calls: dict[str, int] = {}
|
|
108
|
+
per_branch_usage: dict[str, Usage] = {}
|
|
109
|
+
per_branch_usd: dict[str, float] = {}
|
|
110
|
+
|
|
111
|
+
for ev in events:
|
|
112
|
+
if ev.usage.is_empty():
|
|
113
|
+
continue
|
|
114
|
+
model = ev.model or "unknown"
|
|
115
|
+
per_model[model] = per_model.get(model, Usage()) + ev.usage
|
|
116
|
+
per_model_calls[model] = per_model_calls.get(model, 0) + 1
|
|
117
|
+
|
|
118
|
+
branch = ev.branch or MAIN_BRANCH
|
|
119
|
+
per_branch_usage[branch] = per_branch_usage.get(branch, Usage()) + ev.usage
|
|
120
|
+
single = _price_model(model, ev.usage, 1)
|
|
121
|
+
per_branch_usd[branch] = per_branch_usd.get(branch, 0.0) + single.total_usd
|
|
122
|
+
|
|
123
|
+
by_model = [
|
|
124
|
+
_price_model(model, per_model[model], per_model_calls[model])
|
|
125
|
+
for model in sorted(per_model)
|
|
126
|
+
]
|
|
127
|
+
|
|
128
|
+
unpriced = [mc.model for mc in by_model if not mc.priced]
|
|
129
|
+
unpriced_tokens = sum(mc.usage.total_tokens for mc in by_model if not mc.priced)
|
|
130
|
+
|
|
131
|
+
return CostReport(
|
|
132
|
+
by_model=by_model,
|
|
133
|
+
by_branch=dict(sorted(per_branch_usd.items())),
|
|
134
|
+
tokens_by_branch=dict(sorted(per_branch_usage.items())),
|
|
135
|
+
total_usd=sum(mc.total_usd for mc in by_model),
|
|
136
|
+
unpriced_models=unpriced,
|
|
137
|
+
unpriced_tokens=unpriced_tokens,
|
|
138
|
+
)
|
blackbox/describe.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""Human-readable labels for events.
|
|
2
|
+
|
|
3
|
+
A finding whose evidence reads ``e9ffa5aa-1c18-477f-9b2f-40eda0d86718:tc0`` is
|
|
4
|
+
not actionable: nobody can tell what that was without grepping the raw trace.
|
|
5
|
+
The same finding showing ``step 412 · Bash: bun test`` can be acted on
|
|
6
|
+
immediately.
|
|
7
|
+
|
|
8
|
+
Labels are derived from stored event fields only, so they survive a replay and
|
|
9
|
+
never change the payload digest for a given input.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
from blackbox.events import (
|
|
18
|
+
ASSISTANT_MESSAGE,
|
|
19
|
+
META,
|
|
20
|
+
TOOL_CALL,
|
|
21
|
+
TOOL_RESULT,
|
|
22
|
+
USER_MESSAGE,
|
|
23
|
+
Event,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
# The argument worth showing, per tool, in preference order.
|
|
27
|
+
_HEADLINE_ARGS = (
|
|
28
|
+
"command",
|
|
29
|
+
"file_path",
|
|
30
|
+
"notebook_path",
|
|
31
|
+
"path",
|
|
32
|
+
"url",
|
|
33
|
+
"query",
|
|
34
|
+
"pattern",
|
|
35
|
+
"prompt",
|
|
36
|
+
"action",
|
|
37
|
+
"skill",
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
_MAX = 110
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _clean(value: Any, limit: int = _MAX) -> str:
|
|
44
|
+
text = " ".join(str(value).split())
|
|
45
|
+
return text if len(text) <= limit else text[: limit - 1] + "…"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def headline_arg(tool_input: dict[str, Any]) -> str:
|
|
49
|
+
"""The most informative single argument of a tool call."""
|
|
50
|
+
for key in _HEADLINE_ARGS:
|
|
51
|
+
value = tool_input.get(key)
|
|
52
|
+
if isinstance(value, (str, int, float)) and str(value).strip():
|
|
53
|
+
return _clean(value)
|
|
54
|
+
for key in sorted(tool_input):
|
|
55
|
+
value = tool_input[key]
|
|
56
|
+
if isinstance(value, (str, int, float)) and str(value).strip():
|
|
57
|
+
return _clean(value)
|
|
58
|
+
return ""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def describe(event: Event) -> str:
|
|
62
|
+
"""A one-line, human-readable summary of what an event was."""
|
|
63
|
+
if event.kind == TOOL_CALL:
|
|
64
|
+
name = event.tool_name or "tool"
|
|
65
|
+
# A call that touches several files is unreadable as raw input: show
|
|
66
|
+
# what it did to which files instead of the first 110 characters of a
|
|
67
|
+
# patch body.
|
|
68
|
+
operations = event.tool_input.get("files")
|
|
69
|
+
if isinstance(operations, list) and operations:
|
|
70
|
+
shown = ", ".join(
|
|
71
|
+
os.path.basename(str(entry.get("path", "?")))
|
|
72
|
+
for entry in operations[:3]
|
|
73
|
+
if isinstance(entry, dict)
|
|
74
|
+
)
|
|
75
|
+
extra = f" +{len(operations) - 3} more" if len(operations) > 3 else ""
|
|
76
|
+
return f"{name}: {len(operations)} file(s) — {shown}{extra}"
|
|
77
|
+
arg = headline_arg(event.tool_input)
|
|
78
|
+
return f"{name}: {arg}" if arg else name
|
|
79
|
+
|
|
80
|
+
if event.kind == TOOL_RESULT:
|
|
81
|
+
if "declined" in event.flags:
|
|
82
|
+
return "result: declined by the user"
|
|
83
|
+
if "interrupted" in event.flags:
|
|
84
|
+
return "result: interrupted"
|
|
85
|
+
first = next((line.strip() for line in event.tool_output.splitlines() if line.strip()), "")
|
|
86
|
+
prefix = "error" if event.tool_ok is False else "result"
|
|
87
|
+
return f"{prefix}: {_clean(first)}" if first else f"{prefix}: (empty)"
|
|
88
|
+
|
|
89
|
+
if event.kind == ASSISTANT_MESSAGE:
|
|
90
|
+
text = _clean(event.text, 90)
|
|
91
|
+
model = event.model or "assistant"
|
|
92
|
+
return f"{model}: {text}" if text else f"{model} turn"
|
|
93
|
+
|
|
94
|
+
if event.kind == USER_MESSAGE:
|
|
95
|
+
text = _clean(event.text, 90)
|
|
96
|
+
return f"user: {text}" if text else "user turn"
|
|
97
|
+
|
|
98
|
+
if event.kind == META:
|
|
99
|
+
return f"({event.raw_type})"
|
|
100
|
+
|
|
101
|
+
return event.kind
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def evidence_detail(event: Event, usd: float | None = None) -> dict[str, Any]:
|
|
105
|
+
"""Structured, renderable evidence for one event."""
|
|
106
|
+
detail: dict[str, Any] = {
|
|
107
|
+
"uid": event.uid,
|
|
108
|
+
"seq": event.seq,
|
|
109
|
+
"source_line": event.source_line,
|
|
110
|
+
"ts": event.ts.isoformat() if event.ts else None,
|
|
111
|
+
"tool": event.tool_name,
|
|
112
|
+
"summary": describe(event),
|
|
113
|
+
}
|
|
114
|
+
if usd is not None:
|
|
115
|
+
detail["usd"] = round(usd, 6)
|
|
116
|
+
return detail
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Detector registry.
|
|
2
|
+
|
|
3
|
+
Order here is irrelevant to the output: findings are sorted by severity and
|
|
4
|
+
then by a stable key, so adding a detector cannot reshuffle existing results.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from blackbox.detectors import (
|
|
10
|
+
context_bloat,
|
|
11
|
+
contradictions,
|
|
12
|
+
error_clusters,
|
|
13
|
+
retry_loops,
|
|
14
|
+
stalls,
|
|
15
|
+
thrash,
|
|
16
|
+
)
|
|
17
|
+
from blackbox.detectors.base import Config, Finding
|
|
18
|
+
from blackbox.graph import Graph
|
|
19
|
+
|
|
20
|
+
DETECTORS = (retry_loops, stalls, error_clusters, contradictions, thrash, context_bloat)
|
|
21
|
+
|
|
22
|
+
__all__ = ["Config", "Finding", "DETECTORS", "run_all"]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def run_all(graph: Graph, config: Config | None = None) -> list[Finding]:
|
|
26
|
+
"""Run every detector and return findings in a stable, severity-first order."""
|
|
27
|
+
config = config or Config()
|
|
28
|
+
findings: list[Finding] = []
|
|
29
|
+
for module in DETECTORS:
|
|
30
|
+
findings.extend(module.run(graph, config))
|
|
31
|
+
findings.sort(key=Finding.sort_key)
|
|
32
|
+
return findings
|