File size: 9,049 Bytes
22decf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
"""Adapter for Codex SDK traces.

The Codex SDK emits a different event stream from the Claude Code SDK, but the
research loop it describes is the same shape, so this maps it onto the same
`Run` / `ToolCall` objects. Everything downstream -- features, statistics,
prose probes, narratives, figures -- then works on either agent without
knowing which one it is reading.

The mapping, and where it is lossy:

| Codex event | mapped to | note |
|---|---|---|
| `command_execution` | `ToolCall(name="Bash")` | started -> completed gives the duration |
| `file_change` | `ToolCall(name="Write"/"Edit")` | **paths only, no content** |
| `reasoning` | an assistant `thinking` block **with text** | Claude's equivalent is encrypted |
| `agent_message` | an assistant `text` block | Codex narrates far more |
| `turn.completed` | the terminal `result` event | carries token usage, not cost |

The `file_change` gap matters for the technique detectors, which read what the
agent wrote. Codex authors most of its code through heredocs inside Bash
(1,209 of 3,946 commands), so that content is still visible; what is lost is
whatever it wrote through the patch tool. Detection rates for Codex are
therefore a lower bound, and are not directly comparable to Claude's.
"""

from __future__ import annotations

import json
import os
from datetime import datetime

from .parse import LINE_RE, RUN_DIR_RE, Event, Run, ToolCall, _ts


def looks_like_codex(trace_path: str) -> bool:
    """Sniff the format from the first JSON line.

    Claude's stream opens with a `system`/`init` event; Codex opens with
    `thread.started`. Checking a handful of lines is enough and avoids making
    the caller declare which agent produced a directory.
    """
    try:
        with open(trace_path, errors="replace") as fh:
            for _ in range(40):
                line = fh.readline()
                if not line:
                    break
                m = LINE_RE.match(line.rstrip("\n"))
                if not m or not m.group(2).startswith("{"):
                    continue
                try:
                    t = json.loads(m.group(2)).get("type", "")
                except json.JSONDecodeError:
                    continue
                if t.startswith(("thread.", "turn.", "item.")):
                    return True
                if t in ("system", "assistant", "user", "result"):
                    return False
    except OSError:
        pass
    return False


def _assistant_event(ts: datetime, rel: float, kind: str, text: str) -> Event:
    """Wrap Codex prose in the Claude content-block shape the probes expect."""
    block = {"type": kind, "text": text} if kind == "text" else {"type": "thinking", "thinking": text}
    return Event(ts, rel, "assistant", None, {"message": {"content": [block]}})


def parse_codex_run(run_dir: str) -> Run | None:
    name = os.path.basename(run_dir.rstrip("/"))
    m = RUN_DIR_RE.match(name)
    if not m:
        return None
    trace = os.path.join(run_dir, "solve_out.txt")
    if not os.path.exists(trace):
        return None

    run = Run(
        run_dir=run_dir,
        task=m.group("task"),
        base_model=m.group("model").replace("_", "/", 1),
        stamp=m.group("stamp"),
    )
    for fname, attr in (("prompt.txt", "prompt"), ("time_taken.txt", "time_taken")):
        p = os.path.join(run_dir, fname)
        if os.path.exists(p):
            setattr(run, attr, open(p, errors="replace").read().strip())
    mp = os.path.join(run_dir, "metrics.json")
    if os.path.exists(mp):
        try:
            run.accuracy = json.load(open(mp)).get("accuracy")
        except Exception:
            pass

    t0: datetime | None = None
    pending: dict[str, ToolCall] = {}
    n_items = 0
    usage: dict = {}
    errors: list[str] = []
    last_message = ""

    with open(trace, errors="replace") as fh:
        for line in fh:
            lm = LINE_RE.match(line.rstrip("\n"))
            if not lm:
                continue
            ts = _ts(lm.group(1))
            if t0 is None:
                t0 = ts
            rel = (ts - t0).total_seconds()
            body = lm.group(2)
            if not body.startswith("{"):
                run.events.append(Event(ts, rel, "log", None, body))
                continue
            try:
                ev = json.loads(body)
            except json.JSONDecodeError:
                run.events.append(Event(ts, rel, "log", None, body))
                continue

            etype = ev.get("type", "")
            run.events.append(Event(ts, rel, etype, None, ev))
            if etype == "error":
                errors.append(str(ev.get("message", ""))[:200])
                continue
            if etype == "turn.completed":
                usage = ev.get("usage", {}) or {}
                continue
            if etype not in ("item.started", "item.completed"):
                continue

            item = ev.get("item") or {}
            itype = item.get("type")
            iid = item.get("id", "")
            n_items += 1

            if itype == "command_execution":
                if etype == "item.started":
                    tc = ToolCall(
                        idx=len(run.tool_calls),
                        ts=ts,
                        t_rel=rel,
                        name="Bash",
                        tool_id=iid,
                        inp={"command": item.get("command", "")},
                    )
                    run.tool_calls.append(tc)
                    pending[iid] = tc
                else:
                    tc = pending.pop(iid, None)
                    if tc is None:  # completion without a start; keep it anyway
                        tc = ToolCall(
                            idx=len(run.tool_calls),
                            ts=ts,
                            t_rel=rel,
                            name="Bash",
                            tool_id=iid,
                            inp={"command": item.get("command", "")},
                        )
                        run.tool_calls.append(tc)
                    tc.result_text = item.get("aggregated_output", "") or ""
                    code = item.get("exit_code")
                    tc.is_error = code not in (0, None)
                    tc.result_t_rel = rel

            elif itype == "file_change":
                if etype != "item.completed":
                    continue
                changes = item.get("changes") or []
                paths = [c.get("path", "") for c in changes]
                kinds = {c.get("kind", "") for c in changes}
                run.tool_calls.append(
                    ToolCall(
                        idx=len(run.tool_calls),
                        ts=ts,
                        t_rel=rel,
                        # `add` creates a file, anything else edits one. The
                        # content is not in the event either way.
                        name="Write" if kinds == {"add"} else "Edit",
                        tool_id=iid,
                        inp={"file_path": " ".join(paths)},
                        result_t_rel=rel,
                    )
                )

            elif itype == "reasoning" and etype == "item.completed":
                run.events.append(_assistant_event(ts, rel, "thinking", item.get("text", "") or ""))

            elif itype == "agent_message" and etype == "item.completed":
                txt = item.get("text", "") or ""
                last_message = txt
                run.events.append(_assistant_event(ts, rel, "text", txt))

            elif itype == "collab_tool_call" and etype == "item.started":
                run.tool_calls.append(
                    ToolCall(
                        idx=len(run.tool_calls),
                        ts=ts,
                        t_rel=rel,
                        name="Task",
                        tool_id=iid,
                        inp={"prompt": str(item.get("prompt") or item.get("tool") or "")},
                        result_t_rel=rel,
                    )
                )

    # Synthesise the terminal event the Claude parser produces, so the cohort
    # rule and the token/cost features read the same fields for both agents.
    # Codex reports tokens but not dollars, so cost stays 0 and is not
    # compared across agents.
    run.result = {
        "terminal_reason": "completed" if usage else "truncated",
        "api_error_status": None,
        "subtype": "success" if usage else "incomplete",
        "num_turns": n_items,
        "duration_api_ms": 0,
        "total_cost_usd": 0.0,
        "usage": {
            "output_tokens": usage.get("output_tokens", 0),
            "cache_read_input_tokens": usage.get("cached_input_tokens", 0),
            "input_tokens": usage.get("input_tokens", 0),
            "reasoning_output_tokens": usage.get("reasoning_output_tokens", 0),
        },
        "stream_errors": errors,
        "result": last_message,
    }
    if usage:
        run.final_message = last_message
    return run