codex-python 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,34 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [ main ]
6
+ pull_request:
7
+ branches: [ main ]
8
+
9
+ permissions:
10
+ contents: read
11
+
12
+ jobs:
13
+ lint-and-test:
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - name: Check out repository
17
+ uses: actions/checkout@v4
18
+
19
+ - name: Set up Python
20
+ uses: actions/setup-python@v5
21
+ with:
22
+ python-version: '3.13'
23
+
24
+ - name: Install uv
25
+ uses: astral-sh/setup-uv@v4
26
+ with:
27
+ version: latest
28
+
29
+ - name: Lint
30
+ run: make lint
31
+
32
+ - name: Test
33
+ run: make test
34
+
@@ -0,0 +1,34 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - 'v*'
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ build-and-publish:
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - name: Check out repository
16
+ uses: actions/checkout@v4
17
+
18
+ - name: Set up Python
19
+ uses: actions/setup-python@v5
20
+ with:
21
+ python-version: '3.13'
22
+
23
+ - name: Install uv
24
+ uses: astral-sh/setup-uv@v4
25
+ with:
26
+ version: latest
27
+
28
+ - name: Build distribution
29
+ run: uv build
30
+
31
+ - name: Publish to PyPI
32
+ env:
33
+ PYPI_API_TOKEN: ${{ secrets.PYPI_API_TOKEN }}
34
+ run: uv publish --token "$PYPI_API_TOKEN"
@@ -0,0 +1,45 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # Distribution / packaging
7
+ .Python
8
+ build/
9
+ develop-eggs/
10
+ dist/
11
+ downloads/
12
+ eggs/
13
+ .eggs/
14
+ lib/
15
+ lib64/
16
+ parts/
17
+ sdist/
18
+ var/
19
+ wheels/
20
+ share/python-wheels/
21
+ *.egg-info/
22
+ .installed.cfg
23
+ *.egg
24
+ MANIFEST
25
+
26
+ # Virtual environments
27
+ .venv/
28
+ venv/
29
+ ENV/
30
+ env/
31
+ .python-version
32
+
33
+ # Tooling
34
+ .pytest_cache/
35
+ .mypy_cache/
36
+ .ruff_cache/
37
+ .coverage
38
+ coverage.xml
39
+ .tox/
40
+ .nox/
41
+ .DS_Store
42
+
43
+ # uv
44
+ .uv/
45
+ uv.lock
@@ -0,0 +1,19 @@
1
+ repos:
2
+ - repo: https://github.com/pre-commit/pre-commit-hooks
3
+ rev: v4.6.0
4
+ hooks:
5
+ - id: trailing-whitespace
6
+ - id: end-of-file-fixer
7
+ - id: check-yaml
8
+ - repo: https://github.com/astral-sh/ruff-pre-commit
9
+ rev: v0.5.6
10
+ hooks:
11
+ - id: ruff
12
+ args: ["--fix"]
13
+ - id: ruff-format
14
+ - repo: https://github.com/pre-commit/mirrors-mypy
15
+ rev: v1.10.0
16
+ hooks:
17
+ - id: mypy
18
+ additional_dependencies: []
19
+
@@ -0,0 +1,17 @@
1
+ % Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on Keep a Changelog and this project adheres to Semantic Versioning.
6
+
7
+ ## [0.1.0] - 2025-09-10
8
+ ### Added
9
+ - Initial project scaffold with Python 3.13+
10
+ - Packaging with Hatchling and uv build/publish
11
+ - CI workflow (lint + test)
12
+ - Publishing workflow on `v*` tags
13
+ - Dev tooling: ruff, pytest, mypy, Makefile
14
+ - Typing marker (`py.typed`)
15
+ - MIT License
16
+
17
+ [0.1.0]: https://github.com/gersmann/codex-python/releases/tag/v0.1.0
@@ -0,0 +1,34 @@
1
+ % Code of Conduct
2
+
3
+ We follow the Contributor Covenant Code of Conduct. By participating, you are expected to uphold this code.
4
+
5
+ ## Our Pledge
6
+ In the interest of fostering an open and welcoming environment, we pledge to make participation in our project and community a harassment-free experience for everyone.
7
+
8
+ ## Our Standards
9
+ Examples of behavior that contributes to creating a positive environment include:
10
+ - Using welcoming and inclusive language
11
+ - Being respectful of differing viewpoints and experiences
12
+ - Gracefully accepting constructive criticism
13
+ - Focusing on what is best for the community
14
+ - Showing empathy towards other community members
15
+
16
+ Examples of unacceptable behavior include:
17
+ - The use of sexualized language or imagery and unwelcome sexual attention or advances
18
+ - Trolling, insulting/derogatory comments, and personal or political attacks
19
+ - Public or private harassment
20
+ - Publishing others’ private information without explicit permission
21
+ - Other conduct which could reasonably be considered inappropriate in a professional setting
22
+
23
+ ## Our Responsibilities
24
+ Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
25
+
26
+ ## Scope
27
+ This Code of Conduct applies within project spaces and in public spaces when an individual is representing the project or its community.
28
+
29
+ ## Enforcement
30
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported via GitHub issues. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances.
31
+
32
+ ## Attribution
33
+ This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org) version 2.1.
34
+
@@ -0,0 +1,54 @@
1
+ % Contributing to codex-python
2
+
3
+ Thanks for considering a contribution! This guide helps you get set up and make changes smoothly.
4
+
5
+ ## Prerequisites
6
+ - Python 3.13+
7
+ - [uv](https://docs.astral.sh/uv/) installed
8
+ - `make` available (optional but recommended)
9
+
10
+ ## Quick Start
11
+ ```
12
+ # Create an isolated environment (optional)
13
+ uv venv --python 3.13
14
+ . .venv/bin/activate # Windows: .venv\Scripts\activate
15
+
16
+ # Install dev tools when running via uv
17
+ make lint # ruff + mypy (installs on first run)
18
+ make test # pytest
19
+ ```
20
+
21
+ ## Project Tasks
22
+ - Lint: `make lint`
23
+ - Format: `make fmt`
24
+ - Tests: `make test`
25
+ - Build: `uv build`
26
+
27
+ ## Type Hints
28
+ This project is typed and ships a `py.typed` marker. Please keep public APIs typed.
29
+
30
+ ## Commit Style
31
+ - Keep commits focused.
32
+ - Reference issues where applicable, e.g., `Fixes #123`.
33
+
34
+ ## Release Process
35
+ 1. Update the version in `codex/__init__.py` (SemVer).
36
+ 2. Update `CHANGELOG.md`.
37
+ 3. Merge to `main`.
38
+ 4. Tag the release: `git tag -a vX.Y.Z -m "vX.Y.Z" && git push --tags`.
39
+ 5. GitHub Actions (publish workflow) will build and publish to PyPI on `v*` tags.
40
+
41
+ ## Pre-commit (optional but recommended)
42
+ ```
43
+ uvx pre-commit install
44
+ uvx pre-commit run --all-files
45
+ ```
46
+
47
+ If you prefer, you can install pre-commit globally via `pipx` or `pip`.
48
+
49
+ ## Reporting Issues
50
+ Please open an issue with reproduction steps, expected vs actual behavior, and environment info.
51
+
52
+ ## Code of Conduct
53
+ By participating, you agree to abide by our [Code of Conduct](CODE_OF_CONDUCT.md).
54
+
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 gersmann
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
@@ -0,0 +1,37 @@
1
+ .PHONY: help venv fmt lint test build publish clean
2
+
3
+ help:
4
+ @echo "Common targets:"
5
+ @echo " make lint - Run ruff and mypy"
6
+ @echo " make test - Run pytest"
7
+ @echo " make build - Build sdist and wheel with uv"
8
+ @echo " make publish - Publish to PyPI via uv (uses PYPI_API_TOKEN)"
9
+ @echo " make clean - Remove build artifacts"
10
+
11
+ venv:
12
+ uv venv --python 3.13
13
+ @echo "Run: . .venv/bin/activate"
14
+
15
+ fmt:
16
+ uv run --group dev ruff format .
17
+
18
+ lint:
19
+ uv run --group dev ruff format --check .
20
+ uv run --group dev ruff check .
21
+ uv run --group dev mypy codex
22
+
23
+ test:
24
+ uv run --group dev pytest
25
+
26
+ build:
27
+ uv build
28
+
29
+ publish: build
30
+ @if [ -z "$${PYPI_API_TOKEN}" ]; then \
31
+ echo "PYPI_API_TOKEN is not set"; \
32
+ exit 1; \
33
+ fi
34
+ uv publish --token "$$PYPI_API_TOKEN"
35
+
36
+ clean:
37
+ rm -rf build dist *.egg-info .pytest_cache .mypy_cache .ruff_cache
@@ -0,0 +1,143 @@
1
+ Metadata-Version: 2.4
2
+ Name: codex-python
3
+ Version: 0.1.0
4
+ Summary: A minimal Python library scaffold for codex-python
5
+ Project-URL: Homepage, https://github.com/gersmann/codex-python
6
+ Project-URL: Repository, https://github.com/gersmann/codex-python
7
+ Project-URL: Issues, https://github.com/gersmann/codex-python/issues
8
+ License: MIT License
9
+
10
+ Copyright (c) 2025 gersmann
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ of this software and associated documentation files (the "Software"), to deal
14
+ in the Software without restriction, including without limitation the rights
15
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ copies of the Software, and to permit persons to whom the Software is
17
+ furnished to do so, subject to the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be included in all
20
+ copies or substantial portions of the Software.
21
+
22
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
+ SOFTWARE.
29
+
30
+ License-File: LICENSE
31
+ Keywords: codex,library,scaffold
32
+ Classifier: License :: OSI Approved :: MIT License
33
+ Classifier: Operating System :: OS Independent
34
+ Classifier: Programming Language :: Python :: 3
35
+ Classifier: Programming Language :: Python :: 3 :: Only
36
+ Classifier: Programming Language :: Python :: 3.13
37
+ Classifier: Typing :: Typed
38
+ Requires-Python: >=3.13
39
+ Description-Content-Type: text/markdown
40
+
41
+ # codex-python
42
+
43
+ A minimal Python library scaffold using `uv` with Python 3.13+.
44
+
45
+ ## Quickstart
46
+
47
+ - Requires Python 3.13+.
48
+ - Package import name: `codex`.
49
+ - Distribution name (PyPI): `codex-python`.
50
+
51
+ ### Repo
52
+
53
+ - Git: `git@github.com:gersmann/codex-python.git`
54
+ - URL: https://github.com/gersmann/codex-python
55
+
56
+ ## Usage
57
+
58
+ Basic non-interactive execution via Codex CLI:
59
+
60
+ ```
61
+ from codex import run_exec
62
+
63
+ out = run_exec("explain this repo")
64
+ print(out)
65
+ ```
66
+
67
+ Options:
68
+
69
+ - Choose model: `run_exec("...", model="gpt-4.1")`
70
+ - Full auto: `run_exec("scaffold a cli", full_auto=True)`
71
+ - Run in another dir: `run_exec("...", cd="/path/to/project")`
72
+
73
+ Using a client with defaults:
74
+
75
+ ```
76
+ from codex import CodexClient
77
+
78
+ client = CodexClient(model="gpt-4.1", full_auto=True)
79
+ print(client.run("explain this repo"))
80
+ ```
81
+
82
+ ### Install uv
83
+
84
+ - macOS (Homebrew): `brew install uv`
85
+ - Or via install script:
86
+ - Unix/macOS: `curl -LsSf https://astral.sh/uv/install.sh | sh`
87
+ - Windows (PowerShell): `iwr https://astral.sh/uv/install.ps1 -UseBasicParsing | iex`
88
+
89
+ See: https://docs.astral.sh/uv/
90
+
91
+ ### Create a virtual env (optional)
92
+
93
+ ```
94
+ uv python install 3.13
95
+ uv venv --python 3.13
96
+ . .venv/bin/activate # or .venv\Scripts\activate on Windows
97
+ ```
98
+
99
+ ### Build
100
+
101
+ ```
102
+ uv build
103
+ ```
104
+
105
+ Artifacts appear in `dist/` (`.whl` and `.tar.gz`).
106
+
107
+ ### Publish to PyPI
108
+
109
+ - Manual:
110
+
111
+ ```
112
+ export PYPI_API_TOKEN="pypi-XXXX" # create at https://pypi.org/manage/account/token/
113
+ uv publish --token "$PYPI_API_TOKEN"
114
+ ```
115
+
116
+ - GitHub Actions: add a repository secret `PYPI_API_TOKEN` and push a tag like `v0.1.0`.
117
+ The workflow at `.github/workflows/publish.yml` builds and publishes with `uv` on `v*` tags.
118
+
119
+ ### Dev tooling
120
+
121
+ - Lint: `make lint` (ruff + mypy)
122
+ - Tests: `make test` (pytest)
123
+ - Format: `make fmt` (ruff formatter)
124
+ - Pre-commit: `uvx pre-commit install && uvx pre-commit run --all-files`
125
+
126
+ ## Project Layout
127
+
128
+ ```
129
+ .
130
+ ├── codex/ # package root (import name: codex)
131
+ │ └── __init__.py # version lives here
132
+ ├── pyproject.toml # PEP 621 metadata, hatchling build backend
133
+ ├── README.md
134
+ └── .gitignore
135
+ ```
136
+
137
+ ## Versioning
138
+
139
+ Version is managed via `codex/__init__.py` and exposed as `__version__`. The build uses Hatch’s version source.
140
+
141
+ ## Python Compatibility
142
+
143
+ - Requires Python `>=3.13`.
@@ -0,0 +1,103 @@
1
+ # codex-python
2
+
3
+ A minimal Python library scaffold using `uv` with Python 3.13+.
4
+
5
+ ## Quickstart
6
+
7
+ - Requires Python 3.13+.
8
+ - Package import name: `codex`.
9
+ - Distribution name (PyPI): `codex-python`.
10
+
11
+ ### Repo
12
+
13
+ - Git: `git@github.com:gersmann/codex-python.git`
14
+ - URL: https://github.com/gersmann/codex-python
15
+
16
+ ## Usage
17
+
18
+ Basic non-interactive execution via Codex CLI:
19
+
20
+ ```
21
+ from codex import run_exec
22
+
23
+ out = run_exec("explain this repo")
24
+ print(out)
25
+ ```
26
+
27
+ Options:
28
+
29
+ - Choose model: `run_exec("...", model="gpt-4.1")`
30
+ - Full auto: `run_exec("scaffold a cli", full_auto=True)`
31
+ - Run in another dir: `run_exec("...", cd="/path/to/project")`
32
+
33
+ Using a client with defaults:
34
+
35
+ ```
36
+ from codex import CodexClient
37
+
38
+ client = CodexClient(model="gpt-4.1", full_auto=True)
39
+ print(client.run("explain this repo"))
40
+ ```
41
+
42
+ ### Install uv
43
+
44
+ - macOS (Homebrew): `brew install uv`
45
+ - Or via install script:
46
+ - Unix/macOS: `curl -LsSf https://astral.sh/uv/install.sh | sh`
47
+ - Windows (PowerShell): `iwr https://astral.sh/uv/install.ps1 -UseBasicParsing | iex`
48
+
49
+ See: https://docs.astral.sh/uv/
50
+
51
+ ### Create a virtual env (optional)
52
+
53
+ ```
54
+ uv python install 3.13
55
+ uv venv --python 3.13
56
+ . .venv/bin/activate # or .venv\Scripts\activate on Windows
57
+ ```
58
+
59
+ ### Build
60
+
61
+ ```
62
+ uv build
63
+ ```
64
+
65
+ Artifacts appear in `dist/` (`.whl` and `.tar.gz`).
66
+
67
+ ### Publish to PyPI
68
+
69
+ - Manual:
70
+
71
+ ```
72
+ export PYPI_API_TOKEN="pypi-XXXX" # create at https://pypi.org/manage/account/token/
73
+ uv publish --token "$PYPI_API_TOKEN"
74
+ ```
75
+
76
+ - GitHub Actions: add a repository secret `PYPI_API_TOKEN` and push a tag like `v0.1.0`.
77
+ The workflow at `.github/workflows/publish.yml` builds and publishes with `uv` on `v*` tags.
78
+
79
+ ### Dev tooling
80
+
81
+ - Lint: `make lint` (ruff + mypy)
82
+ - Tests: `make test` (pytest)
83
+ - Format: `make fmt` (ruff formatter)
84
+ - Pre-commit: `uvx pre-commit install && uvx pre-commit run --all-files`
85
+
86
+ ## Project Layout
87
+
88
+ ```
89
+ .
90
+ ├── codex/ # package root (import name: codex)
91
+ │ └── __init__.py # version lives here
92
+ ├── pyproject.toml # PEP 621 metadata, hatchling build backend
93
+ ├── README.md
94
+ └── .gitignore
95
+ ```
96
+
97
+ ## Versioning
98
+
99
+ Version is managed via `codex/__init__.py` and exposed as `__version__`. The build uses Hatch’s version source.
100
+
101
+ ## Python Compatibility
102
+
103
+ - Requires Python `>=3.13`.
@@ -0,0 +1,30 @@
1
+ """codex
2
+
3
+ Python interface for the Codex CLI.
4
+
5
+ Usage:
6
+ from codex import run_exec
7
+ output = run_exec("explain this codebase to me")
8
+ """
9
+
10
+ from .api import (
11
+ CodexClient,
12
+ CodexError,
13
+ CodexNotFoundError,
14
+ CodexProcessError,
15
+ find_binary,
16
+ run_exec,
17
+ )
18
+
19
+ __all__ = [
20
+ "__version__",
21
+ "CodexError",
22
+ "CodexNotFoundError",
23
+ "CodexProcessError",
24
+ "CodexClient",
25
+ "find_binary",
26
+ "run_exec",
27
+ ]
28
+
29
+ # Managed by Hatch via pyproject.toml [tool.hatch.version]
30
+ __version__ = "0.1.0"
@@ -0,0 +1,165 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import shutil
5
+ import subprocess
6
+ from collections.abc import Iterable, Mapping, Sequence
7
+ from dataclasses import dataclass
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: str | None = None,
54
+ full_auto: bool = False,
55
+ cd: str | None = None,
56
+ timeout: float | None = None,
57
+ env: Mapping[str, str] | None = None,
58
+ executable: str = "codex",
59
+ extra_args: Iterable[str] | None = 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
+
102
+
103
+ @dataclass(slots=True)
104
+ class CodexClient:
105
+ """Lightweight, synchronous client for the Codex CLI.
106
+
107
+ Provides defaults for repeated invocations and convenience helpers.
108
+ """
109
+
110
+ executable: str = "codex"
111
+ model: str | None = None
112
+ full_auto: bool = False
113
+ cd: str | None = None
114
+ env: Mapping[str, str] | None = None
115
+ extra_args: Sequence[str] | None = None
116
+
117
+ def ensure_available(self) -> str:
118
+ """Return the resolved binary path or raise CodexNotFoundError."""
119
+ return find_binary(self.executable)
120
+
121
+ def run(
122
+ self,
123
+ prompt: str,
124
+ *,
125
+ model: str | None = None,
126
+ full_auto: bool | None = None,
127
+ cd: str | None = None,
128
+ timeout: float | None = None,
129
+ env: Mapping[str, str] | None = None,
130
+ extra_args: Iterable[str] | None = None,
131
+ ) -> str:
132
+ """Execute `codex exec` and return stdout.
133
+
134
+ Explicit arguments override the client's defaults.
135
+ """
136
+ eff_model = model if model is not None else self.model
137
+ eff_full_auto = full_auto if full_auto is not None else self.full_auto
138
+ eff_cd = cd if cd is not None else self.cd
139
+
140
+ # Merge environment overlays; run_exec will merge with os.environ
141
+ merged_env: Mapping[str, str] | None
142
+ if self.env and env:
143
+ tmp = dict(self.env)
144
+ tmp.update(env)
145
+ merged_env = tmp
146
+ else:
147
+ merged_env = env or self.env
148
+
149
+ # Compose extra args
150
+ eff_extra: list[str] = []
151
+ if self.extra_args:
152
+ eff_extra.extend(self.extra_args)
153
+ if extra_args:
154
+ eff_extra.extend(list(extra_args))
155
+
156
+ return run_exec(
157
+ prompt,
158
+ model=eff_model,
159
+ full_auto=eff_full_auto,
160
+ cd=eff_cd,
161
+ timeout=timeout,
162
+ env=merged_env,
163
+ executable=self.executable,
164
+ extra_args=eff_extra,
165
+ )
@@ -0,0 +1 @@
1
+
@@ -0,0 +1,61 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "codex-python"
7
+ description = "A minimal Python library scaffold for codex-python"
8
+ readme = "README.md"
9
+ requires-python = ">=3.13"
10
+ keywords = ["codex", "library", "scaffold"]
11
+ classifiers = [
12
+ "Programming Language :: Python :: 3",
13
+ "Programming Language :: Python :: 3 :: Only",
14
+ "Programming Language :: Python :: 3.13",
15
+ "License :: OSI Approved :: MIT License",
16
+ "Typing :: Typed",
17
+ "Operating System :: OS Independent",
18
+ ]
19
+ dynamic = ["version"]
20
+ license = { file = "LICENSE" }
21
+
22
+ [project.urls]
23
+ Homepage = "https://github.com/gersmann/codex-python"
24
+ Repository = "https://github.com/gersmann/codex-python"
25
+ Issues = "https://github.com/gersmann/codex-python/issues"
26
+
27
+ [tool.hatch.version]
28
+ path = "codex/__init__.py"
29
+
30
+ [tool.hatch.build.targets.wheel]
31
+ packages = ["codex"]
32
+ force-include = { "codex/py.typed" = "codex/py.typed" }
33
+
34
+ # Development dependency groups (used by uv)
35
+ [dependency-groups]
36
+ dev = [
37
+ "ruff>=0.5",
38
+ "pytest>=8",
39
+ "mypy>=1.10",
40
+ ]
41
+
42
+ [tool.ruff]
43
+ line-length = 100
44
+ target-version = "py313"
45
+
46
+ [tool.ruff.lint]
47
+ select = ["E", "F", "I", "B", "UP"]
48
+ ignore = []
49
+
50
+ [tool.pytest.ini_options]
51
+ addopts = "-q"
52
+ testpaths = ["tests"]
53
+ python_files = ["test_*.py"]
54
+
55
+ [tool.mypy]
56
+ python_version = "3.13"
57
+ warn_return_any = true
58
+ warn_unused_ignores = true
59
+ disallow_untyped_defs = true
60
+ no_implicit_optional = true
61
+ check_untyped_defs = true
@@ -0,0 +1,27 @@
1
+ import os
2
+ import stat
3
+ from pathlib import Path
4
+
5
+ import pytest
6
+
7
+ from codex.api import CodexNotFoundError, run_exec
8
+
9
+
10
+ def test_missing_binary_raises():
11
+ with pytest.raises(CodexNotFoundError):
12
+ run_exec("hello", executable="codex-does-not-exist-xyz")
13
+
14
+
15
+ def test_runs_with_dummy_binary(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
16
+ # Create a dummy 'codex' executable that echoes args and succeeds
17
+ bin_dir = tmp_path / "bin"
18
+ bin_dir.mkdir()
19
+ codex_path = bin_dir / "codex"
20
+ codex_path.write_text("""#!/bin/sh\necho \"[dummy] $@\"\n""")
21
+ codex_path.chmod(codex_path.stat().st_mode | stat.S_IXUSR)
22
+
23
+ # Prepend our dummy bin to PATH
24
+ monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}" + os.environ.get("PATH", ""))
25
+
26
+ out = run_exec("hello world", executable="codex")
27
+ assert "[dummy] exec hello world" in out
@@ -0,0 +1,37 @@
1
+ import os
2
+ import stat
3
+ from pathlib import Path
4
+
5
+ import pytest
6
+
7
+ from codex import CodexClient, CodexNotFoundError
8
+
9
+
10
+ def test_client_missing_binary():
11
+ client = CodexClient(executable="codex-does-not-exist-xyz")
12
+ with pytest.raises(CodexNotFoundError):
13
+ client.ensure_available()
14
+ with pytest.raises(CodexNotFoundError):
15
+ client.run("hello")
16
+
17
+
18
+ def test_client_runs_with_defaults(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
19
+ # Dummy codex that echoes args and succeeds
20
+ bin_dir = tmp_path / "bin"
21
+ bin_dir.mkdir()
22
+ codex_path = bin_dir / "codex"
23
+ codex_path.write_text("""#!/bin/sh\necho \"[dummy] $@\"\n""")
24
+ codex_path.chmod(codex_path.stat().st_mode | stat.S_IXUSR)
25
+
26
+ monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}" + os.environ.get("PATH", ""))
27
+
28
+ client = CodexClient(model="test-model", full_auto=True, extra_args=["--ask-for-approval"])
29
+ out = client.run("hello world")
30
+
31
+ # Ensure key flags and prompt are passed along; order-insensitive
32
+ assert "[dummy]" in out
33
+ assert "exec" in out
34
+ assert "hello world" in out
35
+ assert "--full-auto" in out
36
+ assert "-m test-model" in out
37
+ assert "--ask-for-approval" in out
@@ -0,0 +1,7 @@
1
+ import re
2
+
3
+
4
+ def test_version_semver():
5
+ from codex import __version__
6
+
7
+ assert re.match(r"^\d+\.\d+\.\d+(?:[.-][A-Za-z0-9.]+)?$", __version__), __version__