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
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
"""Adapter for OpenAI Codex CLI rollouts (``~/.codex/sessions/**/rollout-*.jsonl``).
|
|
2
|
+
|
|
3
|
+
Written to answer a fair challenge: a canonical model designed against one
|
|
4
|
+
vendor's logs has not been shown to be canonical. This adapter exists to test
|
|
5
|
+
that claim against a format that differs from Claude Code's in every surface
|
|
6
|
+
detail -- and it required no change to the graph, the cost engine, or any
|
|
7
|
+
detector.
|
|
8
|
+
|
|
9
|
+
What differs, and how it maps:
|
|
10
|
+
|
|
11
|
+
* **No parent pointers.** Codex rollouts are a flat sequence, so the causal
|
|
12
|
+
spine is rebuilt from ``call_id`` and from turn order rather than read off
|
|
13
|
+
the rows.
|
|
14
|
+
* **Usage is cumulative, not per-turn.** ``token_count`` events carry a
|
|
15
|
+
running ``total_token_usage``. Summing the per-request ``last_token_usage``
|
|
16
|
+
double counts -- verified against this corpus, where it overstated output
|
|
17
|
+
tokens by about 5% -- so each turn's usage is the delta between consecutive
|
|
18
|
+
cumulative readings.
|
|
19
|
+
* **Input tokens include cached ones.** OpenAI reports ``input_tokens`` as the
|
|
20
|
+
total and ``cached_input_tokens`` as the share served from cache, so fresh
|
|
21
|
+
input is the difference. There is no separate cache-write charge, so those
|
|
22
|
+
tiers stay zero rather than being invented.
|
|
23
|
+
* **One patch call edits many files.** ``apply_patch`` is normalised into the
|
|
24
|
+
canonical multi-file operation list, which is why ``thrash`` and
|
|
25
|
+
``contradiction`` work on Codex traces unchanged.
|
|
26
|
+
* **Compaction is recorded.** Codex writes a row when it summarises and clears
|
|
27
|
+
the context. That boundary is kept, because a tool result dumped before one
|
|
28
|
+
stops being re-sent after it -- which is the difference between an estimate
|
|
29
|
+
and a guess in :mod:`blackbox.detectors.context_bloat`.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
from __future__ import annotations
|
|
33
|
+
|
|
34
|
+
import json
|
|
35
|
+
import re
|
|
36
|
+
from typing import Any
|
|
37
|
+
|
|
38
|
+
from blackbox.adapters._linking import link_results_to_calls
|
|
39
|
+
from blackbox.adapters.base import Trace
|
|
40
|
+
from blackbox.events import (
|
|
41
|
+
ASSISTANT_MESSAGE,
|
|
42
|
+
META,
|
|
43
|
+
TOOL_CALL,
|
|
44
|
+
TOOL_RESULT,
|
|
45
|
+
USER_MESSAGE,
|
|
46
|
+
Event,
|
|
47
|
+
Usage,
|
|
48
|
+
parse_ts,
|
|
49
|
+
)
|
|
50
|
+
from blackbox.toolinfo import EDIT, MULTI_FILE_KEY, WRITE
|
|
51
|
+
|
|
52
|
+
NAME = "codex"
|
|
53
|
+
|
|
54
|
+
_ROW_TYPES = {"session_meta", "response_item", "event_msg", "turn_context", "compacted"}
|
|
55
|
+
|
|
56
|
+
# Marks a point where the context window was summarised and cleared.
|
|
57
|
+
# Anything carried before it stops being re-sent afterwards.
|
|
58
|
+
COMPACTION_FLAG = "compaction"
|
|
59
|
+
|
|
60
|
+
_EXIT = re.compile(r"process exited with code (\d+)", re.I)
|
|
61
|
+
_PATCH_OP = re.compile(r"^\*\*\*\s+(Add|Update|Delete)\s+File:\s*(.+?)\s*$", re.M)
|
|
62
|
+
|
|
63
|
+
_USAGE_FIELDS = (
|
|
64
|
+
"input_tokens",
|
|
65
|
+
"cached_input_tokens",
|
|
66
|
+
"output_tokens",
|
|
67
|
+
"reasoning_output_tokens",
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def sniff(path: str) -> bool:
|
|
72
|
+
"""True when the first usable line looks like a Codex rollout row."""
|
|
73
|
+
try:
|
|
74
|
+
with open(path, "r", encoding="utf-8", errors="replace") as fh:
|
|
75
|
+
for _ in range(20):
|
|
76
|
+
line = fh.readline()
|
|
77
|
+
if not line:
|
|
78
|
+
break
|
|
79
|
+
line = line.strip()
|
|
80
|
+
if not line:
|
|
81
|
+
continue
|
|
82
|
+
try:
|
|
83
|
+
row = json.loads(line)
|
|
84
|
+
except json.JSONDecodeError:
|
|
85
|
+
return False
|
|
86
|
+
if not isinstance(row, dict):
|
|
87
|
+
return False
|
|
88
|
+
return row.get("type") in _ROW_TYPES and isinstance(row.get("payload"), dict)
|
|
89
|
+
except OSError:
|
|
90
|
+
return False
|
|
91
|
+
return False
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _delta_usage(current: dict[str, Any], previous: dict[str, int]) -> tuple[Usage, dict[str, int]]:
|
|
95
|
+
"""Per-turn usage from two cumulative readings.
|
|
96
|
+
|
|
97
|
+
A decrease would mean the counter restarted; the reading is then taken as
|
|
98
|
+
the delta rather than producing a negative, which would silently subtract
|
|
99
|
+
from the run's total.
|
|
100
|
+
"""
|
|
101
|
+
latest = {field: int(current.get(field) or 0) for field in _USAGE_FIELDS}
|
|
102
|
+
delta = {}
|
|
103
|
+
for field, value in latest.items():
|
|
104
|
+
previous_value = previous.get(field, 0)
|
|
105
|
+
delta[field] = value - previous_value if value >= previous_value else value
|
|
106
|
+
|
|
107
|
+
cached = delta["cached_input_tokens"]
|
|
108
|
+
total_input = delta["input_tokens"]
|
|
109
|
+
return (
|
|
110
|
+
Usage(
|
|
111
|
+
# OpenAI counts cached tokens inside input_tokens, so fresh input
|
|
112
|
+
# is the remainder. There is no cache-write charge to record.
|
|
113
|
+
input_tokens=max(total_input - cached, 0),
|
|
114
|
+
output_tokens=delta["output_tokens"],
|
|
115
|
+
cache_read_tokens=cached,
|
|
116
|
+
thinking_tokens=delta["reasoning_output_tokens"],
|
|
117
|
+
),
|
|
118
|
+
latest,
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _patch_files(patch: str) -> list[dict[str, str]]:
|
|
123
|
+
"""The files an ``apply_patch`` call touches, with how it touches each."""
|
|
124
|
+
operations = []
|
|
125
|
+
for verb, path in _PATCH_OP.findall(patch or ""):
|
|
126
|
+
# Adding or deleting replaces the file wholesale, so the agent knows
|
|
127
|
+
# the result either way; updating edits content it must already know.
|
|
128
|
+
operations.append({"path": path.strip(), "op": EDIT if verb == "Update" else WRITE})
|
|
129
|
+
return operations
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _result_ok(output: str) -> bool | None:
|
|
133
|
+
"""Whether a tool result reports success, or None when it does not say."""
|
|
134
|
+
if not output:
|
|
135
|
+
return None
|
|
136
|
+
head = output[:800]
|
|
137
|
+
match = _EXIT.search(head)
|
|
138
|
+
if match:
|
|
139
|
+
return match.group(1) == "0"
|
|
140
|
+
lowered = head.lower()
|
|
141
|
+
if "failed for" in lowered or lowered.startswith("error") or '"error"' in lowered:
|
|
142
|
+
return False
|
|
143
|
+
if "success." in lowered:
|
|
144
|
+
return True
|
|
145
|
+
return None
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _text_of(content: Any) -> str:
|
|
149
|
+
if isinstance(content, str):
|
|
150
|
+
return content
|
|
151
|
+
if isinstance(content, list):
|
|
152
|
+
parts = []
|
|
153
|
+
for block in content:
|
|
154
|
+
if isinstance(block, dict) and isinstance(block.get("text"), str):
|
|
155
|
+
parts.append(block["text"])
|
|
156
|
+
return "\n".join(parts)
|
|
157
|
+
return ""
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def parse(path: str) -> Trace:
|
|
161
|
+
events: list[Event] = []
|
|
162
|
+
seq = 0
|
|
163
|
+
skipped = 0
|
|
164
|
+
model: str | None = None
|
|
165
|
+
cwd: str | None = None
|
|
166
|
+
session_id: str | None = None
|
|
167
|
+
cli_version: str | None = None
|
|
168
|
+
previous_usage: dict[str, int] = {}
|
|
169
|
+
last_turn_uid: str | None = None
|
|
170
|
+
|
|
171
|
+
def add(event: Event) -> Event:
|
|
172
|
+
nonlocal seq
|
|
173
|
+
events.append(event)
|
|
174
|
+
seq += 1
|
|
175
|
+
return event
|
|
176
|
+
|
|
177
|
+
with open(path, "r", encoding="utf-8", errors="replace") as fh:
|
|
178
|
+
for lineno, line in enumerate(fh, start=1):
|
|
179
|
+
line = line.strip()
|
|
180
|
+
if not line:
|
|
181
|
+
continue
|
|
182
|
+
try:
|
|
183
|
+
row = json.loads(line)
|
|
184
|
+
except json.JSONDecodeError:
|
|
185
|
+
skipped += 1
|
|
186
|
+
continue
|
|
187
|
+
if not isinstance(row, dict):
|
|
188
|
+
skipped += 1
|
|
189
|
+
continue
|
|
190
|
+
|
|
191
|
+
payload = row.get("payload")
|
|
192
|
+
payload = payload if isinstance(payload, dict) else {}
|
|
193
|
+
row_type = str(row.get("type") or "unknown")
|
|
194
|
+
sub_type = str(payload.get("type") or "")
|
|
195
|
+
ts = parse_ts(row.get("timestamp"))
|
|
196
|
+
|
|
197
|
+
if row_type == "session_meta":
|
|
198
|
+
session_id = session_id or payload.get("id")
|
|
199
|
+
cwd = cwd or payload.get("cwd")
|
|
200
|
+
cli_version = cli_version or payload.get("cli_version")
|
|
201
|
+
model = payload.get("model") or model
|
|
202
|
+
add(Event(uid=f"line{lineno}", seq=seq, kind=META, ts=ts,
|
|
203
|
+
raw_type=row_type, source_line=lineno))
|
|
204
|
+
continue
|
|
205
|
+
|
|
206
|
+
if row_type == "turn_context":
|
|
207
|
+
# The model can change between turns; later turns bill at the
|
|
208
|
+
# new rate, so this is tracked rather than read once.
|
|
209
|
+
model = payload.get("model") or model
|
|
210
|
+
cwd = cwd or payload.get("cwd")
|
|
211
|
+
add(Event(uid=f"line{lineno}", seq=seq, kind=META, ts=ts,
|
|
212
|
+
raw_type=row_type, source_line=lineno))
|
|
213
|
+
continue
|
|
214
|
+
|
|
215
|
+
if row_type == "compacted" or (
|
|
216
|
+
row_type == "event_msg" and sub_type == "context_compacted"
|
|
217
|
+
):
|
|
218
|
+
add(Event(uid=f"line{lineno}", seq=seq, kind=META, ts=ts,
|
|
219
|
+
flags=(COMPACTION_FLAG,), raw_type="compacted",
|
|
220
|
+
source_line=lineno))
|
|
221
|
+
continue
|
|
222
|
+
|
|
223
|
+
if row_type == "event_msg":
|
|
224
|
+
if sub_type == "token_count":
|
|
225
|
+
info = payload.get("info")
|
|
226
|
+
if isinstance(info, dict):
|
|
227
|
+
total = info.get("total_token_usage")
|
|
228
|
+
if isinstance(total, dict):
|
|
229
|
+
usage, previous_usage = _delta_usage(total, previous_usage)
|
|
230
|
+
if not usage.is_empty():
|
|
231
|
+
turn = add(
|
|
232
|
+
Event(
|
|
233
|
+
uid=f"line{lineno}",
|
|
234
|
+
seq=seq,
|
|
235
|
+
kind=ASSISTANT_MESSAGE,
|
|
236
|
+
ts=ts,
|
|
237
|
+
model=model,
|
|
238
|
+
usage=usage,
|
|
239
|
+
raw_type="token_count",
|
|
240
|
+
source_line=lineno,
|
|
241
|
+
)
|
|
242
|
+
)
|
|
243
|
+
last_turn_uid = turn.uid
|
|
244
|
+
continue
|
|
245
|
+
add(Event(uid=f"line{lineno}", seq=seq, kind=META, ts=ts,
|
|
246
|
+
text=_text_of(payload.get("message"))[:2000],
|
|
247
|
+
raw_type=f"{row_type}/{sub_type}" if sub_type else row_type,
|
|
248
|
+
source_line=lineno))
|
|
249
|
+
continue
|
|
250
|
+
|
|
251
|
+
if row_type != "response_item":
|
|
252
|
+
skipped += 1
|
|
253
|
+
continue
|
|
254
|
+
|
|
255
|
+
if sub_type == "message":
|
|
256
|
+
role = payload.get("role")
|
|
257
|
+
text = _text_of(payload.get("content"))
|
|
258
|
+
kind = USER_MESSAGE if role == "user" else META
|
|
259
|
+
add(Event(uid=f"line{lineno}", seq=seq, kind=kind, ts=ts, text=text[:4000],
|
|
260
|
+
raw_type=f"message/{role}", source_line=lineno))
|
|
261
|
+
continue
|
|
262
|
+
|
|
263
|
+
if sub_type in ("function_call", "custom_tool_call", "web_search_call",
|
|
264
|
+
"tool_search_call"):
|
|
265
|
+
name = payload.get("name") or sub_type
|
|
266
|
+
call_id = payload.get("call_id") or payload.get("id")
|
|
267
|
+
|
|
268
|
+
tool_input: dict[str, Any] = {}
|
|
269
|
+
raw_args = payload.get("arguments")
|
|
270
|
+
if isinstance(raw_args, str):
|
|
271
|
+
try:
|
|
272
|
+
parsed = json.loads(raw_args)
|
|
273
|
+
if isinstance(parsed, dict):
|
|
274
|
+
tool_input = parsed
|
|
275
|
+
except json.JSONDecodeError:
|
|
276
|
+
tool_input = {"arguments": raw_args}
|
|
277
|
+
raw_input = payload.get("input")
|
|
278
|
+
if isinstance(raw_input, str):
|
|
279
|
+
tool_input = {"input": raw_input}
|
|
280
|
+
if name == "apply_patch":
|
|
281
|
+
files = _patch_files(raw_input)
|
|
282
|
+
if files:
|
|
283
|
+
tool_input[MULTI_FILE_KEY] = files
|
|
284
|
+
if isinstance(payload.get("query"), str):
|
|
285
|
+
tool_input.setdefault("query", payload["query"])
|
|
286
|
+
|
|
287
|
+
add(Event(uid=f"line{lineno}", seq=seq, kind=TOOL_CALL, parent_uid=last_turn_uid,
|
|
288
|
+
ts=ts, model=model, tool_name=name, tool_use_id=call_id,
|
|
289
|
+
tool_input=tool_input, raw_type=sub_type, source_line=lineno))
|
|
290
|
+
continue
|
|
291
|
+
|
|
292
|
+
if sub_type in ("function_call_output", "custom_tool_call_output",
|
|
293
|
+
"tool_search_output"):
|
|
294
|
+
output = payload.get("output")
|
|
295
|
+
if not isinstance(output, str):
|
|
296
|
+
output = json.dumps(output, sort_keys=True) if output is not None else ""
|
|
297
|
+
add(Event(uid=f"line{lineno}", seq=seq, kind=TOOL_RESULT,
|
|
298
|
+
parent_uid=last_turn_uid, ts=ts,
|
|
299
|
+
tool_use_id=payload.get("call_id"), tool_ok=_result_ok(output),
|
|
300
|
+
tool_output=output, raw_type=sub_type, source_line=lineno))
|
|
301
|
+
continue
|
|
302
|
+
|
|
303
|
+
add(Event(uid=f"line{lineno}", seq=seq, kind=META, ts=ts,
|
|
304
|
+
raw_type=sub_type or row_type, source_line=lineno))
|
|
305
|
+
|
|
306
|
+
events = link_results_to_calls(events)
|
|
307
|
+
|
|
308
|
+
return Trace(
|
|
309
|
+
events=events,
|
|
310
|
+
source=path,
|
|
311
|
+
adapter=NAME,
|
|
312
|
+
skipped_lines=skipped,
|
|
313
|
+
meta={
|
|
314
|
+
"session_id": session_id,
|
|
315
|
+
"cwd": cwd,
|
|
316
|
+
"client_versions": [cli_version] if cli_version else [],
|
|
317
|
+
},
|
|
318
|
+
)
|
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
"""Adapter for turn-level agent trajectories with published waste labels.
|
|
2
|
+
|
|
3
|
+
This reads the format of the dataset released with *How Do AI Agents Waste
|
|
4
|
+
Your Money?* (Zeng, Lu, Cai et al., 2026; arXiv 2611.07238;
|
|
5
|
+
``huiminz3/How_Do_AI_Agents_Waste_Your_Money`` on Hugging Face, CC BY 4.0).
|
|
6
|
+
Each line of a file is one trajectory::
|
|
7
|
+
|
|
8
|
+
{"trace_id", "model", "harness", "benchmark", "domain", "task_id",
|
|
9
|
+
"solved", "turns": [{"round", "received": {"role", "text"},
|
|
10
|
+
"reasoning", "visible", "action",
|
|
11
|
+
"output_tokens", "reasoning_tokens", "labels"}]}
|
|
12
|
+
|
|
13
|
+
It exists so Agent Black Box can be scored against waste someone else
|
|
14
|
+
labelled. The labels are read by :mod:`blackbox.bench`, never by this module:
|
|
15
|
+
the adapter's job is only to produce the same canonical events every other
|
|
16
|
+
adapter produces, so the detectors run on this data exactly as they run on a
|
|
17
|
+
Claude Code or Codex trace. That separation is what makes the benchmark fair
|
|
18
|
+
-- the detectors cannot see the answers.
|
|
19
|
+
|
|
20
|
+
What this format does not carry, and what that costs:
|
|
21
|
+
|
|
22
|
+
* **No timestamps.** The stall detector needs gaps between events, so it can
|
|
23
|
+
never fire here. That is a limit of the data, not a finding.
|
|
24
|
+
* **No input or cache tokens.** Only output and reasoning tokens are recorded
|
|
25
|
+
per turn, so ``context_bloat`` (which prices re-sent input) is inert and any
|
|
26
|
+
dollar figure would be invented. Costs are not reported for this format.
|
|
27
|
+
* **One observation per turn.** ``received`` is the last message the model saw
|
|
28
|
+
before the turn. When a turn makes several tool calls, only the last call's
|
|
29
|
+
result survives; earlier calls in that turn get no result event rather than
|
|
30
|
+
a guessed one.
|
|
31
|
+
* **Truncated text.** Observations and actions were clipped by the dataset's
|
|
32
|
+
authors (1,500 and 8,000 characters). Two calls that differ only past the
|
|
33
|
+
clip will look identical. Rare, and stated rather than hidden.
|
|
34
|
+
|
|
35
|
+
Tool names differ by harness. A shell call is normalised to the canonical
|
|
36
|
+
``Bash`` with a ``command`` key, and a ``str_replace_editor`` call to the
|
|
37
|
+
canonical multi-file operation list, so ``retry_loop``, ``error_cluster``,
|
|
38
|
+
``thrash`` and ``contradiction`` understand them. An unrecognised tool keeps
|
|
39
|
+
its own name and arguments: it can still repeat, it just cannot be read as a
|
|
40
|
+
file operation.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
from __future__ import annotations
|
|
44
|
+
|
|
45
|
+
import json
|
|
46
|
+
import re
|
|
47
|
+
from typing import Any, Iterator
|
|
48
|
+
|
|
49
|
+
from blackbox.adapters._linking import link_results_to_calls
|
|
50
|
+
from blackbox.adapters.base import Trace
|
|
51
|
+
from blackbox.events import (
|
|
52
|
+
ASSISTANT_MESSAGE,
|
|
53
|
+
TOOL_CALL,
|
|
54
|
+
TOOL_RESULT,
|
|
55
|
+
USER_MESSAGE,
|
|
56
|
+
Event,
|
|
57
|
+
Usage,
|
|
58
|
+
)
|
|
59
|
+
from blackbox.toolinfo import EDIT, MULTI_FILE_KEY, READ, WRITE
|
|
60
|
+
|
|
61
|
+
NAME = "labelled-turns"
|
|
62
|
+
|
|
63
|
+
#: Where a call starts: ``name(`` at the beginning of a line. Arguments are
|
|
64
|
+
#: JSON, which escapes its own newlines, so a new line that opens with a name
|
|
65
|
+
#: and a parenthesis is a new call.
|
|
66
|
+
_CALL_START = re.compile(r"^([A-Za-z_][\w.\-:/]*)\(", re.M)
|
|
67
|
+
_TRUNCATED = " ...[truncated]"
|
|
68
|
+
|
|
69
|
+
SHELL_NAMES = frozenset(
|
|
70
|
+
{"bash", "execute_bash", "shell", "run_shell_command", "terminal", "run_command", "exec"}
|
|
71
|
+
)
|
|
72
|
+
_EDITOR_NAMES = frozenset({"str_replace_editor", "str_replace_based_edit_tool"})
|
|
73
|
+
_EDITOR_OPS = {"view": READ, "create": WRITE, "str_replace": EDIT, "insert": EDIT,
|
|
74
|
+
"undo_edit": EDIT}
|
|
75
|
+
|
|
76
|
+
_RETURNCODE = re.compile(r"<returncode>\s*(-?\d+)\s*</returncode>", re.I)
|
|
77
|
+
_EXIT = re.compile(r"(?:exit code|exited with code|exit status)[:\s]+(-?\d+)", re.I)
|
|
78
|
+
_ERROR_START = re.compile(r"^\s*(error\b|error:|exception\b|traceback \(most recent call last\))",
|
|
79
|
+
re.I)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def sniff(path: str) -> bool:
|
|
83
|
+
"""True when the first line is a trajectory with labelled turns."""
|
|
84
|
+
try:
|
|
85
|
+
with open(path, "r", encoding="utf-8", errors="replace") as fh:
|
|
86
|
+
line = fh.readline().strip()
|
|
87
|
+
except OSError:
|
|
88
|
+
return False
|
|
89
|
+
if not line:
|
|
90
|
+
return False
|
|
91
|
+
try:
|
|
92
|
+
row = json.loads(line)
|
|
93
|
+
except json.JSONDecodeError:
|
|
94
|
+
return False
|
|
95
|
+
return (
|
|
96
|
+
isinstance(row, dict)
|
|
97
|
+
and isinstance(row.get("turns"), list)
|
|
98
|
+
and "trace_id" in row
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
# --- actions -----------------------------------------------------------------
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def split_action(action: str) -> list[tuple[str, dict[str, Any]]]:
|
|
106
|
+
"""Every call in an ``action`` string, as ``(name, arguments)``.
|
|
107
|
+
|
|
108
|
+
The dataset renders a turn's tool calls as ``name(arguments)`` joined by
|
|
109
|
+
newlines. Each call's arguments are decoded as JSON where they start, so a
|
|
110
|
+
newline *inside* an argument cannot split a call in two; only when that
|
|
111
|
+
fails (clipped or non-JSON arguments) does the text fall back to splitting
|
|
112
|
+
on lines that open with ``name(``. Arguments that are not a JSON object
|
|
113
|
+
are kept whole under ``raw`` so the call still has a stable identity for
|
|
114
|
+
repeat detection.
|
|
115
|
+
"""
|
|
116
|
+
if not action or not action.strip():
|
|
117
|
+
return []
|
|
118
|
+
text = action.strip()
|
|
119
|
+
clipped = text.endswith(_TRUNCATED)
|
|
120
|
+
if clipped:
|
|
121
|
+
text = text[: -len(_TRUNCATED)]
|
|
122
|
+
# strict=False: a provider may put a raw newline inside an argument string.
|
|
123
|
+
decoder = json.JSONDecoder(strict=False)
|
|
124
|
+
calls: list[tuple[str, dict[str, Any]]] = []
|
|
125
|
+
pos = 0
|
|
126
|
+
while pos < len(text):
|
|
127
|
+
match = _CALL_START.match(text, pos)
|
|
128
|
+
if not match:
|
|
129
|
+
break
|
|
130
|
+
name, args_at = match.group(1), match.end()
|
|
131
|
+
try:
|
|
132
|
+
if text[args_at:args_at + 1] == ")":
|
|
133
|
+
value, end = {}, args_at
|
|
134
|
+
else:
|
|
135
|
+
value, end = decoder.raw_decode(text, args_at)
|
|
136
|
+
except json.JSONDecodeError:
|
|
137
|
+
break
|
|
138
|
+
if text[end:end + 1] != ")":
|
|
139
|
+
break
|
|
140
|
+
rest = text[end + 1:]
|
|
141
|
+
if rest and not rest.startswith("\n"):
|
|
142
|
+
break
|
|
143
|
+
args = value if isinstance(value, dict) else {"value": value}
|
|
144
|
+
calls.append(_normalise(name, args))
|
|
145
|
+
pos = end + 2
|
|
146
|
+
if pos >= len(text):
|
|
147
|
+
return calls
|
|
148
|
+
return calls + _split_lines(text[pos:], clipped)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _split_lines(text: str, clipped: bool) -> list[tuple[str, dict[str, Any]]]:
|
|
152
|
+
"""The fallback: one call per line that opens with ``name(``."""
|
|
153
|
+
starts = [m.start() for m in _CALL_START.finditer(text)]
|
|
154
|
+
if not starts or starts[0] != 0:
|
|
155
|
+
starts = [0] + starts
|
|
156
|
+
calls = []
|
|
157
|
+
for i, start in enumerate(starts):
|
|
158
|
+
end = starts[i + 1] if i + 1 < len(starts) else len(text)
|
|
159
|
+
chunk = text[start:end].strip()
|
|
160
|
+
match = _CALL_START.match(chunk)
|
|
161
|
+
name = match.group(1) if match else "?"
|
|
162
|
+
body = chunk[match.end():] if match else chunk
|
|
163
|
+
last = i + 1 == len(starts)
|
|
164
|
+
if body.endswith(")") and not (clipped and last):
|
|
165
|
+
body = body[:-1]
|
|
166
|
+
try:
|
|
167
|
+
parsed = json.loads(body) if body.strip() else {}
|
|
168
|
+
args: dict[str, Any] = parsed if isinstance(parsed, dict) else {"value": parsed}
|
|
169
|
+
except json.JSONDecodeError:
|
|
170
|
+
args = {"raw": body}
|
|
171
|
+
if clipped and last:
|
|
172
|
+
args = {**args, "_truncated": True}
|
|
173
|
+
calls.append(_normalise(name, args))
|
|
174
|
+
return calls
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
#: File tools by lower-cased name, across harnesses, and how each touches a file.
|
|
178
|
+
_FILE_TOOLS = {
|
|
179
|
+
"read": READ, "read_file": READ, "readfile": READ, "view": READ,
|
|
180
|
+
"write": WRITE, "write_file": WRITE, "writefile": WRITE, "create_file": WRITE,
|
|
181
|
+
"edit": EDIT, "edit_file": EDIT, "strreplacefile": EDIT, "str_replace": EDIT,
|
|
182
|
+
"apply_edit": EDIT, "multiedit": EDIT,
|
|
183
|
+
}
|
|
184
|
+
_PATH_ARGS = ("file_path", "filePath", "path", "filename")
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _normalise(name: str, args: dict[str, Any]) -> tuple[str, dict[str, Any]]:
|
|
188
|
+
"""Map a harness's tool onto the canonical one the detectors understand."""
|
|
189
|
+
lowered = name.lower()
|
|
190
|
+
if lowered in SHELL_NAMES:
|
|
191
|
+
command = args.get("command", args.get("cmd", args.get("raw")))
|
|
192
|
+
if isinstance(command, list):
|
|
193
|
+
command = " ".join(str(part) for part in command)
|
|
194
|
+
if isinstance(command, str):
|
|
195
|
+
return "Bash", {"command": command}
|
|
196
|
+
return "Bash", args
|
|
197
|
+
path = next((args[k] for k in _PATH_ARGS if isinstance(args.get(k), str) and args[k]), None)
|
|
198
|
+
if path is None:
|
|
199
|
+
return name, args
|
|
200
|
+
if lowered in _EDITOR_NAMES:
|
|
201
|
+
op = _EDITOR_OPS.get(str(args.get("command", "")))
|
|
202
|
+
else:
|
|
203
|
+
op = _FILE_TOOLS.get(lowered)
|
|
204
|
+
if op:
|
|
205
|
+
return name, {**args, MULTI_FILE_KEY: [{"path": path, "op": op}]}
|
|
206
|
+
return name, args
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def result_ok(text: str) -> bool | None:
|
|
210
|
+
"""Whether a tool result reports success, or None when it does not say.
|
|
211
|
+
|
|
212
|
+
Deliberately conservative: an explicit return code decides; otherwise only
|
|
213
|
+
a result that *opens* as an error counts as one. Text that merely mentions
|
|
214
|
+
an error somewhere (a grep hit, a log line) is not a failed call.
|
|
215
|
+
"""
|
|
216
|
+
if not text:
|
|
217
|
+
return None
|
|
218
|
+
head = text[:1500]
|
|
219
|
+
match = _RETURNCODE.search(head) or _EXIT.search(head)
|
|
220
|
+
if match:
|
|
221
|
+
return match.group(1) == "0"
|
|
222
|
+
if _ERROR_START.match(head):
|
|
223
|
+
return False
|
|
224
|
+
return None
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
# --- records -----------------------------------------------------------------
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def _text(value: Any) -> str:
|
|
231
|
+
if isinstance(value, str):
|
|
232
|
+
return value
|
|
233
|
+
if value is None:
|
|
234
|
+
return ""
|
|
235
|
+
return json.dumps(value, ensure_ascii=False, sort_keys=True)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _int(value: Any) -> int:
|
|
239
|
+
try:
|
|
240
|
+
return int(value or 0)
|
|
241
|
+
except (TypeError, ValueError):
|
|
242
|
+
return 0
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def ordered_turns(record: dict[str, Any]) -> list[tuple[int, dict[str, Any]]]:
|
|
246
|
+
"""``(round, turn)`` pairs in round order; a missing round falls back to position."""
|
|
247
|
+
turns = record.get("turns")
|
|
248
|
+
if not isinstance(turns, list):
|
|
249
|
+
return []
|
|
250
|
+
pairs = []
|
|
251
|
+
for position, turn in enumerate(turns):
|
|
252
|
+
if not isinstance(turn, dict):
|
|
253
|
+
continue
|
|
254
|
+
rnd = turn.get("round")
|
|
255
|
+
pairs.append((_int(rnd) if rnd is not None else position + 1, position, turn))
|
|
256
|
+
pairs.sort(key=lambda item: (item[0], item[1]))
|
|
257
|
+
return [(rnd, turn) for rnd, _, turn in pairs]
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def round_of_uid(uid: str) -> int | None:
|
|
261
|
+
"""The round an event uid from this adapter belongs to.
|
|
262
|
+
|
|
263
|
+
A tool result is attributed to the round of the call it answers: the waste
|
|
264
|
+
of a repeated or failed call lives in the turn that made it.
|
|
265
|
+
"""
|
|
266
|
+
found = re.findall(r":r(-?\d+):", uid)
|
|
267
|
+
return int(found[-1]) if found else None
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def parse_record(record: dict[str, Any], source: str = "") -> Trace:
|
|
271
|
+
"""One trajectory record as canonical events."""
|
|
272
|
+
trace_id = str(record.get("trace_id") or "trace")
|
|
273
|
+
model = record.get("model")
|
|
274
|
+
model = str(model) if model else None
|
|
275
|
+
events: list[Event] = []
|
|
276
|
+
seq = 0
|
|
277
|
+
previous_calls: list[Event] = []
|
|
278
|
+
previous_round: int | None = None
|
|
279
|
+
|
|
280
|
+
for rnd, turn in ordered_turns(record):
|
|
281
|
+
prefix = f"{trace_id}:r{rnd}:"
|
|
282
|
+
received = turn.get("received")
|
|
283
|
+
if isinstance(received, dict):
|
|
284
|
+
role = str(received.get("role") or "")
|
|
285
|
+
text = _text(received.get("text"))
|
|
286
|
+
if role == "tool" and previous_calls:
|
|
287
|
+
call = previous_calls[-1]
|
|
288
|
+
ok = result_ok(text)
|
|
289
|
+
# Attributed to the call's round, not this one: see round_of_uid.
|
|
290
|
+
events.append(Event(
|
|
291
|
+
uid=f"{trace_id}:r{previous_round}:result",
|
|
292
|
+
seq=seq, kind=TOOL_RESULT, parent_uid=call.uid,
|
|
293
|
+
tool_use_id=call.tool_use_id, tool_name=call.tool_name,
|
|
294
|
+
tool_ok=ok, tool_output=text, raw_type="received.tool",
|
|
295
|
+
source_line=rnd,
|
|
296
|
+
))
|
|
297
|
+
seq += 1
|
|
298
|
+
elif text and role != "tool":
|
|
299
|
+
events.append(Event(
|
|
300
|
+
uid=f"{prefix}received", seq=seq, kind=USER_MESSAGE, text=text,
|
|
301
|
+
raw_type=f"received.{role or 'unknown'}", source_line=rnd,
|
|
302
|
+
))
|
|
303
|
+
seq += 1
|
|
304
|
+
|
|
305
|
+
message_uid = f"{prefix}assistant"
|
|
306
|
+
reasoning = _text(turn.get("reasoning"))
|
|
307
|
+
visible = _text(turn.get("visible"))
|
|
308
|
+
events.append(Event(
|
|
309
|
+
uid=message_uid, seq=seq, kind=ASSISTANT_MESSAGE, model=model,
|
|
310
|
+
usage=Usage(
|
|
311
|
+
output_tokens=_int(turn.get("output_tokens")),
|
|
312
|
+
thinking_tokens=_int(turn.get("reasoning_tokens")),
|
|
313
|
+
),
|
|
314
|
+
text="\n".join(part for part in (reasoning, visible) if part),
|
|
315
|
+
raw_type="turn", source_line=rnd,
|
|
316
|
+
))
|
|
317
|
+
seq += 1
|
|
318
|
+
|
|
319
|
+
calls = []
|
|
320
|
+
for index, (name, args) in enumerate(split_action(_text(turn.get("action")))):
|
|
321
|
+
uid = f"{prefix}call{index}"
|
|
322
|
+
call = Event(
|
|
323
|
+
uid=uid, seq=seq, kind=TOOL_CALL, parent_uid=message_uid, model=model,
|
|
324
|
+
tool_name=name, tool_use_id=uid, tool_input=args, raw_type="action",
|
|
325
|
+
source_line=rnd,
|
|
326
|
+
)
|
|
327
|
+
events.append(call)
|
|
328
|
+
calls.append(call)
|
|
329
|
+
seq += 1
|
|
330
|
+
previous_calls = calls
|
|
331
|
+
previous_round = rnd
|
|
332
|
+
|
|
333
|
+
meta = {
|
|
334
|
+
key: record.get(key)
|
|
335
|
+
for key in ("trace_id", "model", "harness", "benchmark", "domain", "task_id", "solved")
|
|
336
|
+
}
|
|
337
|
+
return Trace(events=link_results_to_calls(events), source=source or trace_id,
|
|
338
|
+
adapter=NAME, meta=meta)
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def iter_records(path: str) -> Iterator[tuple[int, dict[str, Any] | None]]:
|
|
342
|
+
"""``(line number, record)`` for every line; ``None`` for an unreadable one."""
|
|
343
|
+
with open(path, "r", encoding="utf-8", errors="replace") as fh:
|
|
344
|
+
for lineno, line in enumerate(fh, 1):
|
|
345
|
+
line = line.strip()
|
|
346
|
+
if not line:
|
|
347
|
+
continue
|
|
348
|
+
try:
|
|
349
|
+
row = json.loads(line)
|
|
350
|
+
except json.JSONDecodeError:
|
|
351
|
+
yield lineno, None
|
|
352
|
+
continue
|
|
353
|
+
yield lineno, row if isinstance(row, dict) and isinstance(row.get("turns"), list) else None
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def parse(path: str) -> Trace:
|
|
357
|
+
"""The first trajectory in a file, so ``blackbox FILE`` works on one run.
|
|
358
|
+
|
|
359
|
+
A file in this format usually holds a hundred trajectories; the benchmark
|
|
360
|
+
(``blackbox bench``) reads all of them. Analysing one at a time from the
|
|
361
|
+
command line is still useful for looking at a single run's findings.
|
|
362
|
+
"""
|
|
363
|
+
skipped = 0
|
|
364
|
+
for lineno, record in iter_records(path):
|
|
365
|
+
if record is None:
|
|
366
|
+
skipped += 1
|
|
367
|
+
continue
|
|
368
|
+
trace = parse_record(record, source=f"{path}#{lineno}")
|
|
369
|
+
trace.skipped_lines = skipped
|
|
370
|
+
return trace
|
|
371
|
+
return Trace(events=[], source=path, adapter=NAME, skipped_lines=skipped)
|