Metadata-Version: 2.5
Name: oxap-sdk
Version: 0.1.0a42
Summary: Python SDK for the Open Agent Protocol project's runtime, over its stdio protocol
Project-URL: Homepage, https://github.com/lsm/oxap
Project-URL: Source, https://github.com/lsm/oxap/tree/main/sdk/python
Author: Open Agent Protocol contributors
License: ISC
Keywords: llm,oxap_sdk,sdk,stdio,streaming
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.11
Provides-Extra: dev
Requires-Dist: mypy>=1.11; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Description-Content-Type: text/markdown

# OAP Python SDK

`oxap-sdk` (imported as `oxap_sdk`) uses one combined OAP 0.1 stdio endpoint by default:

```text
oapx serve agent,provider --stdio
```

It multiplexes `agent-control-core` and `model-provider-core` profiles over that connection. The public `MakaiClient` name remains for source compatibility.

The package requires Python 3.11+. Install from a checkout with `pip install ./sdk/python` (it is not yet published to PyPI). It was called `oap-sdk` / `oap_sdk` before; no `oap_sdk` module is kept, so change the import. The `oap-sdk` project on PyPI is unrelated.

## Connect and call a provider

```python
import asyncio
import oxap_sdk

async def main() -> None:
    async with oxap_sdk.connect() as client:
        model = await client.models.resolve(
            provider_id="anthropic", model_id="claude-sonnet-4-5"
        )
        response = await client.provider.complete(
            model_ref=model.model_ref,
            messages=[{"role": "user", "content": "Write a haiku about streams."}],
            options=oxap_sdk.RunOptions(max_tokens=128),
        )
        print(response.text)

asyncio.run(main())
```

`client.models` reads the direct provider profile's catalog. Treat returned `model_ref` values as opaque. `client.provider.stream(...)` yields `MessageStart`, content deltas, tool-call events, and `MessageEnd` or `StreamError`. If leaving a stream early, close its async generator so the SDK sends a best-effort cancellation. Direct provider tool definitions map to OAP `input_schema`; tool calls are returned to the caller, not executed in the SDK.

## Breaking changes

`Usage.input` and `Usage.output` are now `Optional[int]`, defaulting to `None`,
like the other four counters. Under Decision 0063, `None` means unmeasured;
an explicit `0` is a measurement. Check `is not None` before arithmetic, and
choose explicitly whether unknown counts are acceptable for your calculation.

Provider and agent unary responses and terminal stream events preserve partial
usage and any supplied `total`, including the full uint64 maximum
(`18446744073709551615`). The SDK does not infer a missing total from partial
counts. An absent usage object remains `None`; `{}` becomes `Usage()` with all
counters unknown. Present null usage or counters, negative, non-integer and
out-of-range counts raise `MakaiProtocolError` with code `malformed_response`.

Usage counters follow Decision 0065: absence is unknown, `0` is measured zero,
and accepted counts are exact integers through `18446744073709551615`.
A raw `-0` count is refused with `MakaiProtocolError(code="malformed_response")`
on provider and agent unary and streaming APIs. The transport retains that
noncanonical integer token for the strict usage decoder instead of accepting
JSON's integer-zero normalization. Usage is checked before content/failure
frames can be ignored or converted to ordinary provider errors; valid counts
retain those frames' behavior. Numbers in tool results and other application
objects retain their ordinary JSON decoding.

`RunOptions(headers=...)` sends request headers on a direct provider call. The endpoint decides which headers it forwards to the provider and refuses the rest with `unsupported_feature`. A credential in a header is refused, and an agent run refuses `headers` client side.

## Agent sessions

`client.agent` uses the agent-control profile. A session has a default model, which can be changed between runs. A per-call `model_ref` overrides that default for one submit. `available_models` reads the session's effective catalog, distinct from direct provider discovery.

```python
async with oxap_sdk.connect() as client:
    session = await client.agent.open_session("my-session")
    session_id = session["session_id"]
    catalog = await client.agent.available_models(session_id)
    await client.agent.switch_model(session_id, catalog["models"][0]["id"])
    response = await client.agent.run(
        messages=[{"role": "user", "content": "Hello"}],
        options=oxap_sdk.RunOptions(session_id=session_id),
    )
```

The optional `client.agent.attach_provider(session_id, {"id": ..., "provider_id": ..., "service_id": ...})` operation attaches an operator-configured OAP provider service to one session. A host without the extension returns typed `unsupported_feature`; there is no implicit attachment. Remote provider services are follow-up work. `switch_model` affects future runs, not an active run.

`tools=` on `client.agent.run` or `.stream` are provided to the session at open (`action.tools.provide`), owned by the SDK's participant `sdk`. When the model calls one, the SDK runs its `execute` callback and answers with `action.call.resolve.request`: the returned text as the result, or the exception's message as an error. A tool without `execute` is answered with an error. Against an endpoint that does not advertise `action.tools.provide`, a run with tools raises `unsupported_feature` before the open rather than having its tools ignored, and once a tool has run, an `auto_once` auth failure is raised rather than retried, so the tool is not run twice. `.stream` yields `tool_execution_start` and `tool_execution_end` for every call, the endpoint's own tools included. Agent `RunOptions.reasoning_effort` becomes the session's reasoning level and `.max_tokens` (an integer from 1 to 4294967295, else `invalid_request`) the oapx output limit, both at open, the output limit only on the `oapx.agent` endpoint that reads it (elsewhere `unsupported_feature`); `.temperature` and `reasoning_effort="minimal"` raise `unsupported_feature`, since the agent loop takes no temperature and runs minimal as low. The open also turns off the loop's `request_user_input` tool, which the SDK cannot answer. `.metadata` maps to submit metadata.

## Authentication

`client.auth.list_providers()` and `.login()` use agent-profile `+auth` on the local stdio connection. The runtime owns credentials; no login code or prompt answer travels in an OAP envelope. A manual-code flow without host-owned input fails with `auth_input_unavailable`. `openai-codex` offers two ways at once: its URL is the ChatGPT sign-in, which returns to a `localhost:1455` callback the runtime listens on, and its instructions also give `https://auth.openai.com/codex/device` and a one-time code for signing in from any other device, which needs device code login turned on in ChatGPT's security settings (or by a workspace admin). Whichever finishes first completes the login. `anthropic` signs in through a browser on the same computer: its URL returns to a `localhost` callback the runtime listens on (macOS and Linux). Where no browser can reach that computer, give the runtime a Claude subscription token, such as one from `claude setup-token`, as `ANTHROPIC_AUTH_TOKEN` in its environment.

```python
handlers = oxap_sdk.AuthFlowHandlers(
    on_event=lambda event: print(event.url) if isinstance(event, oxap_sdk.AuthUrlEvent) else None,
)
await client.auth.login("anthropic", handlers)
```

`AuthOptions(auth_retry_policy="auto_once", handlers=handlers)` enables one login and retry after a typed `auth_required` or `credential_*` failure; arbitrary provider-error text never triggers login. For a stream that already emitted user-visible output, the SDK does not replay the call.

## Configuration and errors

`connect()` accepts `command`, `args`, `cwd`, `env`, a `BinaryResolverOptions`, `auth`, and timeouts in seconds. `response_timeout` bounds each request's reply, the acceptance of a run or inference included, and never a running run; `idle_timeout`, off by default, cancels a run or inference that sends no event for that long. The default args are `("serve", "agent,provider", "--stdio")`. Binary resolution honors `OXAP_SDK_BINARY_PATH` and then the legacy `OAP_SDK_BINARY_PATH`, an explicit path or checksum-verified URL, local `zig-out/bin/oxap` and `zig/zig-out/bin/oxap` before the `oapx` names, then `oxap` and then `oapx` on `PATH`. An `OXAP_SDK_BINARY_URL` likewise outranks `OAP_SDK_BINARY_URL`, and each environment URL takes the checksum written beside it, so a checksum is never borrowed across the two pairs; `checksum_sha256` from the options is the fallback for any URL. The legacy names stay read-compatible.

`oxap_sdk.connect_sync()` supplies the same API through a blocking wrapper for scripts; do not call it inside a running event loop. The async and sync clients own their child process and should be closed.

Failures are typed as `MakaiStreamError`, `MakaiAuthRequiredError`, `MakaiProtocolError`, or `MakaiAuthError`. Unsupported operations carry code `unsupported_feature`. The `Makai` class names remain for compatibility.

Run `uv run --with pytest --with pytest-asyncio pytest -q` from `sdk/python` to run the suite. OAP fake-host tests require no credentials.
