"""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