|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import json |
| 4 | +import os |
| 5 | +import subprocess |
| 6 | +from collections.abc import Iterator |
| 7 | + |
| 8 | +from pydantic import BaseModel |
| 9 | + |
| 10 | +from .types import EventMsg |
| 11 | + |
| 12 | + |
| 13 | +class Event(BaseModel): |
| 14 | + """Protocol event envelope emitted by `codex exec --json`.""" |
| 15 | + |
| 16 | + id: str |
| 17 | + msg: EventMsg |
| 18 | + |
| 19 | + |
| 20 | +def stream_exec_events( |
| 21 | + prompt: str, |
| 22 | + *, |
| 23 | + executable: str = "codex", |
| 24 | + model: str | None = None, |
| 25 | + full_auto: bool = False, |
| 26 | + cd: str | None = None, |
| 27 | + env: dict[str, str] | None = None, |
| 28 | +) -> Iterator[Event]: |
| 29 | + """Spawn `codex exec --json` and yield Event objects from NDJSON stdout. |
| 30 | +
|
| 31 | + Non-event lines (config summary, prompt echo) are ignored. |
| 32 | + """ |
| 33 | + cmd: list[str] = [executable] |
| 34 | + if cd: |
| 35 | + cmd += ["--cd", cd] |
| 36 | + if model: |
| 37 | + cmd += ["-m", model] |
| 38 | + if full_auto: |
| 39 | + cmd.append("--full-auto") |
| 40 | + cmd += ["exec", "--json", prompt] |
| 41 | + |
| 42 | + with subprocess.Popen( |
| 43 | + cmd, |
| 44 | + stdout=subprocess.PIPE, |
| 45 | + stderr=subprocess.PIPE, |
| 46 | + text=True, |
| 47 | + env={**os.environ, **(env or {})}, |
| 48 | + ) as proc: |
| 49 | + assert proc.stdout is not None |
| 50 | + for line in proc.stdout: |
| 51 | + line = line.strip() |
| 52 | + if not line: |
| 53 | + continue |
| 54 | + try: |
| 55 | + obj = json.loads(line) |
| 56 | + except json.JSONDecodeError: |
| 57 | + continue |
| 58 | + |
| 59 | + # Filter out non-event helper lines |
| 60 | + if not isinstance(obj, dict): |
| 61 | + continue |
| 62 | + if "id" in obj and "msg" in obj: |
| 63 | + # Attempt to validate into our Pydantic Event model |
| 64 | + yield Event.model_validate(obj) |
| 65 | + |
| 66 | + # Drain stderr for diagnostics if the process failed |
| 67 | + ret = proc.wait() |
| 68 | + if ret != 0 and proc.stderr is not None: |
| 69 | + err = proc.stderr.read() |
| 70 | + raise RuntimeError(f"codex exec failed with {ret}: {err}") |
0 commit comments