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/guard_cli.py
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
"""``blackbox guard``: install, run and replay the live guardrail.
|
|
2
|
+
|
|
3
|
+
blackbox guard install # add the hook to .claude/settings.json
|
|
4
|
+
blackbox guard install --scope local
|
|
5
|
+
blackbox guard uninstall
|
|
6
|
+
blackbox guard replay run.jsonl # what it would have done on a finished run
|
|
7
|
+
blackbox guard hook # what Claude Code runs (reads stdin)
|
|
8
|
+
|
|
9
|
+
Nothing is written anywhere unless you run ``install``, and ``install
|
|
10
|
+
--dry-run`` shows the change without making it.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import argparse
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import shutil
|
|
19
|
+
import sys
|
|
20
|
+
from typing import Any
|
|
21
|
+
|
|
22
|
+
from blackbox import guard
|
|
23
|
+
from blackbox.detectors.base import Config
|
|
24
|
+
|
|
25
|
+
# Any hook command containing this is ours; install replaces it and
|
|
26
|
+
# uninstall removes it, without touching anyone else's hooks.
|
|
27
|
+
COMMAND_SIGNATURE = "blackbox guard hook"
|
|
28
|
+
EVENTS = ("PreToolUse", "PostToolUse")
|
|
29
|
+
SEVERITIES = ("high", "medium", "low", "never")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _add_policy_flags(parser: argparse.ArgumentParser) -> None:
|
|
33
|
+
parser.add_argument(
|
|
34
|
+
"--warn-at",
|
|
35
|
+
choices=SEVERITIES,
|
|
36
|
+
default=guard.Policy.warn_at,
|
|
37
|
+
help="severity at which the agent is told (default medium)",
|
|
38
|
+
)
|
|
39
|
+
parser.add_argument(
|
|
40
|
+
"--block-at",
|
|
41
|
+
choices=SEVERITIES,
|
|
42
|
+
default=guard.Policy.block_at,
|
|
43
|
+
help="severity at which the call is denied (default high; 'never' only warns)",
|
|
44
|
+
)
|
|
45
|
+
parser.add_argument("--retry-min-repeats", type=int, default=Config.retry_min_repeats)
|
|
46
|
+
parser.add_argument("--retry-window", type=int, default=Config.retry_window)
|
|
47
|
+
parser.add_argument("--thrash-min-edits", type=int, default=Config.thrash_min_edits)
|
|
48
|
+
parser.add_argument("--thrash-window", type=int, default=Config.thrash_window)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _config(args: argparse.Namespace) -> Config:
|
|
52
|
+
return Config(
|
|
53
|
+
retry_min_repeats=args.retry_min_repeats,
|
|
54
|
+
retry_window=args.retry_window,
|
|
55
|
+
thrash_min_edits=args.thrash_min_edits,
|
|
56
|
+
thrash_window=args.thrash_window,
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _policy(args: argparse.Namespace) -> guard.Policy:
|
|
61
|
+
return guard.Policy(warn_at=args.warn_at, block_at=args.block_at)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _policy_argv(args: argparse.Namespace) -> list[str]:
|
|
65
|
+
"""Flags to bake into the installed command: only the non-defaults."""
|
|
66
|
+
defaults = {
|
|
67
|
+
"warn_at": guard.Policy.warn_at,
|
|
68
|
+
"block_at": guard.Policy.block_at,
|
|
69
|
+
"retry_min_repeats": Config.retry_min_repeats,
|
|
70
|
+
"retry_window": Config.retry_window,
|
|
71
|
+
"thrash_min_edits": Config.thrash_min_edits,
|
|
72
|
+
"thrash_window": Config.thrash_window,
|
|
73
|
+
}
|
|
74
|
+
out: list[str] = []
|
|
75
|
+
for name, default in defaults.items():
|
|
76
|
+
value = getattr(args, name)
|
|
77
|
+
if value != default:
|
|
78
|
+
out += [f"--{name.replace('_', '-')}", str(value)]
|
|
79
|
+
return out
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
83
|
+
parser = argparse.ArgumentParser(
|
|
84
|
+
prog="blackbox guard",
|
|
85
|
+
description=(
|
|
86
|
+
"Stop retry loops and file thrash while a Claude Code agent is running. "
|
|
87
|
+
"Same detectors as the report, run as a hook. Offline, no model calls."
|
|
88
|
+
),
|
|
89
|
+
)
|
|
90
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
91
|
+
|
|
92
|
+
hook = sub.add_parser("hook", help="run as a Claude Code hook (reads the event on stdin)")
|
|
93
|
+
_add_policy_flags(hook)
|
|
94
|
+
|
|
95
|
+
install = sub.add_parser("install", help="add the hook to a Claude Code settings file")
|
|
96
|
+
_add_policy_flags(install)
|
|
97
|
+
install.add_argument(
|
|
98
|
+
"--scope",
|
|
99
|
+
choices=("project", "local", "user"),
|
|
100
|
+
default="project",
|
|
101
|
+
help=(
|
|
102
|
+
"project: .claude/settings.json (shared through git); "
|
|
103
|
+
"local: .claude/settings.local.json (just you); "
|
|
104
|
+
"user: ~/.claude/settings.json (every project)"
|
|
105
|
+
),
|
|
106
|
+
)
|
|
107
|
+
install.add_argument("--dir", default=".", help="project directory (default: here)")
|
|
108
|
+
install.add_argument("--dry-run", action="store_true", help="print the result, write nothing")
|
|
109
|
+
|
|
110
|
+
uninstall = sub.add_parser("uninstall", help="remove the hook from a settings file")
|
|
111
|
+
uninstall.add_argument("--scope", choices=("project", "local", "user"), default="project")
|
|
112
|
+
uninstall.add_argument("--dir", default=".")
|
|
113
|
+
|
|
114
|
+
rep = sub.add_parser("replay", help="show what the guard would have done on a finished run")
|
|
115
|
+
rep.add_argument("trace", help="a Claude Code or Codex trace file")
|
|
116
|
+
_add_policy_flags(rep)
|
|
117
|
+
return parser
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def main(argv: list[str] | None = None) -> int:
|
|
121
|
+
args = build_parser().parse_args(argv)
|
|
122
|
+
if args.command == "hook":
|
|
123
|
+
out = guard.run_hook(sys.stdin.read(), config=_config(args), policy=_policy(args))
|
|
124
|
+
if out:
|
|
125
|
+
sys.stdout.write(out + "\n")
|
|
126
|
+
return 0
|
|
127
|
+
if args.command == "install":
|
|
128
|
+
return _install(args)
|
|
129
|
+
if args.command == "uninstall":
|
|
130
|
+
return _uninstall(args)
|
|
131
|
+
if args.command == "replay":
|
|
132
|
+
return _replay(args)
|
|
133
|
+
return 2
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
# --- settings files ----------------------------------------------------------
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def settings_path(scope: str, directory: str = ".") -> str:
|
|
140
|
+
if scope == "user":
|
|
141
|
+
return os.path.join(os.path.expanduser("~"), ".claude", "settings.json")
|
|
142
|
+
name = "settings.local.json" if scope == "local" else "settings.json"
|
|
143
|
+
return os.path.join(os.path.abspath(directory), ".claude", name)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def hook_command(extra: list[str] | None = None) -> str:
|
|
147
|
+
"""The command Claude Code will run.
|
|
148
|
+
|
|
149
|
+
``blackbox`` when it is on PATH, which is what a shared settings file
|
|
150
|
+
wants. Otherwise this interpreter, so an install made with ``uvx`` or
|
|
151
|
+
from a virtualenv still points at something that exists.
|
|
152
|
+
"""
|
|
153
|
+
base = "blackbox" if shutil.which("blackbox") else f'"{sys.executable}" -m blackbox'
|
|
154
|
+
return " ".join([base, "guard", "hook", *(extra or [])])
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _is_ours(handler: Any) -> bool:
|
|
158
|
+
return isinstance(handler, dict) and COMMAND_SIGNATURE in str(handler.get("command", ""))
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _without_ours(groups: Any) -> list[Any]:
|
|
162
|
+
"""Drop our handlers from a list of matcher groups, keeping everyone else's."""
|
|
163
|
+
kept = []
|
|
164
|
+
for group in groups if isinstance(groups, list) else []:
|
|
165
|
+
if not isinstance(group, dict):
|
|
166
|
+
kept.append(group)
|
|
167
|
+
continue
|
|
168
|
+
handlers = group.get("hooks")
|
|
169
|
+
if not isinstance(handlers, list):
|
|
170
|
+
kept.append(group)
|
|
171
|
+
continue
|
|
172
|
+
remaining = [h for h in handlers if not _is_ours(h)]
|
|
173
|
+
if remaining:
|
|
174
|
+
kept.append({**group, "hooks": remaining})
|
|
175
|
+
elif not any(_is_ours(h) for h in handlers):
|
|
176
|
+
kept.append(group)
|
|
177
|
+
return kept
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def install_into(settings: dict[str, Any], command: str) -> dict[str, Any]:
|
|
181
|
+
"""Return ``settings`` with the guard registered once on both events."""
|
|
182
|
+
out = dict(settings)
|
|
183
|
+
hooks = dict(out.get("hooks") or {})
|
|
184
|
+
for event in EVENTS:
|
|
185
|
+
groups = _without_ours(hooks.get(event))
|
|
186
|
+
groups.append(
|
|
187
|
+
{"matcher": "*", "hooks": [{"type": "command", "command": command, "timeout": 10}]}
|
|
188
|
+
)
|
|
189
|
+
hooks[event] = groups
|
|
190
|
+
out["hooks"] = hooks
|
|
191
|
+
return out
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def uninstall_from(settings: dict[str, Any]) -> dict[str, Any]:
|
|
195
|
+
out = dict(settings)
|
|
196
|
+
hooks = dict(out.get("hooks") or {})
|
|
197
|
+
for event in list(hooks):
|
|
198
|
+
groups = _without_ours(hooks[event])
|
|
199
|
+
if groups:
|
|
200
|
+
hooks[event] = groups
|
|
201
|
+
else:
|
|
202
|
+
del hooks[event]
|
|
203
|
+
if hooks:
|
|
204
|
+
out["hooks"] = hooks
|
|
205
|
+
else:
|
|
206
|
+
out.pop("hooks", None)
|
|
207
|
+
return out
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _read_settings(path: str) -> dict[str, Any] | None:
|
|
211
|
+
if not os.path.exists(path):
|
|
212
|
+
return {}
|
|
213
|
+
try:
|
|
214
|
+
with open(path, "r", encoding="utf-8") as fh:
|
|
215
|
+
data = json.load(fh)
|
|
216
|
+
except (OSError, json.JSONDecodeError) as exc:
|
|
217
|
+
print(f"error: could not read {path}: {exc}", file=sys.stderr)
|
|
218
|
+
return None
|
|
219
|
+
if not isinstance(data, dict):
|
|
220
|
+
print(f"error: {path} is not a JSON object", file=sys.stderr)
|
|
221
|
+
return None
|
|
222
|
+
return data
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _write_settings(path: str, data: dict[str, Any]) -> None:
|
|
226
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
227
|
+
with open(path, "w", encoding="utf-8") as fh:
|
|
228
|
+
json.dump(data, fh, indent=2)
|
|
229
|
+
fh.write("\n")
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _install(args: argparse.Namespace) -> int:
|
|
233
|
+
path = settings_path(args.scope, args.dir)
|
|
234
|
+
current = _read_settings(path)
|
|
235
|
+
if current is None:
|
|
236
|
+
return 1
|
|
237
|
+
command = hook_command(_policy_argv(args))
|
|
238
|
+
updated = install_into(current, command)
|
|
239
|
+
if args.dry_run:
|
|
240
|
+
print(f"would write {path}:")
|
|
241
|
+
print(json.dumps(updated, indent=2))
|
|
242
|
+
return 0
|
|
243
|
+
_write_settings(path, updated)
|
|
244
|
+
print(f"guard installed in {path}")
|
|
245
|
+
print(f" command {command}")
|
|
246
|
+
print(
|
|
247
|
+
f" warns at {args.warn_at}, blocks at {args.block_at}. "
|
|
248
|
+
"Takes effect in new Claude Code sessions."
|
|
249
|
+
)
|
|
250
|
+
print(" turn it off for one session with BLACKBOX_GUARD=off, or run 'blackbox guard uninstall'")
|
|
251
|
+
if args.scope == "project" and not command.startswith("blackbox "):
|
|
252
|
+
print(
|
|
253
|
+
" note: 'blackbox' is not on PATH, so the command names this machine's Python.\n"
|
|
254
|
+
" .claude/settings.json is shared through git; consider --scope local."
|
|
255
|
+
)
|
|
256
|
+
return 0
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _uninstall(args: argparse.Namespace) -> int:
|
|
260
|
+
path = settings_path(args.scope, args.dir)
|
|
261
|
+
if not os.path.exists(path):
|
|
262
|
+
print(f"nothing to do: {path} does not exist")
|
|
263
|
+
return 0
|
|
264
|
+
current = _read_settings(path)
|
|
265
|
+
if current is None:
|
|
266
|
+
return 1
|
|
267
|
+
updated = uninstall_from(current)
|
|
268
|
+
if updated == current:
|
|
269
|
+
print(f"nothing to do: the guard is not in {path}")
|
|
270
|
+
return 0
|
|
271
|
+
_write_settings(path, updated)
|
|
272
|
+
print(f"guard removed from {path}")
|
|
273
|
+
return 0
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
# --- replay --------------------------------------------------------------------
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _replay(args: argparse.Namespace) -> int:
|
|
280
|
+
from blackbox.adapters.registry import NoAdapterError
|
|
281
|
+
|
|
282
|
+
if not os.path.exists(args.trace):
|
|
283
|
+
print(f"error: no such file: {args.trace}", file=sys.stderr)
|
|
284
|
+
return 1
|
|
285
|
+
try:
|
|
286
|
+
result = guard.replay(args.trace, config=_config(args), policy=_policy(args))
|
|
287
|
+
except NoAdapterError as exc:
|
|
288
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
289
|
+
return 1
|
|
290
|
+
print(render_replay(result, _policy(args)))
|
|
291
|
+
return 0
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def render_replay(result: guard.ReplayResult, policy: guard.Policy) -> str:
|
|
295
|
+
lines = [
|
|
296
|
+
f"AGENT BLACK BOX guard replay of {os.path.basename(result.source)}",
|
|
297
|
+
f" {result.tool_calls} tool calls · ${result.total_usd:.2f} run cost · "
|
|
298
|
+
f"warns at {policy.warn_at}, blocks at {policy.block_at}",
|
|
299
|
+
"",
|
|
300
|
+
]
|
|
301
|
+
if not result.interventions:
|
|
302
|
+
lines.append(" the guard would have stayed quiet on this run")
|
|
303
|
+
return "\n".join(lines)
|
|
304
|
+
|
|
305
|
+
for item in result.interventions:
|
|
306
|
+
d = item.decision
|
|
307
|
+
label = "BLOCK" if d.action == guard.BLOCK else "warn "
|
|
308
|
+
if d.detector == "thrash":
|
|
309
|
+
what = f"{_ordinal(d.count)} write in {d.span} calls {d.subject}"
|
|
310
|
+
else:
|
|
311
|
+
what = f"{_ordinal(d.count)} identical call {d.subject}"
|
|
312
|
+
spent = f" ${d.usd:.2f} so far" if d.usd >= 0.01 else ""
|
|
313
|
+
lines.append(f" line {item.call.source_line:<5} {label} {d.detector:<10} {_cut(what, 70)}{spent}")
|
|
314
|
+
|
|
315
|
+
first_block = next((i for i in result.interventions if i.decision.action == guard.BLOCK), None)
|
|
316
|
+
if first_block is not None:
|
|
317
|
+
lines += ["", " what the agent would have read instead of running that call:", ""]
|
|
318
|
+
lines += [" " + chunk for chunk in _wrap(first_block.decision.message, 74)]
|
|
319
|
+
|
|
320
|
+
lines += [
|
|
321
|
+
"",
|
|
322
|
+
f" {result.blocks} block(s), {result.warnings} warning(s)",
|
|
323
|
+
f" the calls it would have blocked were issued by turns costing ${result.blocked_usd:.2f};",
|
|
324
|
+
f" turns that kept a streak going after the guard first spoke cost ${result.after_first_word_usd:.2f}",
|
|
325
|
+
" (what the agent would have done instead is unknown, so these are what the",
|
|
326
|
+
" guard stood in front of, not a promised saving)",
|
|
327
|
+
]
|
|
328
|
+
return "\n".join(lines)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _ordinal(n: int) -> str:
|
|
332
|
+
return guard._ordinal(n)
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _cut(text: str, limit: int) -> str:
|
|
336
|
+
return text if len(text) <= limit else text[: limit - 1] + "…"
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _wrap(text: str, width: int) -> list[str]:
|
|
340
|
+
words, lines, current = text.split(), [], ""
|
|
341
|
+
for word in words:
|
|
342
|
+
if current and len(current) + 1 + len(word) > width:
|
|
343
|
+
lines.append(current)
|
|
344
|
+
current = word
|
|
345
|
+
else:
|
|
346
|
+
current = f"{current} {word}".strip()
|
|
347
|
+
if current:
|
|
348
|
+
lines.append(current)
|
|
349
|
+
return lines
|
blackbox/pricing.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Model pricing, in US dollars per million tokens.
|
|
2
|
+
|
|
3
|
+
Rates verified against Anthropic's published pricing on 2026-11-10. They are
|
|
4
|
+
data, not logic: when prices move, edit this table and nothing else.
|
|
5
|
+
|
|
6
|
+
Two cache tiers are priced separately because they are billed separately:
|
|
7
|
+
|
|
8
|
+
* a **cache read** is far cheaper than fresh input -- 0.1x the input rate by
|
|
9
|
+
default, with per-model overrides where Anthropic publishes one;
|
|
10
|
+
* a **cache write** costs *more* than fresh input, and a 1-hour write costs
|
|
11
|
+
more than a 5-minute one (2.0x vs 1.25x the input rate).
|
|
12
|
+
|
|
13
|
+
That last line is why a run can look cheap per token and still be expensive:
|
|
14
|
+
rebuilding a long 1-hour-cached prefix is the single most effective way to
|
|
15
|
+
burn money without noticing.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
|
|
22
|
+
PRICING_AS_OF = "2026-11-10"
|
|
23
|
+
|
|
24
|
+
CACHE_READ_MULTIPLIER = 0.1
|
|
25
|
+
CACHE_WRITE_5M_MULTIPLIER = 1.25
|
|
26
|
+
CACHE_WRITE_1H_MULTIPLIER = 2.0
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class Price:
|
|
31
|
+
"""Dollars per million tokens for one model."""
|
|
32
|
+
|
|
33
|
+
input: float
|
|
34
|
+
output: float
|
|
35
|
+
cache_read: float | None = None
|
|
36
|
+
cache_write_5m: float | None = None
|
|
37
|
+
cache_write_1h: float | None = None
|
|
38
|
+
|
|
39
|
+
def read_rate(self) -> float:
|
|
40
|
+
if self.cache_read is not None:
|
|
41
|
+
return self.cache_read
|
|
42
|
+
return self.input * CACHE_READ_MULTIPLIER
|
|
43
|
+
|
|
44
|
+
def write_5m_rate(self) -> float:
|
|
45
|
+
if self.cache_write_5m is not None:
|
|
46
|
+
return self.cache_write_5m
|
|
47
|
+
return self.input * CACHE_WRITE_5M_MULTIPLIER
|
|
48
|
+
|
|
49
|
+
def write_1h_rate(self) -> float:
|
|
50
|
+
if self.cache_write_1h is not None:
|
|
51
|
+
return self.cache_write_1h
|
|
52
|
+
return self.input * CACHE_WRITE_1H_MULTIPLIER
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# Explicit cache-read rates below are the ones Anthropic publishes directly;
|
|
56
|
+
# every other model falls back to the 0.1x default.
|
|
57
|
+
PRICES: dict[str, Price] = {
|
|
58
|
+
"claude-fable-5-2": Price(input=8.00, output=40.00, cache_read=0.20),
|
|
59
|
+
"claude-mythos-5-2": Price(input=8.00, output=40.00, cache_read=0.20),
|
|
60
|
+
"claude-fable-5-1": Price(input=10.00, output=50.00),
|
|
61
|
+
"claude-mythos-5-1": Price(input=10.00, output=50.00),
|
|
62
|
+
"claude-fable-5": Price(input=10.00, output=50.00),
|
|
63
|
+
"claude-opus-5-5": Price(input=4.00, output=20.00, cache_read=0.20),
|
|
64
|
+
"claude-opus-5": Price(input=5.00, output=25.00),
|
|
65
|
+
"claude-opus-4-8": Price(input=5.00, output=25.00),
|
|
66
|
+
"claude-opus-4-7": Price(input=5.00, output=25.00),
|
|
67
|
+
"claude-opus-4-6": Price(input=5.00, output=25.00),
|
|
68
|
+
"claude-sonnet-5-5": Price(input=2.00, output=10.00, cache_read=0.10),
|
|
69
|
+
"claude-sonnet-5": Price(input=2.00, output=10.00),
|
|
70
|
+
"claude-sonnet-4-6": Price(input=3.00, output=15.00),
|
|
71
|
+
"claude-haiku-5-5": Price(input=0.10, output=0.50),
|
|
72
|
+
"claude-haiku-4-5": Price(input=1.00, output=5.00),
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
# Rows the harness writes for its own bookkeeping. They carry no model call,
|
|
76
|
+
# so they cost nothing -- priced at zero rather than reported as unknown.
|
|
77
|
+
FREE_MODELS = {"<synthetic>"}
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
# Rates supplied at runtime, for models this table does not ship. Kept
|
|
81
|
+
# separate from PRICES so it is always clear which numbers came from the user
|
|
82
|
+
# and which were verified here.
|
|
83
|
+
OVERRIDES: dict[str, Price] = {}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def set_overrides(mapping: dict[str, dict[str, float]] | None) -> dict[str, dict[str, float]]:
|
|
87
|
+
"""Install user-supplied rates. Returns what was applied, for the record.
|
|
88
|
+
|
|
89
|
+
This exists because guessing is not an option. Rates for models outside
|
|
90
|
+
this table -- another vendor's, or one released after it was written --
|
|
91
|
+
have to come from whoever is running the tool, and then travel with the
|
|
92
|
+
stored run so a replay prices it identically.
|
|
93
|
+
"""
|
|
94
|
+
OVERRIDES.clear()
|
|
95
|
+
applied: dict[str, dict[str, float]] = {}
|
|
96
|
+
for model, entry in sorted((mapping or {}).items()):
|
|
97
|
+
if not isinstance(entry, dict):
|
|
98
|
+
continue
|
|
99
|
+
try:
|
|
100
|
+
price = Price(
|
|
101
|
+
input=float(entry["input"]),
|
|
102
|
+
output=float(entry["output"]),
|
|
103
|
+
cache_read=_opt(entry.get("cache_read")),
|
|
104
|
+
cache_write_5m=_opt(entry.get("cache_write_5m")),
|
|
105
|
+
cache_write_1h=_opt(entry.get("cache_write_1h")),
|
|
106
|
+
)
|
|
107
|
+
except (KeyError, TypeError, ValueError):
|
|
108
|
+
continue
|
|
109
|
+
OVERRIDES[model] = price
|
|
110
|
+
applied[model] = {
|
|
111
|
+
"input": price.input,
|
|
112
|
+
"output": price.output,
|
|
113
|
+
"cache_read": price.cache_read,
|
|
114
|
+
"cache_write_5m": price.cache_write_5m,
|
|
115
|
+
"cache_write_1h": price.cache_write_1h,
|
|
116
|
+
}
|
|
117
|
+
return applied
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _opt(value) -> float | None:
|
|
121
|
+
return None if value is None else float(value)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def lookup(model: str | None) -> Price | None:
|
|
125
|
+
"""Return the price for ``model``, or ``None`` when it is not in the table.
|
|
126
|
+
|
|
127
|
+
An unknown model is never guessed at. The report counts its tokens and
|
|
128
|
+
says plainly that part of the bill could not be priced -- a wrong number
|
|
129
|
+
is worse than a missing one.
|
|
130
|
+
"""
|
|
131
|
+
if not model:
|
|
132
|
+
return None
|
|
133
|
+
if model in OVERRIDES:
|
|
134
|
+
return OVERRIDES[model]
|
|
135
|
+
if model in FREE_MODELS:
|
|
136
|
+
return Price(input=0.0, output=0.0, cache_read=0.0, cache_write_5m=0.0, cache_write_1h=0.0)
|
|
137
|
+
return PRICES.get(model)
|
blackbox/py.typed
ADDED
|
File without changes
|
blackbox/replay.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Deterministic replay.
|
|
2
|
+
|
|
3
|
+
Re-derives the entire report from the stored canonical events -- no trace file,
|
|
4
|
+
no network, no model call -- and must produce byte-identical output.
|
|
5
|
+
|
|
6
|
+
This is the load-bearing claim of the whole tool. An analysis of an agent run
|
|
7
|
+
that cannot itself be re-verified is just another opinion; one that reproduces
|
|
8
|
+
exactly, from a store you can also query by hand, is evidence. The thresholds
|
|
9
|
+
are read back out of the store rather than re-defaulted, so a replay cannot
|
|
10
|
+
quietly disagree with the original pass because a default moved.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
|
|
17
|
+
from blackbox import store
|
|
18
|
+
from blackbox.analysis import Analysis, analyze_events
|
|
19
|
+
from blackbox.detectors.base import Config
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def config_from_meta(meta: dict[str, str]) -> Config:
|
|
23
|
+
raw = meta.get("config")
|
|
24
|
+
if not raw:
|
|
25
|
+
return Config()
|
|
26
|
+
try:
|
|
27
|
+
data = json.loads(raw)
|
|
28
|
+
except json.JSONDecodeError:
|
|
29
|
+
return Config()
|
|
30
|
+
allowed = {f for f in Config.__dataclass_fields__}
|
|
31
|
+
return Config(**{k: v for k, v in data.items() if k in allowed})
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def replay(db_path: str) -> Analysis:
|
|
35
|
+
"""Rebuild the analysis from a stored run. Zero model calls."""
|
|
36
|
+
from blackbox import pricing
|
|
37
|
+
|
|
38
|
+
events = store.read_events(db_path)
|
|
39
|
+
meta = store.read_meta(db_path)
|
|
40
|
+
|
|
41
|
+
# Rates supplied at analysis time are part of the input, so a replay has
|
|
42
|
+
# to use the same ones or it would price the same run differently.
|
|
43
|
+
try:
|
|
44
|
+
overrides = json.loads(meta.get("price_overrides") or "{}")
|
|
45
|
+
except json.JSONDecodeError:
|
|
46
|
+
overrides = {}
|
|
47
|
+
applied = pricing.set_overrides(overrides)
|
|
48
|
+
|
|
49
|
+
trace_meta = {}
|
|
50
|
+
for key, value in meta.items():
|
|
51
|
+
if key.startswith("trace."):
|
|
52
|
+
try:
|
|
53
|
+
trace_meta[key[len("trace.") :]] = json.loads(value)
|
|
54
|
+
except json.JSONDecodeError:
|
|
55
|
+
trace_meta[key[len("trace.") :]] = value
|
|
56
|
+
|
|
57
|
+
return analyze_events(
|
|
58
|
+
events,
|
|
59
|
+
source=meta.get("source", db_path),
|
|
60
|
+
adapter=meta.get("adapter", "unknown"),
|
|
61
|
+
meta=trace_meta,
|
|
62
|
+
config=config_from_meta(meta),
|
|
63
|
+
skipped_lines=int(meta.get("skipped_lines") or 0),
|
|
64
|
+
price_overrides=applied,
|
|
65
|
+
)
|
|
File without changes
|