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/graph.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""The causal graph.
|
|
2
|
+
|
|
3
|
+
A trace file is a flat list of rows. This module turns it into the shape the
|
|
4
|
+
run actually had: a tree of events, with each subagent's work separated into
|
|
5
|
+
its own branch.
|
|
6
|
+
|
|
7
|
+
Why bother, when you could just count tool calls in file order? Because a flat
|
|
8
|
+
list cannot answer the two questions that make the rest of the report mean
|
|
9
|
+
anything:
|
|
10
|
+
|
|
11
|
+
* **Which result belongs to which call?** With parallel tool calls inside one
|
|
12
|
+
assistant message, file order alone cannot say. Per-call durations computed
|
|
13
|
+
from it are wrong, and "the agent stalled" becomes a coin flip.
|
|
14
|
+
* **Whose cost is this?** A subagent's tokens are billed to the run but are not
|
|
15
|
+
the main thread's work. Smear them together and the expensive step looks
|
|
16
|
+
cheap while the main thread looks bloated.
|
|
17
|
+
|
|
18
|
+
Branch names are assigned in order of first appearance, so the same trace
|
|
19
|
+
always produces the same names.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
from dataclasses import dataclass, field, replace
|
|
25
|
+
|
|
26
|
+
from blackbox.events import MAIN_BRANCH, TOOL_CALL, TOOL_RESULT, Event
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class Branch:
|
|
31
|
+
"""One thread of execution: the main thread, or one subagent."""
|
|
32
|
+
|
|
33
|
+
name: str
|
|
34
|
+
root_uid: str | None
|
|
35
|
+
event_count: int = 0
|
|
36
|
+
tool_calls: int = 0
|
|
37
|
+
first_seq: int = 0
|
|
38
|
+
last_seq: int = 0
|
|
39
|
+
|
|
40
|
+
@property
|
|
41
|
+
def is_main(self) -> bool:
|
|
42
|
+
return self.name == MAIN_BRANCH
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class Graph:
|
|
47
|
+
events: list[Event]
|
|
48
|
+
by_uid: dict[str, Event] = field(default_factory=dict)
|
|
49
|
+
children: dict[str, list[str]] = field(default_factory=dict)
|
|
50
|
+
branches: list[Branch] = field(default_factory=list)
|
|
51
|
+
roots: list[str] = field(default_factory=list)
|
|
52
|
+
orphans: int = 0
|
|
53
|
+
|
|
54
|
+
# -- lookups -----------------------------------------------------------
|
|
55
|
+
|
|
56
|
+
def tool_calls(self, branch: str | None = None) -> list[Event]:
|
|
57
|
+
return [
|
|
58
|
+
e
|
|
59
|
+
for e in self.events
|
|
60
|
+
if e.kind == TOOL_CALL and (branch is None or e.branch == branch)
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
def result_for(self, call: Event) -> Event | None:
|
|
64
|
+
"""The result answering ``call``, found through the re-parented edge."""
|
|
65
|
+
for uid in self.children.get(call.uid, ()):
|
|
66
|
+
child = self.by_uid.get(uid)
|
|
67
|
+
if child is not None and child.kind == TOOL_RESULT:
|
|
68
|
+
return child
|
|
69
|
+
return None
|
|
70
|
+
|
|
71
|
+
def branch_named(self, name: str) -> Branch | None:
|
|
72
|
+
for b in self.branches:
|
|
73
|
+
if b.name == name:
|
|
74
|
+
return b
|
|
75
|
+
return None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def build(events: list[Event]) -> Graph:
|
|
79
|
+
"""Assign branches and index the tree. ``events`` is not mutated."""
|
|
80
|
+
ordered = sorted(events, key=lambda e: e.seq)
|
|
81
|
+
by_uid = {e.uid: e for e in ordered}
|
|
82
|
+
|
|
83
|
+
# --- branch assignment ------------------------------------------------
|
|
84
|
+
# A sidechain event belongs to the branch of its nearest sidechain
|
|
85
|
+
# ancestor. An event whose parent is absent or not a sidechain starts one.
|
|
86
|
+
branch_of: dict[str, str] = {}
|
|
87
|
+
branch_names: dict[str, str] = {} # root uid -> display name
|
|
88
|
+
next_index = 1
|
|
89
|
+
|
|
90
|
+
for ev in ordered:
|
|
91
|
+
if not ev.is_sidechain:
|
|
92
|
+
branch_of[ev.uid] = MAIN_BRANCH
|
|
93
|
+
continue
|
|
94
|
+
|
|
95
|
+
parent = by_uid.get(ev.parent_uid) if ev.parent_uid else None
|
|
96
|
+
if parent is not None and parent.is_sidechain:
|
|
97
|
+
# Inherit the parent's branch. Parents precede children in seq
|
|
98
|
+
# order in practice; if one does not, fall back to starting a
|
|
99
|
+
# branch here rather than silently mislabelling the event.
|
|
100
|
+
inherited = branch_of.get(parent.uid)
|
|
101
|
+
if inherited and inherited != MAIN_BRANCH:
|
|
102
|
+
branch_of[ev.uid] = inherited
|
|
103
|
+
continue
|
|
104
|
+
|
|
105
|
+
name = branch_names.get(ev.uid)
|
|
106
|
+
if name is None:
|
|
107
|
+
name = f"subagent-{next_index}"
|
|
108
|
+
next_index += 1
|
|
109
|
+
branch_names[ev.uid] = name
|
|
110
|
+
branch_of[ev.uid] = name
|
|
111
|
+
|
|
112
|
+
labelled = [replace(e, branch=branch_of.get(e.uid, MAIN_BRANCH)) for e in ordered]
|
|
113
|
+
by_uid = {e.uid: e for e in labelled}
|
|
114
|
+
|
|
115
|
+
# --- index ------------------------------------------------------------
|
|
116
|
+
children: dict[str, list[str]] = {}
|
|
117
|
+
roots: list[str] = []
|
|
118
|
+
orphans = 0
|
|
119
|
+
for ev in labelled:
|
|
120
|
+
if ev.parent_uid is None:
|
|
121
|
+
roots.append(ev.uid)
|
|
122
|
+
elif ev.parent_uid in by_uid:
|
|
123
|
+
children.setdefault(ev.parent_uid, []).append(ev.uid)
|
|
124
|
+
else:
|
|
125
|
+
orphans += 1
|
|
126
|
+
roots.append(ev.uid)
|
|
127
|
+
|
|
128
|
+
# --- branch summaries -------------------------------------------------
|
|
129
|
+
summaries: dict[str, Branch] = {}
|
|
130
|
+
for ev in labelled:
|
|
131
|
+
b = summaries.get(ev.branch)
|
|
132
|
+
if b is None:
|
|
133
|
+
root = None if ev.branch == MAIN_BRANCH else ev.uid
|
|
134
|
+
b = Branch(name=ev.branch, root_uid=root, first_seq=ev.seq, last_seq=ev.seq)
|
|
135
|
+
summaries[ev.branch] = b
|
|
136
|
+
b.event_count += 1
|
|
137
|
+
b.last_seq = max(b.last_seq, ev.seq)
|
|
138
|
+
if ev.kind == TOOL_CALL:
|
|
139
|
+
b.tool_calls += 1
|
|
140
|
+
|
|
141
|
+
branches = sorted(summaries.values(), key=lambda b: (not b.is_main, b.first_seq))
|
|
142
|
+
|
|
143
|
+
return Graph(
|
|
144
|
+
events=labelled,
|
|
145
|
+
by_uid=by_uid,
|
|
146
|
+
children=children,
|
|
147
|
+
branches=branches,
|
|
148
|
+
roots=roots,
|
|
149
|
+
orphans=orphans,
|
|
150
|
+
)
|
blackbox/guard.py
ADDED
|
@@ -0,0 +1,528 @@
|
|
|
1
|
+
"""The live guardrail: the same detectors, run while the agent is still working.
|
|
2
|
+
|
|
3
|
+
Everything else in this package reads a run after it ends. That is the right
|
|
4
|
+
place to find out what went wrong, and the wrong place to stop it. A retry
|
|
5
|
+
loop costs money on every turn it lasts; a report on it the next morning
|
|
6
|
+
saves none of that money.
|
|
7
|
+
|
|
8
|
+
This module runs as a Claude Code hook. Before each tool call (``PreToolUse``)
|
|
9
|
+
and after it (``PostToolUse``) Claude Code hands the hook the session's
|
|
10
|
+
transcript path and the call. The guard parses the transcript with the normal
|
|
11
|
+
adapter, puts the call on the end, and asks two detectors one question:
|
|
12
|
+
*does this call extend a streak?*
|
|
13
|
+
|
|
14
|
+
* ``retry_loop`` -- the same acting call, with identical input, again.
|
|
15
|
+
* ``thrash`` -- another write to a file just written several times.
|
|
16
|
+
|
|
17
|
+
What happens next is set by severity, using the detectors' own scale:
|
|
18
|
+
|
|
19
|
+
* **warn** (default: medium) -- after the call runs, the agent is told what it
|
|
20
|
+
is repeating and what the repeats have cost so far.
|
|
21
|
+
* **block** (default: high) -- before the call runs, it is denied, with the
|
|
22
|
+
same explanation as the reason. The call never happens, so neither does the
|
|
23
|
+
turn that would have followed it.
|
|
24
|
+
|
|
25
|
+
Three rules keep it from getting in the way of ordinary work, each one a case
|
|
26
|
+
where blocking would be wrong:
|
|
27
|
+
|
|
28
|
+
* **An edit resets a retry streak.** Running the tests, editing the code and
|
|
29
|
+
running the tests again is the loop working as intended. Identical calls
|
|
30
|
+
only count as retries while nothing has been written in between.
|
|
31
|
+
* **A streak is blocked once.** If the agent makes the same call again right
|
|
32
|
+
after being blocked, it goes through with a warning. The agent has been
|
|
33
|
+
told; a guard that can trap an agent is worse than no guard.
|
|
34
|
+
* **Calls it cannot place are allowed.** A subagent call that is not in the
|
|
35
|
+
transcript yet cannot be put on the right branch, so it is not judged.
|
|
36
|
+
|
|
37
|
+
Nothing here makes a model call or opens a socket, and the decision is a pure
|
|
38
|
+
function of the transcript and the call -- the same input always gets the
|
|
39
|
+
same answer, which is what makes :func:`replay` an honest demo.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
from __future__ import annotations
|
|
43
|
+
|
|
44
|
+
import json
|
|
45
|
+
import os
|
|
46
|
+
from dataclasses import dataclass, replace
|
|
47
|
+
from typing import Any
|
|
48
|
+
|
|
49
|
+
from blackbox import cost as cost_mod
|
|
50
|
+
from blackbox import graph as graph_mod
|
|
51
|
+
from blackbox import toolinfo
|
|
52
|
+
from blackbox.describe import describe
|
|
53
|
+
from blackbox.detectors import retry_loops, thrash
|
|
54
|
+
from blackbox.detectors.base import HIGH, LOW, MEDIUM, Config, Finding
|
|
55
|
+
from blackbox.events import MAIN_BRANCH, TOOL_CALL, Event
|
|
56
|
+
|
|
57
|
+
# Every message the guard writes starts with this, so a call it denied can be
|
|
58
|
+
# recognised in the transcript afterwards and kept out of the counts.
|
|
59
|
+
MARKER = "[agent-blackbox guard]"
|
|
60
|
+
|
|
61
|
+
ALLOW = "allow"
|
|
62
|
+
WARN = "warn"
|
|
63
|
+
BLOCK = "block"
|
|
64
|
+
|
|
65
|
+
NEVER = "never"
|
|
66
|
+
_RANK = {HIGH: 0, MEDIUM: 1, LOW: 2, NEVER: 99}
|
|
67
|
+
|
|
68
|
+
GUARDED_DETECTORS = (retry_loops.NAME, thrash.NAME)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass(frozen=True)
|
|
72
|
+
class Policy:
|
|
73
|
+
"""Which severity earns a warning, and which earns a block.
|
|
74
|
+
|
|
75
|
+
The defaults follow the detectors' own scale. A retry loop is medium at
|
|
76
|
+
3 identical calls and high at 5; thrash is medium at 5 writes to one file
|
|
77
|
+
and high at 8. So by default the agent hears about a retry on the 3rd
|
|
78
|
+
attempt and is stopped on the 5th, and hears about a file on the 5th
|
|
79
|
+
write and is stopped on the 8th.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
warn_at: str = MEDIUM
|
|
83
|
+
block_at: str = HIGH
|
|
84
|
+
|
|
85
|
+
def __post_init__(self) -> None:
|
|
86
|
+
for name in ("warn_at", "block_at"):
|
|
87
|
+
value = getattr(self, name)
|
|
88
|
+
if value not in _RANK:
|
|
89
|
+
raise ValueError(f"{name} must be one of high, medium, low, never; got {value!r}")
|
|
90
|
+
|
|
91
|
+
def action_for(self, severity: str) -> str:
|
|
92
|
+
rank = _RANK.get(severity, _RANK[NEVER])
|
|
93
|
+
if self.block_at != NEVER and rank <= _RANK[self.block_at]:
|
|
94
|
+
return BLOCK
|
|
95
|
+
if self.warn_at != NEVER and rank <= _RANK[self.warn_at]:
|
|
96
|
+
return WARN
|
|
97
|
+
return ALLOW
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
@dataclass(frozen=True)
|
|
101
|
+
class Decision:
|
|
102
|
+
action: str
|
|
103
|
+
detector: str | None = None
|
|
104
|
+
severity: str | None = None
|
|
105
|
+
count: int = 0
|
|
106
|
+
span: int = 0
|
|
107
|
+
usd: float = 0.0
|
|
108
|
+
subject: str = ""
|
|
109
|
+
message: str = ""
|
|
110
|
+
notice: str = ""
|
|
111
|
+
streak_key: str = ""
|
|
112
|
+
|
|
113
|
+
@property
|
|
114
|
+
def speaks(self) -> bool:
|
|
115
|
+
return self.action != ALLOW
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
ALLOWED = Decision(action=ALLOW)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
# --- core ------------------------------------------------------------------
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def was_blocked(result: Event | None) -> bool:
|
|
125
|
+
"""True when a call's result is the guard's own denial."""
|
|
126
|
+
return result is not None and MARKER in result.tool_output[:2000]
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def check(
|
|
130
|
+
calls: list[Event],
|
|
131
|
+
pending: Event,
|
|
132
|
+
by_uid: dict[str, Event],
|
|
133
|
+
*,
|
|
134
|
+
blocked: set[str] | frozenset[str] = frozenset(),
|
|
135
|
+
config: Config | None = None,
|
|
136
|
+
policy: Policy | None = None,
|
|
137
|
+
) -> Decision:
|
|
138
|
+
"""Judge ``pending`` against the calls before it on the same branch.
|
|
139
|
+
|
|
140
|
+
``calls`` are the branch's earlier tool calls in order. ``blocked`` holds
|
|
141
|
+
the uids of calls the guard already denied: they did not run, so they do
|
|
142
|
+
not count towards a streak, but they do mean that streak has had its one
|
|
143
|
+
block. ``by_uid`` is used only to price the turns behind a streak.
|
|
144
|
+
"""
|
|
145
|
+
config = config or Config()
|
|
146
|
+
policy = policy or Policy()
|
|
147
|
+
|
|
148
|
+
executed = [c for c in calls if c.uid not in blocked]
|
|
149
|
+
events = executed + [pending]
|
|
150
|
+
branch = graph_mod.Branch(name=pending.branch, root_uid=None)
|
|
151
|
+
g = graph_mod.Graph(events=events, by_uid=by_uid, branches=[branch])
|
|
152
|
+
|
|
153
|
+
candidates: list[tuple[Finding, list[Event]]] = []
|
|
154
|
+
|
|
155
|
+
for finding in retry_loops.run(g, config):
|
|
156
|
+
if pending.uid not in finding.evidence or finding.metrics.get("kind") != "retry_loop":
|
|
157
|
+
continue
|
|
158
|
+
streak = _since_last_write(finding, events)
|
|
159
|
+
if len(streak) < config.retry_min_repeats:
|
|
160
|
+
continue
|
|
161
|
+
severity = HIGH if len(streak) >= 5 else MEDIUM
|
|
162
|
+
candidates.append((replace(finding, severity=severity, count=len(streak)), streak))
|
|
163
|
+
|
|
164
|
+
for finding in thrash.run(g, config):
|
|
165
|
+
if pending.uid not in finding.evidence:
|
|
166
|
+
continue
|
|
167
|
+
members = [e for e in events if e.uid in set(finding.evidence)]
|
|
168
|
+
candidates.append((finding, members))
|
|
169
|
+
|
|
170
|
+
if not candidates:
|
|
171
|
+
return ALLOWED
|
|
172
|
+
|
|
173
|
+
finding, streak = min(candidates, key=lambda pair: pair[0].sort_key())
|
|
174
|
+
action = policy.action_for(finding.severity)
|
|
175
|
+
if action == ALLOW:
|
|
176
|
+
return ALLOWED
|
|
177
|
+
|
|
178
|
+
streak_key = _streak_key(finding, pending)
|
|
179
|
+
if action == BLOCK and _already_blocked(streak_key, streak, calls, blocked):
|
|
180
|
+
action = WARN
|
|
181
|
+
|
|
182
|
+
index = {c.uid: i for i, c in enumerate(events)}
|
|
183
|
+
span_calls = index[streak[-1].uid] - index[streak[0].uid] + 1
|
|
184
|
+
earlier = [e for e in streak if e.uid != pending.uid]
|
|
185
|
+
usd = _turns_usd(earlier, by_uid)
|
|
186
|
+
subject = describe(pending)
|
|
187
|
+
|
|
188
|
+
decision = Decision(
|
|
189
|
+
action=action,
|
|
190
|
+
detector=finding.detector,
|
|
191
|
+
severity=finding.severity,
|
|
192
|
+
count=len(streak),
|
|
193
|
+
span=span_calls,
|
|
194
|
+
usd=round(usd, 6),
|
|
195
|
+
subject=subject,
|
|
196
|
+
streak_key=streak_key,
|
|
197
|
+
)
|
|
198
|
+
# ``notice`` is the after-the-fact wording: what a PostToolUse hook says
|
|
199
|
+
# when the call has already run, whatever the action would have been.
|
|
200
|
+
return replace(
|
|
201
|
+
decision,
|
|
202
|
+
message=_message(decision, pending),
|
|
203
|
+
notice=_message(replace(decision, action=WARN), pending),
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _since_last_write(finding: Finding, events: list[Event]) -> list[Event]:
|
|
208
|
+
"""The members of a retry cluster that came after the last write.
|
|
209
|
+
|
|
210
|
+
Identical calls only mean "nothing changed" if nothing changed. An edit
|
|
211
|
+
to any file between two test runs makes the second run a new experiment,
|
|
212
|
+
not a retry.
|
|
213
|
+
"""
|
|
214
|
+
members = set(finding.evidence)
|
|
215
|
+
streak: list[Event] = []
|
|
216
|
+
for call in events:
|
|
217
|
+
if call.uid in members:
|
|
218
|
+
streak.append(call)
|
|
219
|
+
continue
|
|
220
|
+
kinds = {kind for _, kind in toolinfo.file_operations(call.tool_name, call.tool_input)}
|
|
221
|
+
if kinds & {toolinfo.WRITE, toolinfo.EDIT}:
|
|
222
|
+
streak = []
|
|
223
|
+
return streak
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _streak_key(finding: Finding, pending: Event) -> str:
|
|
227
|
+
if finding.detector == thrash.NAME:
|
|
228
|
+
return f"thrash:{finding.metrics.get('path')}"
|
|
229
|
+
return f"retry:{pending.tool_name}:{pending.input_digest()}"
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _already_blocked(
|
|
233
|
+
streak_key: str, streak: list[Event], calls: list[Event], blocked: set[str] | frozenset[str]
|
|
234
|
+
) -> bool:
|
|
235
|
+
"""Has the guard already denied a call belonging to this streak?"""
|
|
236
|
+
if not blocked or not streak:
|
|
237
|
+
return False
|
|
238
|
+
first = streak[0].seq
|
|
239
|
+
for call in calls:
|
|
240
|
+
if call.uid not in blocked or call.seq < first:
|
|
241
|
+
continue
|
|
242
|
+
if _key_of(call, streak_key) == streak_key:
|
|
243
|
+
return True
|
|
244
|
+
return False
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _key_of(call: Event, like: str) -> str:
|
|
248
|
+
if like.startswith("thrash:"):
|
|
249
|
+
for path, kind in toolinfo.file_operations(call.tool_name, call.tool_input):
|
|
250
|
+
if kind in (toolinfo.WRITE, toolinfo.EDIT) and like == f"thrash:{path}":
|
|
251
|
+
return like
|
|
252
|
+
return ""
|
|
253
|
+
return f"retry:{call.tool_name}:{call.input_digest()}"
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _turns_usd(calls: list[Event], by_uid: dict[str, Event]) -> float:
|
|
257
|
+
"""What the model turns that issued these calls cost, each turn once."""
|
|
258
|
+
turns: dict[str, Event] = {}
|
|
259
|
+
for call in calls:
|
|
260
|
+
parent = by_uid.get(call.parent_uid) if call.parent_uid else None
|
|
261
|
+
if parent is not None and not parent.usage.is_empty():
|
|
262
|
+
turns[parent.uid] = parent
|
|
263
|
+
return sum(cost_mod.event_usd(turns[uid]) for uid in sorted(turns))
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _ordinal(n: int) -> str:
|
|
267
|
+
suffix = "th" if 10 <= n % 100 <= 20 else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th")
|
|
268
|
+
return f"{n}{suffix}"
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _money(usd: float) -> str:
|
|
272
|
+
if usd <= 0:
|
|
273
|
+
return ""
|
|
274
|
+
return f" The earlier ones cost about ${usd:.2f}." if usd >= 0.01 else " The earlier ones cost under a cent."
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _message(d: Decision, pending: Event) -> str:
|
|
278
|
+
what = d.subject
|
|
279
|
+
if d.detector == thrash.NAME:
|
|
280
|
+
path = toolinfo.target_path(pending.tool_name, pending.tool_input) or "this file"
|
|
281
|
+
head = (
|
|
282
|
+
f"{MARKER} This is the {_ordinal(d.count)} write to {path} in the last "
|
|
283
|
+
f"{d.span} tool calls.{_money(d.usd)}"
|
|
284
|
+
)
|
|
285
|
+
why = (
|
|
286
|
+
" Edits packed that tightly usually mean each one is fixing the last. "
|
|
287
|
+
"Re-read the whole file and decide what it should contain before changing it again."
|
|
288
|
+
)
|
|
289
|
+
else:
|
|
290
|
+
head = (
|
|
291
|
+
f"{MARKER} This is the {_ordinal(d.count)} identical call in the last "
|
|
292
|
+
f"{d.span} tool calls, with nothing written in between: {what}.{_money(d.usd)}"
|
|
293
|
+
)
|
|
294
|
+
why = (
|
|
295
|
+
" Identical input will give the same result. Read the last output, change "
|
|
296
|
+
"something, or try a different approach before running it again."
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
if d.action == BLOCK:
|
|
300
|
+
return (
|
|
301
|
+
head.replace(f"{MARKER} This is", f"{MARKER} Blocked. This would be", 1)
|
|
302
|
+
+ why
|
|
303
|
+
+ " (If you make this call again unchanged, it will be allowed.)"
|
|
304
|
+
)
|
|
305
|
+
return head + why
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
# --- reading a Claude Code session ---------------------------------------
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
# How much of a long session the hook reads. A streak is found within a
|
|
312
|
+
# window of a few dozen tool calls, so the last few thousand rows hold any
|
|
313
|
+
# streak that matters; reading them keeps the hook well under a second on a
|
|
314
|
+
# session of any length, where reading the whole file would not.
|
|
315
|
+
TAIL_LINES = 4_000
|
|
316
|
+
TAIL_BYTES = 24 * 1024 * 1024
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def tail_lines(path: str, max_lines: int = TAIL_LINES, max_bytes: int = TAIL_BYTES) -> list[str]:
|
|
320
|
+
"""The last ``max_lines`` complete lines of a file, reading from the end."""
|
|
321
|
+
with open(path, "rb") as fh:
|
|
322
|
+
fh.seek(0, os.SEEK_END)
|
|
323
|
+
end = fh.tell()
|
|
324
|
+
position = end
|
|
325
|
+
chunks: list[bytes] = []
|
|
326
|
+
newlines = 0
|
|
327
|
+
while position > 0 and newlines <= max_lines and end - position < max_bytes:
|
|
328
|
+
step = min(1024 * 1024, position)
|
|
329
|
+
position -= step
|
|
330
|
+
fh.seek(position)
|
|
331
|
+
chunk = fh.read(step)
|
|
332
|
+
chunks.append(chunk)
|
|
333
|
+
newlines += chunk.count(b"\n")
|
|
334
|
+
data = b"".join(reversed(chunks))
|
|
335
|
+
lines = data.decode("utf-8", errors="replace").split("\n")
|
|
336
|
+
if position > 0:
|
|
337
|
+
lines = lines[1:] # the first line was cut part-way through
|
|
338
|
+
return lines[-max_lines:]
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _load(transcript_path: str | None) -> graph_mod.Graph:
|
|
342
|
+
from blackbox.adapters import claude_code
|
|
343
|
+
|
|
344
|
+
if not transcript_path or not os.path.isfile(transcript_path):
|
|
345
|
+
return graph_mod.build([])
|
|
346
|
+
trace = claude_code.parse_lines(tail_lines(transcript_path), source=transcript_path)
|
|
347
|
+
return graph_mod.build(trace.events)
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _blocked_uids(g: graph_mod.Graph) -> set[str]:
|
|
351
|
+
return {call.uid for call in g.tool_calls() if was_blocked(g.result_for(call))}
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def from_hook(
|
|
355
|
+
payload: dict[str, Any],
|
|
356
|
+
*,
|
|
357
|
+
config: Config | None = None,
|
|
358
|
+
policy: Policy | None = None,
|
|
359
|
+
) -> Decision:
|
|
360
|
+
"""Judge the call described by a Claude Code hook's stdin."""
|
|
361
|
+
tool_name = payload.get("tool_name")
|
|
362
|
+
if not isinstance(tool_name, str) or not tool_name:
|
|
363
|
+
return ALLOWED
|
|
364
|
+
tool_input = payload.get("tool_input")
|
|
365
|
+
tool_input = tool_input if isinstance(tool_input, dict) else {}
|
|
366
|
+
tool_use_id = payload.get("tool_use_id")
|
|
367
|
+
|
|
368
|
+
g = _load(payload.get("transcript_path"))
|
|
369
|
+
calls = g.tool_calls()
|
|
370
|
+
|
|
371
|
+
# The transcript is written asynchronously and may not hold this call
|
|
372
|
+
# yet. When it does, judge it in place; when not, append it.
|
|
373
|
+
position = next(
|
|
374
|
+
(i for i, c in enumerate(calls) if tool_use_id and c.tool_use_id == tool_use_id), None
|
|
375
|
+
)
|
|
376
|
+
if position is not None:
|
|
377
|
+
pending = calls[position]
|
|
378
|
+
earlier = [c for c in calls[:position] if c.branch == pending.branch]
|
|
379
|
+
else:
|
|
380
|
+
if payload.get("agent_id"):
|
|
381
|
+
# A subagent's call we cannot see cannot be put on its branch.
|
|
382
|
+
return ALLOWED
|
|
383
|
+
pending = Event(
|
|
384
|
+
uid=f"pending:{tool_use_id or 'call'}",
|
|
385
|
+
seq=(g.events[-1].seq + 1) if g.events else 0,
|
|
386
|
+
kind=TOOL_CALL,
|
|
387
|
+
parent_uid=None,
|
|
388
|
+
branch=MAIN_BRANCH,
|
|
389
|
+
tool_name=tool_name,
|
|
390
|
+
tool_use_id=tool_use_id if isinstance(tool_use_id, str) else None,
|
|
391
|
+
tool_input=tool_input,
|
|
392
|
+
)
|
|
393
|
+
earlier = [c for c in calls if c.branch == MAIN_BRANCH]
|
|
394
|
+
|
|
395
|
+
return check(
|
|
396
|
+
earlier,
|
|
397
|
+
pending,
|
|
398
|
+
g.by_uid,
|
|
399
|
+
blocked=_blocked_uids(g),
|
|
400
|
+
config=config,
|
|
401
|
+
policy=policy,
|
|
402
|
+
)
|
|
403
|
+
|
|
404
|
+
|
|
405
|
+
def hook_response(event_name: str, decision: Decision) -> dict[str, Any] | None:
|
|
406
|
+
"""The JSON a hook prints for ``decision``, or ``None`` to stay silent.
|
|
407
|
+
|
|
408
|
+
``PreToolUse`` only ever denies: a warning before the call would be
|
|
409
|
+
noise, and saying "allow" would skip the user's own permission prompt.
|
|
410
|
+
``PostToolUse`` only ever warns: the call has run, so the agent is told
|
|
411
|
+
alongside its result.
|
|
412
|
+
"""
|
|
413
|
+
if event_name == "PreToolUse" and decision.action == BLOCK:
|
|
414
|
+
return {
|
|
415
|
+
"hookSpecificOutput": {
|
|
416
|
+
"hookEventName": "PreToolUse",
|
|
417
|
+
"permissionDecision": "deny",
|
|
418
|
+
"permissionDecisionReason": decision.message,
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
if event_name == "PostToolUse" and decision.action in (WARN, BLOCK):
|
|
422
|
+
return {
|
|
423
|
+
"hookSpecificOutput": {
|
|
424
|
+
"hookEventName": "PostToolUse",
|
|
425
|
+
"additionalContext": decision.notice,
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
return None
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def run_hook(
|
|
432
|
+
stdin_text: str, *, config: Config | None = None, policy: Policy | None = None
|
|
433
|
+
) -> str:
|
|
434
|
+
"""Hook entry point: stdin in, stdout out. Never raises.
|
|
435
|
+
|
|
436
|
+
A guard that crashes must not take the agent down with it, so any
|
|
437
|
+
failure here means "say nothing" and the call proceeds as if the hook
|
|
438
|
+
were not installed.
|
|
439
|
+
"""
|
|
440
|
+
if os.environ.get("BLACKBOX_GUARD", "").lower() in ("0", "off", "false", "no"):
|
|
441
|
+
return ""
|
|
442
|
+
try:
|
|
443
|
+
payload = json.loads(stdin_text)
|
|
444
|
+
if not isinstance(payload, dict):
|
|
445
|
+
return ""
|
|
446
|
+
event_name = str(payload.get("hook_event_name") or "")
|
|
447
|
+
if event_name not in ("PreToolUse", "PostToolUse"):
|
|
448
|
+
return ""
|
|
449
|
+
decision = from_hook(payload, config=config, policy=policy)
|
|
450
|
+
response = hook_response(event_name, decision)
|
|
451
|
+
return json.dumps(response) if response else ""
|
|
452
|
+
except Exception: # noqa: BLE001 -- a guard must fail open
|
|
453
|
+
return ""
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
# --- replay: what the guard would have done on a finished run --------------
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
@dataclass(frozen=True)
|
|
460
|
+
class Intervention:
|
|
461
|
+
call: Event
|
|
462
|
+
decision: Decision
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
@dataclass(frozen=True)
|
|
466
|
+
class ReplayResult:
|
|
467
|
+
source: str
|
|
468
|
+
tool_calls: int
|
|
469
|
+
total_usd: float
|
|
470
|
+
interventions: list[Intervention]
|
|
471
|
+
blocked_usd: float
|
|
472
|
+
after_first_word_usd: float
|
|
473
|
+
|
|
474
|
+
@property
|
|
475
|
+
def warnings(self) -> int:
|
|
476
|
+
return sum(1 for i in self.interventions if i.decision.action == WARN)
|
|
477
|
+
|
|
478
|
+
@property
|
|
479
|
+
def blocks(self) -> int:
|
|
480
|
+
return sum(1 for i in self.interventions if i.decision.action == BLOCK)
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def replay(
|
|
484
|
+
path: str, *, config: Config | None = None, policy: Policy | None = None
|
|
485
|
+
) -> ReplayResult:
|
|
486
|
+
"""Walk a finished run call by call, as if the guard had been installed.
|
|
487
|
+
|
|
488
|
+
A call the guard would have blocked is treated as blocked from then on:
|
|
489
|
+
it does not count towards later streaks, and it uses up that streak's one
|
|
490
|
+
block. What the agent would have done instead cannot be known, so the run
|
|
491
|
+
is otherwise left as it happened.
|
|
492
|
+
"""
|
|
493
|
+
from blackbox.adapters import registry
|
|
494
|
+
|
|
495
|
+
config = config or Config()
|
|
496
|
+
policy = policy or Policy()
|
|
497
|
+
trace = registry.load(path)
|
|
498
|
+
g = graph_mod.build(trace.events)
|
|
499
|
+
total = cost_mod.compute(g.events).total_usd
|
|
500
|
+
|
|
501
|
+
blocked: set[str] = set()
|
|
502
|
+
interventions: list[Intervention] = []
|
|
503
|
+
by_branch: dict[str, list[Event]] = {}
|
|
504
|
+
spoken_streaks: set[str] = set()
|
|
505
|
+
after_word: list[Event] = []
|
|
506
|
+
blocked_calls: list[Event] = []
|
|
507
|
+
|
|
508
|
+
for call in g.tool_calls():
|
|
509
|
+
earlier = by_branch.setdefault(call.branch, [])
|
|
510
|
+
decision = check(earlier, call, g.by_uid, blocked=blocked, config=config, policy=policy)
|
|
511
|
+
if decision.speaks:
|
|
512
|
+
interventions.append(Intervention(call=call, decision=decision))
|
|
513
|
+
if decision.streak_key in spoken_streaks or decision.action == BLOCK:
|
|
514
|
+
after_word.append(call)
|
|
515
|
+
spoken_streaks.add(decision.streak_key)
|
|
516
|
+
if decision.action == BLOCK:
|
|
517
|
+
blocked.add(call.uid)
|
|
518
|
+
blocked_calls.append(call)
|
|
519
|
+
earlier.append(call)
|
|
520
|
+
|
|
521
|
+
return ReplayResult(
|
|
522
|
+
source=trace.source,
|
|
523
|
+
tool_calls=len(g.tool_calls()),
|
|
524
|
+
total_usd=total,
|
|
525
|
+
interventions=interventions,
|
|
526
|
+
blocked_usd=round(_turns_usd(blocked_calls, g.by_uid), 6),
|
|
527
|
+
after_first_word_usd=round(_turns_usd(after_word, g.by_uid), 6),
|
|
528
|
+
)
|