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/store.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
"""The canonical event store.
|
|
2
|
+
|
|
3
|
+
Writing the parsed run to DuckDB buys two things:
|
|
4
|
+
|
|
5
|
+
* **SQL over an agent run.** ``select tool_name, count(*) from events ...`` is
|
|
6
|
+
a better interface than any fixed dashboard, and it is the natural home for
|
|
7
|
+
questions this tool's authors did not think of.
|
|
8
|
+
* **A replay substrate.** Once the canonical events are stored, the findings
|
|
9
|
+
can be re-derived without the original trace file and without a model call.
|
|
10
|
+
:mod:`blackbox.replay` does exactly that, and the determinism test asserts
|
|
11
|
+
the result is byte-identical.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import json
|
|
17
|
+
from typing import TYPE_CHECKING, Any
|
|
18
|
+
|
|
19
|
+
from blackbox.events import Event, Usage, parse_ts
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING: # pragma: no cover
|
|
22
|
+
from blackbox.analysis import Analysis
|
|
23
|
+
|
|
24
|
+
EVENT_COLUMNS = (
|
|
25
|
+
"uid",
|
|
26
|
+
"seq",
|
|
27
|
+
"kind",
|
|
28
|
+
"parent_uid",
|
|
29
|
+
"ts",
|
|
30
|
+
"is_sidechain",
|
|
31
|
+
"branch",
|
|
32
|
+
"model",
|
|
33
|
+
"tool_name",
|
|
34
|
+
"tool_use_id",
|
|
35
|
+
"tool_input",
|
|
36
|
+
"tool_ok",
|
|
37
|
+
"tool_output",
|
|
38
|
+
"text",
|
|
39
|
+
"flags",
|
|
40
|
+
"raw_type",
|
|
41
|
+
"source_line",
|
|
42
|
+
"input_tokens",
|
|
43
|
+
"output_tokens",
|
|
44
|
+
"cache_read_tokens",
|
|
45
|
+
"cache_write_5m_tokens",
|
|
46
|
+
"cache_write_1h_tokens",
|
|
47
|
+
"thinking_tokens",
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
_SCHEMA = """
|
|
51
|
+
create table events (
|
|
52
|
+
uid text, seq bigint, kind text, parent_uid text, ts text,
|
|
53
|
+
is_sidechain boolean, branch text, model text,
|
|
54
|
+
tool_name text, tool_use_id text, tool_input text, tool_ok boolean,
|
|
55
|
+
tool_output text, text text, flags text, raw_type text, source_line bigint,
|
|
56
|
+
input_tokens bigint, output_tokens bigint, cache_read_tokens bigint,
|
|
57
|
+
cache_write_5m_tokens bigint, cache_write_1h_tokens bigint, thinking_tokens bigint
|
|
58
|
+
);
|
|
59
|
+
create table findings (
|
|
60
|
+
detector text, severity text, title text, detail text, key text,
|
|
61
|
+
branch text, count bigint, evidence text, metrics text
|
|
62
|
+
);
|
|
63
|
+
create table cost_by_model (
|
|
64
|
+
model text, calls bigint, priced boolean,
|
|
65
|
+
input_tokens bigint, output_tokens bigint, cache_read_tokens bigint,
|
|
66
|
+
cache_write_5m_tokens bigint, cache_write_1h_tokens bigint, thinking_tokens bigint,
|
|
67
|
+
input_usd double, output_usd double, cache_read_usd double,
|
|
68
|
+
cache_write_usd double, total_usd double
|
|
69
|
+
);
|
|
70
|
+
create table run_meta (key text, value text);
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _connect(path: str):
|
|
75
|
+
try:
|
|
76
|
+
import duckdb
|
|
77
|
+
except ModuleNotFoundError as exc: # pragma: no cover
|
|
78
|
+
raise RuntimeError(
|
|
79
|
+
"duckdb is required for --db. Install it with: pip install duckdb"
|
|
80
|
+
) from exc
|
|
81
|
+
return duckdb.connect(path)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def write(path: str, analysis: "Analysis") -> None:
|
|
85
|
+
"""Write events, findings and cost to a fresh DuckDB file at ``path``."""
|
|
86
|
+
import os
|
|
87
|
+
|
|
88
|
+
if os.path.exists(path):
|
|
89
|
+
os.remove(path)
|
|
90
|
+
|
|
91
|
+
con = _connect(path)
|
|
92
|
+
try:
|
|
93
|
+
con.execute(_SCHEMA)
|
|
94
|
+
|
|
95
|
+
rows = [tuple(e.to_row()[c] for c in EVENT_COLUMNS) for e in analysis.graph.events]
|
|
96
|
+
if rows:
|
|
97
|
+
placeholders = ",".join("?" * len(EVENT_COLUMNS))
|
|
98
|
+
con.executemany(f"insert into events values ({placeholders})", rows)
|
|
99
|
+
|
|
100
|
+
finding_rows = [
|
|
101
|
+
(
|
|
102
|
+
f.detector,
|
|
103
|
+
f.severity,
|
|
104
|
+
f.title,
|
|
105
|
+
f.detail,
|
|
106
|
+
f.key,
|
|
107
|
+
f.branch,
|
|
108
|
+
f.count,
|
|
109
|
+
json.dumps(list(f.evidence)),
|
|
110
|
+
json.dumps({k: f.metrics[k] for k in sorted(f.metrics)}, default=str),
|
|
111
|
+
)
|
|
112
|
+
for f in analysis.findings
|
|
113
|
+
]
|
|
114
|
+
if finding_rows:
|
|
115
|
+
con.executemany("insert into findings values (?,?,?,?,?,?,?,?,?)", finding_rows)
|
|
116
|
+
|
|
117
|
+
cost_rows = [
|
|
118
|
+
(
|
|
119
|
+
mc.model,
|
|
120
|
+
mc.calls,
|
|
121
|
+
mc.priced,
|
|
122
|
+
mc.usage.input_tokens,
|
|
123
|
+
mc.usage.output_tokens,
|
|
124
|
+
mc.usage.cache_read_tokens,
|
|
125
|
+
mc.usage.cache_write_5m_tokens,
|
|
126
|
+
mc.usage.cache_write_1h_tokens,
|
|
127
|
+
mc.usage.thinking_tokens,
|
|
128
|
+
mc.input_usd,
|
|
129
|
+
mc.output_usd,
|
|
130
|
+
mc.cache_read_usd,
|
|
131
|
+
mc.cache_write_usd,
|
|
132
|
+
mc.total_usd,
|
|
133
|
+
)
|
|
134
|
+
for mc in analysis.cost.by_model
|
|
135
|
+
]
|
|
136
|
+
if cost_rows:
|
|
137
|
+
con.executemany(
|
|
138
|
+
"insert into cost_by_model values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)", cost_rows
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
meta_rows = [
|
|
142
|
+
("source", analysis.trace.source),
|
|
143
|
+
("adapter", analysis.trace.adapter),
|
|
144
|
+
("skipped_lines", str(analysis.trace.skipped_lines)),
|
|
145
|
+
("config", json.dumps(analysis.config.to_dict(), sort_keys=True)),
|
|
146
|
+
("pricing_as_of", analysis.cost.pricing_as_of),
|
|
147
|
+
("price_overrides", json.dumps(analysis.price_overrides, sort_keys=True)),
|
|
148
|
+
]
|
|
149
|
+
meta_rows += [
|
|
150
|
+
(f"trace.{k}", json.dumps(v, sort_keys=True, default=str))
|
|
151
|
+
for k, v in sorted(analysis.trace.meta.items())
|
|
152
|
+
]
|
|
153
|
+
con.executemany("insert into run_meta values (?,?)", meta_rows)
|
|
154
|
+
finally:
|
|
155
|
+
con.close()
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def read_events(path: str) -> list[Event]:
|
|
159
|
+
"""Reconstruct canonical events from a stored run.
|
|
160
|
+
|
|
161
|
+
The round trip must be lossless for everything a detector reads, which is
|
|
162
|
+
why the store keeps tool output in full and why ``flags`` survives as a
|
|
163
|
+
list rather than a formatted string.
|
|
164
|
+
"""
|
|
165
|
+
con = _connect(path)
|
|
166
|
+
try:
|
|
167
|
+
cols = ",".join(EVENT_COLUMNS)
|
|
168
|
+
rows = con.execute(f"select {cols} from events order by seq").fetchall()
|
|
169
|
+
finally:
|
|
170
|
+
con.close()
|
|
171
|
+
|
|
172
|
+
events: list[Event] = []
|
|
173
|
+
for row in rows:
|
|
174
|
+
d: dict[str, Any] = dict(zip(EVENT_COLUMNS, row))
|
|
175
|
+
usage = Usage(
|
|
176
|
+
input_tokens=int(d["input_tokens"] or 0),
|
|
177
|
+
output_tokens=int(d["output_tokens"] or 0),
|
|
178
|
+
cache_read_tokens=int(d["cache_read_tokens"] or 0),
|
|
179
|
+
cache_write_5m_tokens=int(d["cache_write_5m_tokens"] or 0),
|
|
180
|
+
cache_write_1h_tokens=int(d["cache_write_1h_tokens"] or 0),
|
|
181
|
+
thinking_tokens=int(d["thinking_tokens"] or 0),
|
|
182
|
+
)
|
|
183
|
+
flags = tuple(f for f in (d["flags"] or "").split(",") if f)
|
|
184
|
+
events.append(
|
|
185
|
+
Event(
|
|
186
|
+
uid=d["uid"],
|
|
187
|
+
seq=int(d["seq"]),
|
|
188
|
+
kind=d["kind"],
|
|
189
|
+
parent_uid=d["parent_uid"],
|
|
190
|
+
ts=parse_ts(d["ts"]),
|
|
191
|
+
is_sidechain=bool(d["is_sidechain"]),
|
|
192
|
+
branch=d["branch"],
|
|
193
|
+
model=d["model"],
|
|
194
|
+
usage=usage,
|
|
195
|
+
tool_name=d["tool_name"],
|
|
196
|
+
tool_use_id=d["tool_use_id"],
|
|
197
|
+
tool_input=json.loads(d["tool_input"]) if d["tool_input"] else {},
|
|
198
|
+
tool_ok=d["tool_ok"],
|
|
199
|
+
tool_output=d["tool_output"] or "",
|
|
200
|
+
text=d["text"] or "",
|
|
201
|
+
flags=flags,
|
|
202
|
+
raw_type=d["raw_type"] or "",
|
|
203
|
+
source_line=int(d["source_line"] or 0),
|
|
204
|
+
)
|
|
205
|
+
)
|
|
206
|
+
return events
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def read_meta(path: str) -> dict[str, str]:
|
|
210
|
+
con = _connect(path)
|
|
211
|
+
try:
|
|
212
|
+
rows = con.execute("select key, value from run_meta").fetchall()
|
|
213
|
+
finally:
|
|
214
|
+
con.close()
|
|
215
|
+
return {k: v for k, v in rows}
|
blackbox/toolinfo.py
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
"""What a tool call actually touches.
|
|
2
|
+
|
|
3
|
+
The detectors need to know, for an arbitrary tool, whether it read a file or
|
|
4
|
+
wrote one and which path it operated on. Keeping that knowledge in one small
|
|
5
|
+
table means adding a tool is a one-line change, and an unrecognised tool
|
|
6
|
+
degrades to "we don't know what this touched" rather than to a wrong answer.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
# tool name -> the input key holding the path it operates on
|
|
15
|
+
PATH_KEYS: dict[str, tuple[str, ...]] = {
|
|
16
|
+
"Read": ("file_path",),
|
|
17
|
+
"Edit": ("file_path",),
|
|
18
|
+
"Write": ("file_path",),
|
|
19
|
+
"NotebookEdit": ("notebook_path",),
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
READ_TOOLS = frozenset({"Read"})
|
|
23
|
+
WRITE_TOOLS = frozenset({"Edit", "Write", "NotebookEdit"})
|
|
24
|
+
|
|
25
|
+
# Tools that edit *existing* content, so operating without having read the file
|
|
26
|
+
# is suspicious. ``Write`` is excluded on purpose: creating a new file without
|
|
27
|
+
# reading it first is the normal case, and flagging it would bury the signal.
|
|
28
|
+
EDIT_IN_PLACE_TOOLS = frozenset({"Edit", "NotebookEdit"})
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# How a call touches a file. ``read`` observes it, ``write`` replaces or
|
|
32
|
+
# creates it (so the agent knows the contents afterwards either way), ``edit``
|
|
33
|
+
# changes it in place (so the agent needs to have known them beforehand).
|
|
34
|
+
READ = "read"
|
|
35
|
+
WRITE = "write"
|
|
36
|
+
EDIT = "edit"
|
|
37
|
+
|
|
38
|
+
# Some tools touch several files in one call -- a patch tool is the obvious
|
|
39
|
+
# case. The adapter normalises those into this list so the detectors never
|
|
40
|
+
# have to know which agent produced the trace.
|
|
41
|
+
MULTI_FILE_KEY = "files"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def file_operations(tool_name: str | None, tool_input: dict[str, Any]) -> list[tuple[str, str]]:
|
|
45
|
+
"""Every (path, kind) this call touches.
|
|
46
|
+
|
|
47
|
+
Returning a list rather than one path is what lets a patch-style tool --
|
|
48
|
+
one call that adds two files and updates a third -- be understood by the
|
|
49
|
+
same detectors that handle single-file edits.
|
|
50
|
+
"""
|
|
51
|
+
if not tool_name:
|
|
52
|
+
return []
|
|
53
|
+
|
|
54
|
+
entries = tool_input.get(MULTI_FILE_KEY)
|
|
55
|
+
if isinstance(entries, list):
|
|
56
|
+
operations = []
|
|
57
|
+
for entry in entries:
|
|
58
|
+
if not isinstance(entry, dict):
|
|
59
|
+
continue
|
|
60
|
+
path = entry.get("path")
|
|
61
|
+
kind = entry.get("op")
|
|
62
|
+
if isinstance(path, str) and path and kind in (READ, WRITE, EDIT):
|
|
63
|
+
operations.append((path, kind))
|
|
64
|
+
return operations
|
|
65
|
+
|
|
66
|
+
path = None
|
|
67
|
+
for key in PATH_KEYS.get(tool_name, ()):
|
|
68
|
+
value = tool_input.get(key)
|
|
69
|
+
if isinstance(value, str) and value:
|
|
70
|
+
path = value
|
|
71
|
+
break
|
|
72
|
+
if path is None:
|
|
73
|
+
return []
|
|
74
|
+
|
|
75
|
+
if tool_name in READ_TOOLS:
|
|
76
|
+
return [(path, READ)]
|
|
77
|
+
if tool_name in EDIT_IN_PLACE_TOOLS:
|
|
78
|
+
return [(path, EDIT)]
|
|
79
|
+
if tool_name in WRITE_TOOLS:
|
|
80
|
+
return [(path, WRITE)]
|
|
81
|
+
return []
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def target_path(tool_name: str | None, tool_input: dict[str, Any]) -> str | None:
|
|
85
|
+
"""The first file path a call operates on, or ``None``."""
|
|
86
|
+
operations = file_operations(tool_name, tool_input)
|
|
87
|
+
return operations[0][0] if operations else None
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def is_read(tool_name: str | None) -> bool:
|
|
91
|
+
return tool_name in READ_TOOLS
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def is_write(tool_name: str | None) -> bool:
|
|
95
|
+
return tool_name in WRITE_TOOLS
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def is_edit_in_place(tool_name: str | None) -> bool:
|
|
99
|
+
return tool_name in EDIT_IN_PLACE_TOOLS
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
# Tools whose job is to *observe*. Calling one repeatedly with identical input
|
|
103
|
+
# is polling -- watching a screen, re-reading a log -- and is normal behaviour.
|
|
104
|
+
# Calling an *acting* tool repeatedly with identical input is a retry loop.
|
|
105
|
+
# Conflating the two was the single biggest source of false positives when
|
|
106
|
+
# this was first run against real traces.
|
|
107
|
+
OBSERVATION_TOOLS = frozenset(
|
|
108
|
+
{"Read", "Glob", "Grep", "ToolSearch", "WebFetch", "WebSearch", "NotebookRead"}
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
# Substrings that mark an MCP tool as an observer regardless of its server.
|
|
112
|
+
OBSERVATION_NAME_HINTS = (
|
|
113
|
+
"read_page",
|
|
114
|
+
"get_page_text",
|
|
115
|
+
"read_terminal",
|
|
116
|
+
"read_console",
|
|
117
|
+
"read_network",
|
|
118
|
+
"screenshot",
|
|
119
|
+
"tabs_context",
|
|
120
|
+
"list_",
|
|
121
|
+
"get_status",
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
# For multiplexed tools (one name, many actions) the action decides.
|
|
125
|
+
OBSERVATION_ACTIONS = frozenset({"screenshot", "wait", "scroll", "zoom", "hover", "read"})
|
|
126
|
+
|
|
127
|
+
# Progress bookkeeping: tools whose whole job is to be called again with the
|
|
128
|
+
# same payload. Advancing a task list with {"advance": true} ten times is the
|
|
129
|
+
# tool working exactly as designed, not an agent stuck in a loop.
|
|
130
|
+
BOOKKEEPING_NAME_HINTS = ("update_plan", "todowrite", "wrap_up", "mark_chapter", "set_status")
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def repeats_by_design(tool_name: str | None, tool_input: dict[str, Any]) -> bool:
|
|
134
|
+
"""True when the same call recurring with identical input is expected.
|
|
135
|
+
|
|
136
|
+
Two families qualify: tools that *observe* (a screenshot returns something
|
|
137
|
+
new each time by definition) and tools that record *progress* (the payload
|
|
138
|
+
repeats because the step pointer, not the argument, is what moves).
|
|
139
|
+
Treating either as a retry loop was the largest source of false positives
|
|
140
|
+
when this was first run across a real corpus.
|
|
141
|
+
"""
|
|
142
|
+
if not tool_name:
|
|
143
|
+
return False
|
|
144
|
+
if tool_name in OBSERVATION_TOOLS:
|
|
145
|
+
return True
|
|
146
|
+
lowered = tool_name.lower()
|
|
147
|
+
if any(hint in lowered for hint in OBSERVATION_NAME_HINTS):
|
|
148
|
+
return True
|
|
149
|
+
if any(hint in lowered for hint in BOOKKEEPING_NAME_HINTS):
|
|
150
|
+
return True
|
|
151
|
+
action = tool_input.get("action")
|
|
152
|
+
return isinstance(action, str) and action in OBSERVATION_ACTIONS
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
# Kept as the older name used by callers that only care about observation.
|
|
156
|
+
is_observation = repeats_by_design
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
# Tools that exist to wait for a human. Time spent in one is the human reading
|
|
160
|
+
# and typing, not the agent hanging, so it must never be reported as a stall.
|
|
161
|
+
HUMAN_IN_THE_LOOP_TOOLS = frozenset(
|
|
162
|
+
{"AskUserQuestion", "ExitPlanMode", "EnterPlanMode", "mcp__ccd_turn__wrap_up"}
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
# A declined tool call is a human saying no. It is not a tool failure, and
|
|
166
|
+
# clustering it with real errors buries the real errors.
|
|
167
|
+
_DECLINE_MARKERS = (
|
|
168
|
+
"the user doesn't want to proceed",
|
|
169
|
+
"the user does not want to proceed",
|
|
170
|
+
"user rejected",
|
|
171
|
+
"user declined",
|
|
172
|
+
"tool use was rejected",
|
|
173
|
+
"permission denied by user",
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def is_human_in_the_loop(tool_name: str | None) -> bool:
|
|
178
|
+
return tool_name in HUMAN_IN_THE_LOOP_TOOLS
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def is_declined(output: str) -> bool:
|
|
182
|
+
"""True when a failed result is a human refusing, not the tool breaking."""
|
|
183
|
+
head = output[:400].lower()
|
|
184
|
+
return any(marker in head for marker in _DECLINE_MARKERS)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
# The first meaningful token of a shell command, used to keep unrelated
|
|
188
|
+
# failures in separate clusters even when their error text collapses.
|
|
189
|
+
# Every tool that runs a shell command, whichever agent issued it. Codex
|
|
190
|
+
# calls it exec_command and names the argument cmd; Claude Code calls it Bash
|
|
191
|
+
# and names it command. Anything keyed to one spelling silently does nothing
|
|
192
|
+
# on the other agent's traces.
|
|
193
|
+
SHELL_TOOLS = frozenset({"Bash", "exec_command"})
|
|
194
|
+
|
|
195
|
+
_SHELL_NOISE = frozenset(
|
|
196
|
+
{"cd", "sudo", "env", "time", "nohup", "exec", "command", "builtin", "nice", "xargs", "then", "do"}
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
_RUNNERS = frozenset(
|
|
200
|
+
{"python", "python3", "uv", "uvx", "npx", "poetry", "bun", "npm", "pnpm", "yarn", "cargo", "go"}
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
_SEGMENT_SPLIT = re.compile(r"&&|\|\||[;|\n]")
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def program_hint(tool_name: str | None, tool_input: dict[str, Any]) -> str:
|
|
207
|
+
"""A short label for *what was run*, for grouping failures.
|
|
208
|
+
|
|
209
|
+
Two `Exit code 1` failures from `pytest` and from `npm run build` are not
|
|
210
|
+
the same problem. Without this, a stripped error signature can still make
|
|
211
|
+
them look identical.
|
|
212
|
+
|
|
213
|
+
Shell plumbing is skipped: `cd /repo && pytest` is a pytest failure, not a
|
|
214
|
+
cd failure.
|
|
215
|
+
"""
|
|
216
|
+
if tool_name not in SHELL_TOOLS:
|
|
217
|
+
return ""
|
|
218
|
+
command = tool_input.get("command") or tool_input.get("cmd")
|
|
219
|
+
if not isinstance(command, str):
|
|
220
|
+
return ""
|
|
221
|
+
|
|
222
|
+
fallback = ""
|
|
223
|
+
for segment in _SEGMENT_SPLIT.split(command):
|
|
224
|
+
for raw in segment.split():
|
|
225
|
+
token = raw.strip("\\\"'`()$&|;")
|
|
226
|
+
if not token or "=" in token or token.startswith("-"):
|
|
227
|
+
continue
|
|
228
|
+
name = token.split("/")[-1][:24]
|
|
229
|
+
if name in _SHELL_NOISE:
|
|
230
|
+
break # skip this whole segment, it is plumbing
|
|
231
|
+
# `python -m pytest` is a pytest failure, not a python failure.
|
|
232
|
+
# Runners say nothing on their own, so take what they ran.
|
|
233
|
+
if name in _RUNNERS:
|
|
234
|
+
tokens = segment.split()
|
|
235
|
+
for i, tok in enumerate(tokens):
|
|
236
|
+
if tok in {"-m", "run", "exec"} and i + 1 < len(tokens):
|
|
237
|
+
return f"{name} {tokens[i + 1].split('/')[-1]}"[:32]
|
|
238
|
+
for tok in tokens[1:]:
|
|
239
|
+
if not tok.startswith("-") and "=" not in tok:
|
|
240
|
+
return f"{name} {tok.split('/')[-1]}"[:32]
|
|
241
|
+
return name
|
|
242
|
+
else:
|
|
243
|
+
continue
|
|
244
|
+
return fallback
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
# Agents read files through the shell as often as through a file tool --
|
|
248
|
+
# `sed -n '1,200p' src/app.js` is a read by any sensible reading. Missing that
|
|
249
|
+
# made every later edit of such a file look blind: on the Codex corpus, 84 of
|
|
250
|
+
# 84 blind-edit findings had a shell read of the same file beforehand.
|
|
251
|
+
#
|
|
252
|
+
# These paths deliberately do NOT become canonical read operations. A shell
|
|
253
|
+
# read returns a slice, formatted however the command chose, so hashing it and
|
|
254
|
+
# comparing against a later read would invent stale-read findings. They are
|
|
255
|
+
# used only to answer "has this agent seen this file at all?".
|
|
256
|
+
SHELL_READ_COMMANDS = frozenset(
|
|
257
|
+
{"cat", "head", "tail", "sed", "nl", "less", "more", "bat", "view", "rg", "grep", "awk"}
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
_SHELL_SPLIT = re.compile(r"&&|\|\||[;|\n]")
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
# A filename, possibly with directories. Deliberately excludes things that
|
|
264
|
+
# are arguments rather than paths: sed scripts (`1,200p`), line numbers, and
|
|
265
|
+
# anything with shell metacharacters.
|
|
266
|
+
_PATHLIKE = re.compile(r"[A-Za-z_][A-Za-z0-9._\-/]*\Z")
|
|
267
|
+
|
|
268
|
+
# These take a pattern before the filenames, which must not be read as a path.
|
|
269
|
+
_PATTERN_FIRST = frozenset({"rg", "grep", "awk"})
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _looks_like_path(token: str) -> bool:
|
|
273
|
+
if not token or token.startswith("-"):
|
|
274
|
+
return False
|
|
275
|
+
if token in {".", "..", "*"}:
|
|
276
|
+
return False
|
|
277
|
+
return bool(_PATHLIKE.match(token))
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def shell_read_paths(tool_name: str | None, tool_input: dict[str, Any]) -> list[str]:
|
|
281
|
+
"""File paths a shell command appears to read.
|
|
282
|
+
|
|
283
|
+
Deliberately permissive: over-counting a read only ever suppresses a
|
|
284
|
+
blind-edit report, while under-counting invents one.
|
|
285
|
+
"""
|
|
286
|
+
if tool_name not in SHELL_TOOLS:
|
|
287
|
+
return []
|
|
288
|
+
command = tool_input.get("command") or tool_input.get("cmd")
|
|
289
|
+
if not isinstance(command, str):
|
|
290
|
+
return []
|
|
291
|
+
|
|
292
|
+
paths: list[str] = []
|
|
293
|
+
for segment in _SHELL_SPLIT.split(command):
|
|
294
|
+
tokens = segment.split()
|
|
295
|
+
if not tokens:
|
|
296
|
+
continue
|
|
297
|
+
program = None
|
|
298
|
+
for token in tokens:
|
|
299
|
+
cleaned = token.strip("\\\"'`()$&|;")
|
|
300
|
+
if not cleaned or "=" in cleaned or cleaned.startswith("-"):
|
|
301
|
+
continue
|
|
302
|
+
program = cleaned.split("/")[-1]
|
|
303
|
+
break
|
|
304
|
+
if program not in SHELL_READ_COMMANDS:
|
|
305
|
+
continue
|
|
306
|
+
skip_pattern = program in _PATTERN_FIRST
|
|
307
|
+
started = False
|
|
308
|
+
for token in tokens:
|
|
309
|
+
cleaned = token.strip("\\\"'`()$&|;<>")
|
|
310
|
+
if not started:
|
|
311
|
+
# Skip forward to just past the command name itself.
|
|
312
|
+
started = cleaned.split("/")[-1] == program
|
|
313
|
+
continue
|
|
314
|
+
if cleaned.startswith("-") or "=" in cleaned:
|
|
315
|
+
continue
|
|
316
|
+
if skip_pattern:
|
|
317
|
+
skip_pattern = False # that was the search pattern, not a file
|
|
318
|
+
continue
|
|
319
|
+
if _looks_like_path(cleaned):
|
|
320
|
+
paths.append(cleaned)
|
|
321
|
+
return paths
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def paths_overlap(a: str, b: str) -> bool:
|
|
325
|
+
"""True when two paths plausibly name the same file.
|
|
326
|
+
|
|
327
|
+
A shell command usually names a file relative to the working directory
|
|
328
|
+
while a patch names it absolutely, so the comparison is on trailing path
|
|
329
|
+
components rather than on the strings.
|
|
330
|
+
"""
|
|
331
|
+
left = [part for part in a.split("/") if part and part != "."]
|
|
332
|
+
right = [part for part in b.split("/") if part and part != "."]
|
|
333
|
+
if not left or not right:
|
|
334
|
+
return False
|
|
335
|
+
shorter, longer = (left, right) if len(left) <= len(right) else (right, left)
|
|
336
|
+
return longer[-len(shorter):] == shorter
|