Skip to content

Commit 077ba69

Browse files
committed
feat(sdk): scaffold Python SDK with auto-regen CI
Adds packages/sdk/python — a Python SDK generated from packages/sdk/openapi.json using openapi-python-client, plus the hand-written surface and CI that keeps it in sync with the same OpenAPI document the JS SDK is generated from. Hand-written: - pyproject.toml (hatchling, Python 3.10+, deps: httpx + attrs + python-dateutil) - src/opencode_ai/__init__.py public exports - src/opencode_ai/server.py — sync ServerHandle / async AsyncServerHandle helpers mirroring createOpencodeServer in packages/sdk/js - README.md modeled on the JS SDK README - scripts/_overlay/* — source of truth for files the generator does not produce - scripts/generate.py — regenerate / --check used by CI - tests/test_unit.py + tests/test_smoke.py - examples/basic_usage.py CI (.github/workflows/python-sdk.yml) runs lint, scripts/generate.py --check (fails the build on openapi.json drift), pytest against a live opencode server spawned from the local checkout, and a hatchling distribution build, on every push/PR that touches packages/sdk/python or packages/sdk/openapi.json. The previous Python SDK was removed in 13b2cf5 ("remove outdated SDKs") for exactly this reason — without a sync CI, the generated tree drifts. This PR ships the SDK and the regen CI together so it stays current. Refs anomalyco#4031, anomalyco#2266.
1 parent a3f7ea2 commit 077ba69

13 files changed

Lines changed: 1131 additions & 0 deletions

File tree

‎.github/workflows/python-sdk.yml‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
name: python-sdk
2+
3+
on:
4+
push:
5+
branches: [dev]
6+
paths:
7+
- "packages/sdk/python/**"
8+
- "packages/sdk/openapi.json"
9+
- ".github/workflows/python-sdk.yml"
10+
pull_request:
11+
paths:
12+
- "packages/sdk/python/**"
13+
- "packages/sdk/openapi.json"
14+
- ".github/workflows/python-sdk.yml"
15+
workflow_dispatch:
16+
17+
permissions:
18+
contents: read
19+
20+
jobs:
21+
test:
22+
name: test (py${{ matrix.python }})
23+
runs-on: blacksmith-4vcpu-ubuntu-2404
24+
strategy:
25+
fail-fast: false
26+
matrix:
27+
python: ["3.10", "3.13"]
28+
29+
defaults:
30+
run:
31+
shell: bash
32+
working-directory: packages/sdk/python
33+
34+
steps:
35+
- name: Checkout
36+
uses: actions/checkout@v4
37+
38+
- name: Setup Bun
39+
uses: ./.github/actions/setup-bun
40+
41+
- name: Setup Python
42+
uses: actions/setup-python@v5
43+
with:
44+
python-version: ${{ matrix.python }}
45+
cache: pip
46+
cache-dependency-path: packages/sdk/python/pyproject.toml
47+
48+
- name: Install Python SDK with dev extras
49+
run: pip install -e .[dev]
50+
51+
- name: Verify SDK is regenerated cleanly
52+
run: python scripts/generate.py --check
53+
54+
- name: Lint
55+
run: ruff check src tests
56+
57+
- name: Provide opencode binary on PATH
58+
working-directory: ${{ github.workspace }}
59+
run: |
60+
mkdir -p "$HOME/.local/bin"
61+
OPENCODE_DIR="$GITHUB_WORKSPACE/packages/opencode"
62+
cat > "$HOME/.local/bin/opencode" <<EOF
63+
#!/usr/bin/env bash
64+
exec bun run --cwd "$OPENCODE_DIR" --conditions=browser src/index.ts "\$@"
65+
EOF
66+
chmod +x "$HOME/.local/bin/opencode"
67+
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
68+
69+
- name: Run pytest (unit + smoke)
70+
env:
71+
OPENCODE_DISABLE_SHARE: "true"
72+
run: pytest tests -v --timeout=120
73+
74+
- name: Build distribution
75+
run: |
76+
pip install build
77+
python -m build
78+
ls dist

‎packages/sdk/python/.gitignore‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
__pycache__/
2+
*.pyc
3+
.pytest_cache/
4+
.ruff_cache/
5+
.mypy_cache/
6+
.venv/
7+
venv/
8+
build/
9+
dist/
10+
*.egg-info/

‎packages/sdk/python/README.md‎

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
# @opencode-ai/sdk (Python)
2+
3+
Python SDK for the [opencode](https://opencode.ai) HTTP API. Mirrors the
4+
JavaScript SDK in `packages/sdk/js`. The client is generated from the same
5+
OpenAPI document used by the JS SDK (`packages/sdk/openapi.json`) so the two
6+
stay in lockstep.
7+
8+
## Install
9+
10+
```bash
11+
pip install opencode-ai
12+
```
13+
14+
Requires Python 3.10+. The runtime depends only on `httpx`, `attrs`, and
15+
`python-dateutil`.
16+
17+
## Quick start
18+
19+
```python
20+
from opencode_ai import Client, ServerOptions, create_opencode_server
21+
from opencode_ai.api.default import global_health, session_create, session_prompt
22+
23+
# Spawn a local opencode server (or skip this and connect to an existing one).
24+
with create_opencode_server(ServerOptions(port=4096)) as server:
25+
client = Client(base_url=server.url)
26+
27+
health = global_health.sync(client=client)
28+
print(health.version)
29+
30+
session = session_create.sync(client=client).id
31+
session_prompt.sync(client=client, id=session, body=...)
32+
```
33+
34+
The generated client follows the standard
35+
[`openapi-python-client`](https://github.com/openapi-generators/openapi-python-client)
36+
convention: every operation lives in its own module under
37+
`opencode_ai.api.<tag>` (most operations live under `default`) and exposes
38+
four entry points:
39+
40+
| function | result |
41+
| ----------------- | ------------------------------------- |
42+
| `sync` | parsed model on success, `None` on 4xx with `raise_on_unexpected_status=False` |
43+
| `sync_detailed` | full `Response[...]` with status, headers, raw bytes |
44+
| `asyncio` | coroutine variant of `sync` |
45+
| `asyncio_detailed`| coroutine variant of `sync_detailed` |
46+
47+
## Server helper
48+
49+
`create_opencode_server` spawns the local `opencode serve` process, blocks
50+
until it prints its listen URL, and returns a context manager that shuts the
51+
process down cleanly on exit. The async sibling
52+
`AsyncServerHandle.create()` provides the same behavior for asyncio code.
53+
54+
```python
55+
import asyncio
56+
from opencode_ai import AsyncServerHandle, ServerOptions
57+
from opencode_ai.api.default import global_health
58+
59+
async def main():
60+
async with await AsyncServerHandle.create(ServerOptions(port=0)) as server:
61+
# ... use server.url
62+
pass
63+
64+
asyncio.run(main())
65+
```
66+
67+
## Authentication
68+
69+
For deployments that require an auth token, pass it via the
70+
`AuthenticatedClient` re-export:
71+
72+
```python
73+
from opencode_ai import AuthenticatedClient
74+
75+
client = AuthenticatedClient(base_url=..., token="...")
76+
```
77+
78+
## Regeneration
79+
80+
The package source is generated by `openapi-python-client` from
81+
`packages/sdk/openapi.json`. Hand-written files (`__init__.py`, `server.py`)
82+
are layered on top from `scripts/_overlay/`.
83+
84+
```bash
85+
# Regenerate in place after editing the overlay or the OpenAPI spec.
86+
python packages/sdk/python/scripts/generate.py
87+
88+
# CI runs this in --check mode and fails if the result differs from disk.
89+
python packages/sdk/python/scripts/generate.py --check
90+
```
91+
92+
## Testing
93+
94+
```bash
95+
pip install -e packages/sdk/python[dev]
96+
pytest packages/sdk/python/tests
97+
```
98+
99+
The smoke suite under `tests/test_smoke.py` is skipped unless an `opencode`
100+
binary is on `$PATH`. CI provides the binary by building the monorepo.
101+
102+
## License
103+
104+
MIT, matching the rest of the repository.
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""End-to-end example: spawn a local opencode server, hit a few endpoints.
2+
3+
Run with:
4+
pip install -e packages/sdk/python
5+
python packages/sdk/python/examples/basic_usage.py
6+
"""
7+
8+
from __future__ import annotations
9+
10+
import socket
11+
12+
from opencode_ai import Client, ServerOptions, create_opencode_server
13+
from opencode_ai.api.default import global_health, session_create, session_list
14+
from opencode_ai.models import SessionCreateBody
15+
16+
17+
def _free_port() -> int:
18+
with socket.socket() as s:
19+
s.bind(("127.0.0.1", 0))
20+
return s.getsockname()[1]
21+
22+
23+
def main() -> None:
24+
options = ServerOptions(port=_free_port(), timeout=15.0)
25+
with create_opencode_server(options) as server:
26+
client = Client(base_url=server.url, raise_on_unexpected_status=True)
27+
28+
health = global_health.sync(client=client)
29+
print(f"opencode {health.version} healthy={health.healthy}")
30+
31+
created = session_create.sync(client=client, body=SessionCreateBody(title="opencode-ai example"))
32+
print(f"created session {created.id}")
33+
34+
listing = session_list.sync(client=client)
35+
sessions = listing if isinstance(listing, list) else getattr(listing, "sessions", listing)
36+
print(f"server reports {len(sessions)} session(s)")
37+
38+
39+
if __name__ == "__main__":
40+
main()
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
project_name_override: opencode-ai
2+
package_name_override: opencode_ai
3+
package_version_override: 0.0.0
4+
use_path_prefixes_for_title_model_names: false
5+
field_constraints: true
6+
http_timeout: 30
7+
post_hooks:
8+
- "ruff check --select I --fix ."
9+
- "ruff format ."

‎packages/sdk/python/pyproject.toml‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
[build-system]
2+
requires = ["hatchling"]
3+
build-backend = "hatchling.build"
4+
5+
[project]
6+
name = "opencode-ai"
7+
version = "0.0.0"
8+
description = "The Python SDK for the opencode API"
9+
readme = "README.md"
10+
license = "MIT"
11+
requires-python = ">=3.10"
12+
authors = [{ name = "opencode" }]
13+
keywords = ["opencode", "sdk", "ai", "agent", "coding"]
14+
classifiers = [
15+
"Development Status :: 4 - Beta",
16+
"Intended Audience :: Developers",
17+
"License :: OSI Approved :: MIT License",
18+
"Operating System :: OS Independent",
19+
"Programming Language :: Python :: 3",
20+
"Programming Language :: Python :: 3.10",
21+
"Programming Language :: Python :: 3.11",
22+
"Programming Language :: Python :: 3.12",
23+
"Programming Language :: Python :: 3.13",
24+
"Typing :: Typed",
25+
]
26+
dependencies = [
27+
"httpx>=0.23.0,<1",
28+
"attrs>=22.2.0",
29+
"python-dateutil>=2.8.0",
30+
]
31+
32+
[project.optional-dependencies]
33+
dev = [
34+
"openapi-python-client>=0.28,<1",
35+
"pytest>=8",
36+
"pytest-asyncio>=0.23",
37+
"pytest-timeout>=2.3",
38+
"ruff>=0.6",
39+
]
40+
41+
[project.urls]
42+
Homepage = "https://opencode.ai"
43+
Repository = "https://github.com/anomalyco/opencode"
44+
Issues = "https://github.com/anomalyco/opencode/issues"
45+
46+
[tool.hatch.build.targets.wheel]
47+
packages = ["src/opencode_ai"]
48+
49+
[tool.hatch.build.targets.sdist]
50+
include = [
51+
"src/opencode_ai",
52+
"README.md",
53+
"openapi-python-client.yaml",
54+
"scripts/generate.py",
55+
]
56+
57+
[tool.ruff]
58+
line-length = 120
59+
# Generated client code follows openapi-python-client's own style — we only lint
60+
# hand-written code. Regeneration is verified separately by scripts/generate.py --check.
61+
extend-exclude = [
62+
"src/opencode_ai/api",
63+
"src/opencode_ai/models",
64+
"src/opencode_ai/client.py",
65+
"src/opencode_ai/errors.py",
66+
"src/opencode_ai/types.py",
67+
]
68+
69+
[tool.ruff.lint]
70+
select = ["F", "I", "UP"]
71+
72+
[tool.pytest.ini_options]
73+
testpaths = ["tests"]
74+
asyncio_mode = "auto"
75+
timeout = 60
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
"""Python SDK for the opencode API.
2+
3+
Generated client code lives in `opencode_ai.api` and `opencode_ai.models`.
4+
The hand-written surface in this module is limited to:
5+
6+
* `Client` / `AuthenticatedClient` — re-exported from the generated `client`
7+
module so callers can do `from opencode_ai import Client`.
8+
* `ServerOptions`, `ServerHandle`, `AsyncServerHandle`,
9+
`create_opencode_server` — process helpers that mirror
10+
`createOpencodeServer` in the JS SDK.
11+
12+
Operation modules are reached as `from opencode_ai.api.default import session_create`,
13+
matching the openapi-python-client convention. Each operation module exposes
14+
`sync`, `sync_detailed`, `asyncio`, and `asyncio_detailed` functions.
15+
"""
16+
17+
from .client import AuthenticatedClient, Client
18+
from .server import (
19+
AsyncServerHandle,
20+
ServerHandle,
21+
ServerOptions,
22+
create_opencode_server,
23+
)
24+
25+
__all__ = (
26+
"AsyncServerHandle",
27+
"AuthenticatedClient",
28+
"Client",
29+
"ServerHandle",
30+
"ServerOptions",
31+
"create_opencode_server",
32+
)

0 commit comments

Comments
 (0)