|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import os |
| 4 | +import shutil |
| 5 | +import subprocess |
| 6 | +from dataclasses import dataclass |
| 7 | +from typing import Iterable, Mapping, Optional, Sequence |
| 8 | + |
| 9 | + |
| 10 | +class CodexError(Exception): |
| 11 | + """Base exception for codex-python.""" |
| 12 | + |
| 13 | + |
| 14 | +class CodexNotFoundError(CodexError): |
| 15 | + """Raised when the 'codex' binary cannot be found or executed.""" |
| 16 | + |
| 17 | + def __init__(self, executable: str = "codex") -> None: |
| 18 | + super().__init__( |
| 19 | + f"Codex CLI not found: '{executable}'.\n" |
| 20 | + "Install from https://github.com/openai/codex or ensure it is on PATH." |
| 21 | + ) |
| 22 | + self.executable = executable |
| 23 | + |
| 24 | + |
| 25 | +@dataclass(slots=True) |
| 26 | +class CodexProcessError(CodexError): |
| 27 | + """Raised when the codex process exits with a non‑zero status.""" |
| 28 | + |
| 29 | + returncode: int |
| 30 | + cmd: Sequence[str] |
| 31 | + stdout: str |
| 32 | + stderr: str |
| 33 | + |
| 34 | + def __str__(self) -> str: # pragma: no cover - repr is sufficient |
| 35 | + return ( |
| 36 | + f"Codex process failed with exit code {self.returncode}.\n" |
| 37 | + f"Command: {' '.join(self.cmd)}\n" |
| 38 | + f"stderr:\n{self.stderr.strip()}" |
| 39 | + ) |
| 40 | + |
| 41 | + |
| 42 | +def find_binary(executable: str = "codex") -> str: |
| 43 | + """Return the absolute path to the Codex CLI binary or raise if not found.""" |
| 44 | + path = shutil.which(executable) |
| 45 | + if not path: |
| 46 | + raise CodexNotFoundError(executable) |
| 47 | + return path |
| 48 | + |
| 49 | + |
| 50 | +def run_exec( |
| 51 | + prompt: str, |
| 52 | + *, |
| 53 | + model: Optional[str] = None, |
| 54 | + full_auto: bool = False, |
| 55 | + cd: Optional[str] = None, |
| 56 | + timeout: Optional[float] = None, |
| 57 | + env: Optional[Mapping[str, str]] = None, |
| 58 | + executable: str = "codex", |
| 59 | + extra_args: Optional[Iterable[str]] = None, |
| 60 | +) -> str: |
| 61 | + """ |
| 62 | + Run `codex exec` with the given prompt and return stdout as text. |
| 63 | +
|
| 64 | + - Raises CodexNotFoundError if the binary is unavailable. |
| 65 | + - Raises CodexProcessError on non‑zero exit with captured stdout/stderr. |
| 66 | + """ |
| 67 | + bin_path = find_binary(executable) |
| 68 | + |
| 69 | + cmd: list[str] = [bin_path] |
| 70 | + |
| 71 | + if cd: |
| 72 | + cmd.extend(["--cd", cd]) |
| 73 | + if model: |
| 74 | + cmd.extend(["-m", model]) |
| 75 | + if full_auto: |
| 76 | + cmd.append("--full-auto") |
| 77 | + if extra_args: |
| 78 | + cmd.extend(list(extra_args)) |
| 79 | + |
| 80 | + cmd.extend(["exec", prompt]) |
| 81 | + |
| 82 | + completed = subprocess.run( |
| 83 | + cmd, |
| 84 | + capture_output=True, |
| 85 | + text=True, |
| 86 | + timeout=timeout, |
| 87 | + env={**os.environ, **(dict(env) if env else {})}, |
| 88 | + check=False, |
| 89 | + ) |
| 90 | + |
| 91 | + stdout = completed.stdout or "" |
| 92 | + stderr = completed.stderr or "" |
| 93 | + if completed.returncode != 0: |
| 94 | + raise CodexProcessError( |
| 95 | + returncode=completed.returncode, |
| 96 | + cmd=tuple(cmd), |
| 97 | + stdout=stdout, |
| 98 | + stderr=stderr, |
| 99 | + ) |
| 100 | + return stdout |
| 101 | + |
0 commit comments