codex-wrapper 0.5.2

A type-safe Codex CLI wrapper for Rust
Documentation
#!/usr/bin/env python3
"""Capture a synthetic rollout from a codex CLI, reduced for use as a fixture.

    npm install --prefix /tmp/codex @openai/codex@0.167.0
    python3 capture.py /tmp/codex/node_modules/.bin/codex > 0.167.0.jsonl

Runs `codex exec` in a temporary home against a loopback endpoint that returns
fixed responses, so no account, network access or personal session is involved.
The first turn calls tools and completes. The second is interrupted.
"""

import http.server
import json
import os
import pathlib
import re
import signal
import subprocess
import sys
import tempfile
import threading

CALLS = [
    {"type": "function_call", "id": "fc_1", "call_id": "call_1", "name": "exec_command",
     "arguments": '{"cmd":"echo fixture"}'},
    {"type": "custom_tool_call", "id": "ctc_2", "call_id": "call_2", "name": "apply_patch",
     "input": "*** Begin Patch\n*** Add File: fixture.txt\n+fixture\n*** End Patch\n"},
    {"type": "tool_search_call", "id": "tsc_3", "call_id": "call_3", "status": "completed",
     "execution": "client", "arguments": {"query": "fixture"}},
]
# The model provider runs these, so no result follows and the answer comes with them.
ANSWER = [
    {"type": "web_search_call", "id": "ws_4", "status": "completed",
     "action": {"type": "search", "query": "fixture"}},
    {"type": "message", "id": "msg_5", "role": "assistant",
     "content": [{"type": "output_text", "text": "fixture answer"}]},
]

hanging = threading.Event()
finished = threading.Event()


class Responses(http.server.BaseHTTPRequestHandler):
    def log_message(self, *_):
        pass

    def do_GET(self):
        self.send_error(404)

    def do_POST(self):
        request = json.loads(self.rfile.read(int(self.headers["content-length"])))
        self.send_response(200)
        self.send_header("content-type", "text/event-stream")
        self.end_headers()
        self.event("response.created", response={"id": "resp_fixture"})
        if "interrupted prompt" in json.dumps(request["input"]):
            hanging.set()
            finished.wait()
            return
        done = sum(item.get("type", "").endswith("_output") for item in request["input"])
        for item in CALLS[done:done + 1] or ANSWER:
            self.event("response.output_item.done", item=item)
        usage = {"input_tokens": 1, "output_tokens": 1, "total_tokens": 2}
        self.event("response.completed", response={"id": "resp_fixture", "usage": usage})

    def event(self, kind, **fields):
        data = json.dumps({"type": kind, **fields})
        self.wfile.write(f"event: {kind}\ndata: {data}\n\n".encode())
        self.wfile.flush()


def capture(codex, root):
    server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Responses)
    server.daemon_threads = True
    threading.Thread(target=server.serve_forever, daemon=True).start()
    home, workspace = root / "home", root / "workspace"
    home.mkdir()
    workspace.mkdir()
    (home / "config.toml").write_text(f"""
model = "gpt-5.2-codex"
model_provider = "fixture"
[model_providers.fixture]
name = "fixture"
base_url = "http://127.0.0.1:{server.server_port}/v1"
wire_api = "responses"
request_max_retries = 0
stream_max_retries = 0
""")
    env = {"PATH": os.environ["PATH"], "HOME": str(home), "CODEX_HOME": str(home), "TZ": "UTC"}
    command = [codex, "exec", "--json", "--skip-git-repo-check", "--sandbox", "workspace-write"]
    options = {"cwd": workspace, "env": env, "stdin": subprocess.DEVNULL, "stdout": sys.stderr}

    subprocess.run([*command, "first prompt"], check=True, timeout=60, **options)
    turn = subprocess.Popen([*command, "resume", "--last", "interrupted prompt"], **options)
    if not hanging.wait(60):
        turn.kill()
        sys.exit("the second turn never reached the endpoint")
    turn.send_signal(signal.SIGINT)
    turn.wait(60)
    finished.set()

    [rollout] = home.glob("sessions/*/*/*/rollout-*.jsonl")
    return rollout.read_text().replace(str(workspace), "/fixture/workspace")


def reduce(rollout):
    """Drop what the reader does not type, and make ids synthetic."""
    ids = {}
    uuid = r"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}"
    rollout = re.sub(
        uuid,
        lambda m: ids.setdefault(m[0], f"00000000-0000-4000-8000-{len(ids) + 1:012}"),
        rollout,
    )
    for line in rollout.splitlines():
        record = json.loads(line)
        payload = record["payload"]
        if record["type"] in ("world_state", "token_usage_record"):
            continue
        if payload.get("type") in ("token_count", "thread_settings_applied"):
            continue
        if payload.get("role") == "developer":
            continue
        for key in ("base_instructions", "permission_profile", "file_system_sandbox_policy"):
            payload.pop(key, None)
        for part in payload.get("content") or []:
            if part.get("text", "").startswith("<environment_context>"):
                part["text"] = "<environment_context></environment_context>"
        yield json.dumps(record, separators=(",", ":"))


if __name__ == "__main__":
    with tempfile.TemporaryDirectory() as directory:
        # Resolved because the CLI records the real path, and macOS links its temp directory.
        for line in reduce(capture(sys.argv[1], pathlib.Path(directory).resolve())):
            print(line)