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
blackbox/bench.py ADDED
@@ -0,0 +1,466 @@
1
+ """Score the detectors against agent waste that someone else labelled.
2
+
3
+ The dataset released with *How Do AI Agents Waste Your Money?* (Zeng, Lu, Cai
4
+ et al., 2026; arXiv 2611.07238) marks, turn by turn, the spans of agent output
5
+ that could have been deleted, and names each one:
6
+
7
+ * ``duplicate-fetch`` -- a tool call that fetched what the agent already had.
8
+ * ``detour`` -- work that looked reasonable but the task did not need.
9
+ * ``restated`` -- prose repeating what is already in context.
10
+ * ``padding`` -- prose that does not advance the task (preambles, narration).
11
+ * ``unread`` -- output produced and never read.
12
+
13
+ The labels come from an LLM judge that read each whole trajectory. This module
14
+ asks a narrower question: of the turns Agent Black Box flags, with no model
15
+ and no network, how many did that judge also mark as waste, and how much of
16
+ the judge's waste do the flags reach?
17
+
18
+ How a flag becomes a turn, per detector:
19
+
20
+ * ``retry_loop`` -- every repeat *after the first* call in a cluster. The first
21
+ call was a reasonable thing to do; the repeats are the waste. Clusters the
22
+ tool itself calls polling or bookkeeping (``expected_repeat``) are not
23
+ claimed as waste, so they are not counted.
24
+ * ``thrash`` -- every write in a burst after the first.
25
+ * ``error_cluster`` -- every failed call in a cluster of the same failure.
26
+ * ``contradiction`` -- reported on its own line. It flags a stale or blind
27
+ view of a file, which is a correctness risk rather than a waste claim, so it
28
+ is left out of the combined "waste detectors" row.
29
+ * ``stall`` and ``context_bloat`` cannot fire on this data at all: it has no
30
+ timestamps and no input-token counts. They are listed as such, not scored.
31
+
32
+ The combined row uses the same three detectors :class:`blackbox.analysis.Analysis`
33
+ already treats as waste when it attributes cost, so the benchmark scores the
34
+ claim the tool makes rather than one invented for the occasion.
35
+
36
+ Everything here is a pure function of the files read: the scores, the counts
37
+ and their digest are identical on every run. Wall-clock time is reported
38
+ separately and kept out of the digest.
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import hashlib
44
+ import json
45
+ import os
46
+ import time
47
+ from collections import defaultdict
48
+ from dataclasses import dataclass, field, replace
49
+ from typing import Any, Iterable
50
+
51
+ from blackbox import detectors as detectors_mod
52
+ from blackbox import graph as graph_mod
53
+ from blackbox.adapters import labelled_turns
54
+ from blackbox.detectors.base import Config, Finding
55
+ from blackbox.events import TOOL_CALL, TOOL_RESULT
56
+
57
+ KINDS = ("duplicate-fetch", "detour", "restated", "padding", "unread")
58
+ #: The paper's "strict waste": wasted however the task went.
59
+ STRICT_KINDS = ("duplicate-fetch", "restated", "padding", "unread")
60
+ WASTE_DETECTORS = ("retry_loop", "thrash", "error_cluster")
61
+ SCORED_DETECTORS = ("retry_loop", "thrash", "error_cluster", "contradiction")
62
+ INERT_DETECTORS = {
63
+ "stall": "needs timestamps; this data has none",
64
+ "context_bloat": "needs input-token counts; this data records output tokens only",
65
+ }
66
+ COMBINED = "waste detectors (combined)"
67
+
68
+ README_START = "<!-- bench:start -->"
69
+ README_END = "<!-- bench:end -->"
70
+
71
+
72
+ # --- labels -------------------------------------------------------------------
73
+
74
+
75
+ @dataclass
76
+ class TurnLabels:
77
+ """What the judge said about one turn."""
78
+
79
+ round: int
80
+ judged: bool
81
+ #: kind -> characters of verified span text, across every stream.
82
+ chars: dict[str, int] = field(default_factory=dict)
83
+ #: The same, for spans in the ``action`` stream only (the tool calls).
84
+ action_chars: dict[str, int] = field(default_factory=dict)
85
+
86
+ @property
87
+ def wasteful(self) -> bool:
88
+ return bool(self.chars)
89
+
90
+ @property
91
+ def action_wasteful(self) -> bool:
92
+ return bool(self.action_chars)
93
+
94
+
95
+ def turn_labels(rnd: int, turn: dict[str, Any]) -> TurnLabels:
96
+ """The judge's verdict on a turn, reduced to characters per kind.
97
+
98
+ Only verified spans count -- a quote the dataset's authors could not find
99
+ in the text it claims to quote is a judge error, and counting it would
100
+ score the detectors against a fabrication. A turn with no efficiency
101
+ verdict was not judged and is left out of every denominator.
102
+ """
103
+ labels = turn.get("labels")
104
+ efficiency = labels.get("efficiency") if isinstance(labels, dict) else None
105
+ if not isinstance(efficiency, dict) or not efficiency:
106
+ return TurnLabels(round=rnd, judged=False)
107
+ chars: dict[str, int] = defaultdict(int)
108
+ action_chars: dict[str, int] = defaultdict(int)
109
+ for stream in sorted(efficiency):
110
+ verdict = efficiency[stream]
111
+ if not isinstance(verdict, dict) or verdict.get("error"):
112
+ continue
113
+ for span in verdict.get("spans") or ():
114
+ if not isinstance(span, dict) or span.get("verified", True) is False:
115
+ continue
116
+ kind = str(span.get("kind") or "")
117
+ quote = span.get("quote")
118
+ length = len(quote) if isinstance(quote, str) else 0
119
+ if not kind or length == 0:
120
+ continue
121
+ chars[kind] += length
122
+ if stream == "action":
123
+ action_chars[kind] += length
124
+ return TurnLabels(round=rnd, judged=True, chars=dict(chars),
125
+ action_chars=dict(action_chars))
126
+
127
+
128
+ # --- flags --------------------------------------------------------------------
129
+
130
+
131
+ def flagged_rounds(findings: Iterable[Finding], graph: graph_mod.Graph) -> dict[str, set[int]]:
132
+ """detector -> the rounds it marks as wasted work."""
133
+ flagged: dict[str, set[int]] = {name: set() for name in SCORED_DETECTORS}
134
+ for finding in findings:
135
+ if finding.detector not in flagged:
136
+ continue
137
+ evidence = list(finding.evidence)
138
+ if finding.detector == "retry_loop":
139
+ if finding.metrics.get("kind") == "expected_repeat":
140
+ continue
141
+ evidence = evidence[1:]
142
+ elif finding.detector == "thrash":
143
+ evidence = evidence[1:]
144
+ for uid in evidence:
145
+ event = graph.by_uid.get(uid)
146
+ if event is not None and event.kind == TOOL_RESULT and event.parent_uid:
147
+ uid = event.parent_uid
148
+ rnd = labelled_turns.round_of_uid(uid)
149
+ if rnd is not None:
150
+ flagged[finding.detector].add(rnd)
151
+ flagged[COMBINED] = set().union(*(flagged[name] for name in WASTE_DETECTORS))
152
+ return flagged
153
+
154
+
155
+ # --- tallies ------------------------------------------------------------------
156
+
157
+
158
+ @dataclass
159
+ class Tally:
160
+ """Counts for one detector (or the combined row) over many turns."""
161
+
162
+ flagged: int = 0
163
+ flagged_wasteful: int = 0
164
+ flagged_action_wasteful: int = 0
165
+ flagged_unjudged: int = 0
166
+ hit_turns: dict[str, int] = field(default_factory=lambda: defaultdict(int))
167
+ hit_chars: dict[str, int] = field(default_factory=lambda: defaultdict(int))
168
+ hit_action_chars: int = 0
169
+ hit_all_chars: int = 0
170
+
171
+ def add(self, labels: TurnLabels) -> None:
172
+ if not labels.judged:
173
+ self.flagged_unjudged += 1
174
+ return
175
+ self.flagged += 1
176
+ self.flagged_wasteful += labels.wasteful
177
+ self.flagged_action_wasteful += labels.action_wasteful
178
+ for kind, n in labels.chars.items():
179
+ self.hit_turns[kind] += 1
180
+ self.hit_chars[kind] += n
181
+ self.hit_all_chars += n
182
+ self.hit_action_chars += sum(labels.action_chars.values())
183
+
184
+
185
+ @dataclass
186
+ class Totals:
187
+ """What the judge labelled, over every judged turn."""
188
+
189
+ trajectories: int = 0
190
+ turns: int = 0
191
+ judged_turns: int = 0
192
+ wasteful_turns: int = 0
193
+ action_wasteful_turns: int = 0
194
+ kind_turns: dict[str, int] = field(default_factory=lambda: defaultdict(int))
195
+ kind_chars: dict[str, int] = field(default_factory=lambda: defaultdict(int))
196
+ action_chars: int = 0
197
+ all_chars: int = 0
198
+ tool_calls: int = 0
199
+
200
+ def add(self, labels: TurnLabels) -> None:
201
+ self.turns += 1
202
+ if not labels.judged:
203
+ return
204
+ self.judged_turns += 1
205
+ self.wasteful_turns += labels.wasteful
206
+ self.action_wasteful_turns += labels.action_wasteful
207
+ for kind, n in labels.chars.items():
208
+ self.kind_turns[kind] += 1
209
+ self.kind_chars[kind] += n
210
+ self.all_chars += n
211
+ self.action_chars += sum(labels.action_chars.values())
212
+
213
+
214
+ def _share(part: int, whole: int) -> float | None:
215
+ return round(part / whole, 4) if whole else None
216
+
217
+
218
+ def _row(tally: Tally, totals: Totals) -> dict[str, Any]:
219
+ base = _share(totals.wasteful_turns, totals.judged_turns)
220
+ precision = _share(tally.flagged_wasteful, tally.flagged)
221
+ return {
222
+ "flagged_turns": tally.flagged,
223
+ "flagged_unjudged_turns": tally.flagged_unjudged,
224
+ "precision": precision,
225
+ "precision_action_stream": _share(tally.flagged_action_wasteful, tally.flagged),
226
+ "lift_over_random": round(precision / base, 2) if precision is not None and base else None,
227
+ "recall_turns": {
228
+ kind: _share(tally.hit_turns.get(kind, 0), totals.kind_turns.get(kind, 0))
229
+ for kind in KINDS
230
+ },
231
+ "recall_chars": {
232
+ kind: _share(tally.hit_chars.get(kind, 0), totals.kind_chars.get(kind, 0))
233
+ for kind in KINDS
234
+ },
235
+ "share_of_all_waste_chars": _share(tally.hit_all_chars, totals.all_chars),
236
+ "share_of_action_waste_chars": _share(tally.hit_action_chars, totals.action_chars),
237
+ }
238
+
239
+
240
+ def _totals_dict(totals: Totals) -> dict[str, Any]:
241
+ return {
242
+ "trajectories": totals.trajectories,
243
+ "turns": totals.turns,
244
+ "judged_turns": totals.judged_turns,
245
+ "tool_calls": totals.tool_calls,
246
+ "wasteful_turns": totals.wasteful_turns,
247
+ "wasteful_turn_rate": _share(totals.wasteful_turns, totals.judged_turns),
248
+ "action_wasteful_turns": totals.action_wasteful_turns,
249
+ "kind_turns": {k: totals.kind_turns.get(k, 0) for k in KINDS},
250
+ "kind_chars": {k: totals.kind_chars.get(k, 0) for k in KINDS},
251
+ "other_kinds": sorted(k for k in totals.kind_chars if k not in KINDS),
252
+ }
253
+
254
+
255
+ # --- the run ------------------------------------------------------------------
256
+
257
+
258
+ VARIANTS = {
259
+ # The tool as shipped.
260
+ "default": {},
261
+ # The dataset's duplicate-fetch needs only one repeat; the shipped retry
262
+ # detector waits for two. This variant shows what that threshold costs.
263
+ "two_repeats": {"retry_min_repeats": 2},
264
+ }
265
+
266
+
267
+ def jsonl_files(paths: Iterable[str]) -> list[str]:
268
+ """Every ``.jsonl`` file under the given paths, in a stable order."""
269
+ found: list[str] = []
270
+ for path in paths:
271
+ if os.path.isdir(path):
272
+ for root, dirs, files in os.walk(path):
273
+ dirs.sort()
274
+ found.extend(os.path.join(root, f) for f in sorted(files) if f.endswith(".jsonl"))
275
+ elif os.path.isfile(path):
276
+ found.append(path)
277
+ return sorted(dict.fromkeys(found))
278
+
279
+
280
+ def _group_of(record: dict[str, Any]) -> str:
281
+ bench = str(record.get("benchmark") or "?")
282
+ domain = record.get("domain")
283
+ if domain and domain not in ("all", bench):
284
+ return f"{bench}-{domain}"
285
+ return bench
286
+
287
+
288
+ def run(paths: Iterable[str], config: Config | None = None, limit: int | None = None) -> dict[str, Any]:
289
+ """Score every trajectory under ``paths``. Returns the results payload."""
290
+ base_config = config or Config()
291
+ configs = {name: replace(base_config, **change) for name, change in VARIANTS.items()}
292
+ files = jsonl_files(paths)
293
+ started = time.perf_counter()
294
+
295
+ totals = Totals()
296
+ group_totals: dict[str, Totals] = defaultdict(Totals)
297
+ tallies = {v: defaultdict(Tally) for v in configs}
298
+ group_tallies = {v: defaultdict(Tally) for v in configs}
299
+ unreadable = 0
300
+ seen = 0
301
+
302
+ for path in files:
303
+ for _, record in labelled_turns.iter_records(path):
304
+ if limit is not None and seen >= limit:
305
+ break
306
+ if record is None:
307
+ unreadable += 1
308
+ continue
309
+ seen += 1
310
+ group = _group_of(record)
311
+ trace = labelled_turns.parse_record(record)
312
+ graph = graph_mod.build(trace.events)
313
+ labels = {rnd: turn_labels(rnd, turn) for rnd, turn in labelled_turns.ordered_turns(record)}
314
+
315
+ totals.trajectories += 1
316
+ group_totals[group].trajectories += 1
317
+ calls = sum(1 for e in graph.events if e.kind == TOOL_CALL)
318
+ totals.tool_calls += calls
319
+ group_totals[group].tool_calls += calls
320
+ for turn in labels.values():
321
+ totals.add(turn)
322
+ group_totals[group].add(turn)
323
+
324
+ for variant, cfg in configs.items():
325
+ flagged = flagged_rounds(detectors_mod.run_all(graph, cfg), graph)
326
+ for detector, rounds in flagged.items():
327
+ for rnd in sorted(rounds):
328
+ turn = labels.get(rnd)
329
+ if turn is None:
330
+ continue
331
+ tallies[variant][detector].add(turn)
332
+ if detector == COMBINED:
333
+ group_tallies[variant][group].add(turn)
334
+ if limit is not None and seen >= limit:
335
+ break
336
+
337
+ elapsed = time.perf_counter() - started
338
+ rows = list(SCORED_DETECTORS) + [COMBINED]
339
+ results = {
340
+ "dataset": {
341
+ "name": "How Do AI Agents Waste Your Money? (labelled trajectories)",
342
+ "source": "huggingface.co/datasets/huiminz3/How_Do_AI_Agents_Waste_Your_Money",
343
+ "paper": "arXiv:2611.07238",
344
+ "license": "CC BY 4.0",
345
+ "files": len(files),
346
+ "unreadable_lines": unreadable,
347
+ },
348
+ "totals": _totals_dict(totals),
349
+ "config": base_config.to_dict(),
350
+ "variants": {
351
+ variant: {
352
+ "config_changes": VARIANTS[variant],
353
+ "detectors": {name: _row(tallies[variant][name], totals) for name in rows},
354
+ "by_group": {
355
+ group: {
356
+ "totals": _totals_dict(group_totals[group]),
357
+ "combined": _row(group_tallies[variant][group], group_totals[group]),
358
+ }
359
+ for group in sorted(group_totals)
360
+ },
361
+ }
362
+ for variant in configs
363
+ },
364
+ "inert_detectors": INERT_DETECTORS,
365
+ "model_calls": 0,
366
+ }
367
+ results["digest"] = digest(results)
368
+ results["run"] = {
369
+ "seconds": round(elapsed, 2),
370
+ "trajectories_per_second": round(totals.trajectories / elapsed, 1) if elapsed else None,
371
+ }
372
+ return results
373
+
374
+
375
+ def digest(results: dict[str, Any]) -> str:
376
+ """Hash of everything except the clock, so two runs can be compared."""
377
+ stable = {k: v for k, v in results.items() if k not in ("digest", "run")}
378
+ blob = json.dumps(stable, sort_keys=True, separators=(",", ":"))
379
+ return hashlib.sha256(blob.encode("utf-8")).hexdigest()
380
+
381
+
382
+ # --- rendering ----------------------------------------------------------------
383
+
384
+
385
+ def _pct(value: float | None) -> str:
386
+ return "n/a" if value is None else f"{value * 100:.1f}%"
387
+
388
+
389
+ def headline(results: dict[str, Any], variant: str = "default") -> str:
390
+ totals = results["totals"]
391
+ row = results["variants"][variant]["detectors"][COMBINED]
392
+ seconds = results.get("run", {}).get("seconds")
393
+ if seconds is None:
394
+ timing = ""
395
+ elif seconds < 1:
396
+ timing = " in under a second"
397
+ else:
398
+ timing = f" in {seconds:g} seconds"
399
+ lift = row["lift_over_random"]
400
+ lift_text = f", {lift:g}x the rate for a turn picked at random" if lift else ""
401
+ return (
402
+ f"On {totals['trajectories']:,} labelled trajectories ({totals['judged_turns']:,} judged turns), "
403
+ f"Agent Black Box flagged {row['flagged_turns']:,} turns as wasted work{timing}, "
404
+ f"with no model calls. {_pct(row['precision'])} of them were also marked as waste "
405
+ f"by the paper's judge (against {_pct(totals['wasteful_turn_rate'])} of all turns"
406
+ f"{lift_text}). They reached "
407
+ f"{_pct(row['recall_turns']['duplicate-fetch'])} of the turns labelled duplicate-fetch "
408
+ f"and {_pct(row['recall_turns']['detour'])} of those labelled detour."
409
+ )
410
+
411
+
412
+ def markdown(results: dict[str, Any]) -> str:
413
+ """The README section, regenerated from a results payload."""
414
+ totals = results["totals"]
415
+ lines = [headline(results), ""]
416
+ lines.append(
417
+ "| detector | settings | turns flagged | also judged waste | lift | "
418
+ "duplicate-fetch found | detour found | restated found | padding found |"
419
+ )
420
+ lines.append("|---|---|---:|---:|---:|---:|---:|---:|---:|")
421
+ for variant, block in results["variants"].items():
422
+ label = "shipped" if variant == "default" else "retry at 2 repeats"
423
+ for name, row in block["detectors"].items():
424
+ if variant != "default" and name not in ("retry_loop", COMBINED):
425
+ continue
426
+ lift = "n/a" if row["lift_over_random"] is None else f"{row['lift_over_random']:g}x"
427
+ rt = row["recall_turns"]
428
+ lines.append(
429
+ f"| {name} | {label} | {row['flagged_turns']:,} | {_pct(row['precision'])} | {lift} | "
430
+ f"{_pct(rt['duplicate-fetch'])} | {_pct(rt['detour'])} | "
431
+ f"{_pct(rt['restated'])} | {_pct(rt['padding'])} |"
432
+ )
433
+ lines.append("")
434
+ lines.append(
435
+ f"Judged turns: {totals['judged_turns']:,}. Turns with any labelled waste: "
436
+ f"{totals['wasteful_turns']:,} ({_pct(totals['wasteful_turn_rate'])}). "
437
+ "Labelled turns per kind: "
438
+ + ", ".join(f"{k} {totals['kind_turns'][k]:,}" for k in KINDS)
439
+ + "."
440
+ )
441
+ by_group = results["variants"]["default"]["by_group"]
442
+ if by_group:
443
+ lines += ["", "| benchmark | trajectories | turns flagged | also judged waste | detour found |",
444
+ "|---|---:|---:|---:|---:|"]
445
+ for group, block in by_group.items():
446
+ row = block["combined"]
447
+ lines.append(
448
+ f"| {group} | {block['totals']['trajectories']:,} | {row['flagged_turns']:,} | "
449
+ f"{_pct(row['precision'])} | {_pct(row['recall_turns']['detour'])} |"
450
+ )
451
+ run_info = results.get("run", {})
452
+ lines += [
453
+ "",
454
+ f"Model calls: {results['model_calls']}. Wall time: {run_info.get('seconds', 'n/a')} s "
455
+ f"on one CPU core. Results digest: `{results['digest'][:16]}`.",
456
+ ]
457
+ return "\n".join(lines) + "\n"
458
+
459
+
460
+ def update_readme(readme: str, section: str) -> str:
461
+ """Replace the text between the benchmark markers with ``section``."""
462
+ start = readme.find(README_START)
463
+ end = readme.find(README_END)
464
+ if start == -1 or end == -1 or end < start:
465
+ raise ValueError(f"README has no {README_START} ... {README_END} block")
466
+ return readme[: start + len(README_START)] + "\n" + section + readme[end:]