# Client SDK

|  | SDK |
| --- | --- |
| Serves | Python programs that drive OpenProgram: conversations, streamed turns, approvals, stopping, Program runs |
| Surface | `OpenProgram` and `AsyncOpenProgram`; `session()`, `send()`, `run()`, `cancel()`, `sessions()`, `agents()`, `models()`, `run_program()` |
| Code | `openprogram/interfaces/sdk/`: `connection.py` (endpoint, socket, HTTP), `client.py` (turns, waits, Program runs), `events.py`, `errors.py`, `sync.py` |
| User docs | [Python SDK](https://openprogram.io/docs/interfaces/sdk.html) |
| Tests | `tests/component/sdk/` against `tests/support/live_worker.py`: the production `create_app` behind owner auth on a loopback port, with a scripted model. Full turn, streaming, tool calls, usage across an approval pause, approve, deny, unattended refusal, cancel from both clients, wrong token, no Worker, a Program run |

## Peers

| Peer | Its SDK |
| --- | --- |
| Codex | Python `openai-codex` and a TypeScript SDK. Spawns the `codex app-server` binary and speaks its JSON-RPC; `Codex` and `AsyncCodex`, `thread_start`/`thread_resume`, `thread.run()` returning a `TurnResult` with usage, a turn handle with `stream()`, `steer()`, `interrupt()`. Types generated from the protocol's JSON schema; a separate distribution pinned to the binary. Approvals by mode, not by callback. |
| Claude Agent SDK | A separate package that runs the CLI with stream-json; `query()` for one-shot, a client object for a conversation, a `can_use_tool` callback for approvals. |
| OpenCode | `@opencode/sdk` hosts the server's router in process; `@opencode/client` is generated from its OpenAPI and reaches a running server. |
| KimiCode | `@moonshot-ai/klient`: a contract-driven facade over the agent core, over IPC or in memory. |
| Pi | An in-process SDK, and an RPC client over a subprocess. |

The peers split into SDKs that start their own agent process (Codex, Claude, Pi's RPC client) and clients of a running server (OpenCode's client, KimiCode over IPC). OpenProgram already runs one Worker per profile that every window shares, so the SDK is a client of it: the Codex shape of the surface, OpenCode's way of reaching the server.

## Decisions

| Question | Choice and reason |
| --- | --- |
| What it talks to | The running Worker, over the protocol the Web UI and TUI use: the `chat` command and its frames, `execution.command`, `question.asked`, `list_sessions`, `load_session`, `list_agents`, and `/api/models/enabled`, `/api/model`, `/api/function/<name>`. A turn started here is the same stored, visible conversation as one typed in the App, and an approval can be answered from either. In-process use stays `from openprogram import Agent`. |
| Where it lives | `openprogram.interfaces.sdk`. The structure rules put every surface through which a program talks to OpenProgram under `interfaces`, allow no new top-level package, and ship one wheel. The package imports no server code: only `host.security.backend_endpoint` to find the local Worker and `operations.worker.spawn_detached` to start one, both lower layers. |
| One wheel | Codex and Claude ship a separate package pinned to a binary because the binary is the product. Here the SDK and the Worker are the same install, so their protocol versions cannot drift; the `worker_capabilities` frame still names what a Worker on another computer offers, and the client reads `cancel_by_request` from it. |
| Finding the Worker | As the CLI does: the profile's access snapshot, the nonce/HMAC challenge, then the owner token; a Worker is started when none runs (`start=False` to only connect). `url=` and `token=` name another one. A 401 or 403 is `AuthenticationError`, no answer `WorkerNotFound`. |
| Events | Frozen dataclasses built from frames, each with `raw`. One `ToolCall` per call id, though the Worker repeats `tool_use` when a wait resumes. Sub-agent frames of the same conversation carry another `msg_id` and are left out. `ApprovalRequest` and `Question` carry their own `approve`/`deny` and `answer`/`decline`, sent as `execution.wait.answer`/`decline` at the wait's own `expected_version`, as the TUI does. |
| Approvals | On the stream, and as Claude's `can_use_tool`-style `on_approval` in `run()`, returning `True`, `False` or a scope. Without a handler `run()` sends the turn non-interactive, so an approval is refused at once instead of pausing a script no one watches; `send()` stays interactive. |
| How a turn ends | The `result` frame, or `cancelled`; a `cancelled` or `failed` execution status ends it after a short grace, for a stop the frame never follows. A failure is `TurnFailed` with the frame's `retryable` and `kind`; a refusal before the ack is `TurnRefused`. |
| Stopping | `execution.cancel` by execution id, or by `client_request_id` before the ack names it, when the Worker offers `cancel_by_request`. The result keeps the text written before the stop. |
| Sync and async | `AsyncOpenProgram` is the implementation; `OpenProgram` runs it on a private event loop in a daemon thread, as Codex pairs `Codex` with `AsyncCodex`. Its waits answer by blocking, and `run()` handlers run in the caller's thread so they can prompt. |
| No TypeScript SDK | Codex and OpenCode generate theirs from a schema. The Worker's frames have none; the TUI's hand-written types in `apps/cli/src/ws/client.ts` are the nearest thing. A hand-written second SDK would drift, so TypeScript waits for a frame schema. |

## Protocol additions

| Addition | Why |
| --- | --- |
| `node_id` in the `POST /api/function/<name>` response | A Program run's output arrives in the `tree_update` frames of its code node, whose `msg_id` is the node id. The Web UI draws that card itself; a client that did not had no way to address the result. |
| `usage` in the turn's `result` frame | The in-flight `context_usage` reports stay inside the Worker (they feed `context_stats`, the conversation's running total), so no frame said what one turn used. The result frame now carries the turn's tally: input, output and cache tokens and the request count, the requests before an approval pause included. |

## Implementation status

| Item | State |
| --- | --- |
| Conversations, streaming, approvals, questions, cancel, listings, model and Agent choice, Program runs, sync and async | Implemented |
| Reattaching to a running turn after the socket or the Worker restarts | Open: `ConnectionLost` ends the turn handle; the turn's stored result is read with `messages()` |
| `openprogram --print` on the SDK | Open: `interfaces/cli/print_mode/worker_turn.py` relays the same frames with its own code |
| Steering a running turn, forking, attachments | Not built |
| TypeScript | Waits for a machine-readable frame schema |
