Metadata-Version: 2.5
Name: wkala
Version: 0.1.0
Summary: Typed asynchronous Python client for the Relay agent API
Requires-Python: >=3.11
Requires-Dist: httpx[socks]<0.29,>=0.28
Requires-Dist: pydantic<3,>=2.10
Provides-Extra: dev
Requires-Dist: pytest-asyncio<2,>=0.25; extra == 'dev'
Requires-Dist: pytest<10,>=8.3; extra == 'dev'
Provides-Extra: mcp
Requires-Dist: mcp==2.3.0; extra == 'mcp'
Provides-Extra: postgres
Requires-Dist: psycopg[binary]==3.3.3; extra == 'postgres'
Description-Content-Type: text/markdown

# Relay Python SDK

A typed asynchronous SDK for running, observing, and controlling agents. Send a message, receive a durable run, stream its messages and tool execution, and respond to explicit requests for input. The service owns the execution loop.

## Install

Python 3.11 or later is required. This kit contains local packages; it does not claim a published PyPI release.

```bash
uv pip install -e packages/sdk-python
# To define MCP tools inside your own Python backend:
uv pip install -e 'packages/sdk-python[mcp]'
```

`AgentClient` is the async client. `AsyncAgentClient` is an equivalent alias. Use one client for an application's lifespan.

The Python and TypeScript backend clients supply the hosted endpoint internally. For a bare Go service, pass `base_url="http://localhost:8080/v1"` at construction. The Compose ingress uses `http://localhost:8088/v1`; native multi-service development uses `http://localhost:18080/v1`; production uses the configured public origin. Python also accepts an origin-style override such as `http://localhost:8080` for compatibility and preserves the positional `AgentClient(base_url, api_key)` form. Browser clients instead use the authenticated same-origin `/app` backend contract.

## Send work and observe the complete execution

```python
import asyncio
import os
from wkala import AgentClient, SnapshotUpdate

async def main():
    async with AgentClient(api_key=os.environ['RELAY_API_KEY']) as client:
        session = await client.sessions.create(title='Delivery investigation')
        run = await session.send(
            'Outline three checks for investigating a delayed delivery.',
            idempotency_key='delivery-investigation-1042',
        )
        async with run.stream() as stream:
            async for update in stream:
                if isinstance(update, SnapshotUpdate):
                    print('Current execution:', stream.state.runs[run.id].status)
                else:
                    print(update.type, update.model_dump(mode='json', by_alias=True))
        result = await run.result()
        print(result.status, result.stop_reason)
        print('Messages:', len(result.messages))
        print('Tool calls:', len(result.tool_calls))
        print('Backend invocations:', len(result.mcp_invocations))

asyncio.run(main())
```

`session.send()` returns immediately after admission. `run.run` is the admitted DTO; `run.id`, `session_id`, `idempotency_key`, and `admission_status` are available before observing anything. `await run.get()` refreshes the DTO. The optional `result.text` projection includes ordinary assistant text; reasoning, tool records, and artifacts remain separately available.

The example bootstrap provisions an account and registers the company tools. The customer proxy attaches those tools to its runs automatically. A direct SDK caller attaches the registered server ID with `mcp_server_ids=[...]` and supplies a private `subject={'id': ...}` derived from its authenticated user. A deployment with missing execution configuration fails visibly. `client.capabilities.get()` reports availability, content support, and session operations without exposing implementation selection. `capabilities.agent.simulation` describes execution mode; each run's `usage.source` separately identifies simulated, estimated, provider-reported, or unknown accounting. An actual executable using the local fixture model still has simulated usage.

## Streaming messages and tools

High-level `run.stream()` hydrates a coherent snapshot and keeps `stream.state` current. A `SnapshotUpdate` replaces the previous view. Typed events include message creation/deltas/completion, authoritative rich-message updates, tool updates, backend invocation updates, interactions, normalized session state, artifacts, and run state.

```python
from wkala import ToolUpdated, MCPInvocationUpdated

async with run.stream() as stream:
    async for update in stream:
        if isinstance(update, ToolUpdated):
            tool = update.data.tool
            print(tool.title, tool.status, tool.arguments, tool.output, tool.content)
        elif isinstance(update, MCPInvocationUpdated):
            invocation = update.data.invocation
            print(invocation.server_name, invocation.status, invocation.result)
```

Tool arguments and results stream as actual execution updates. Argument-token chunks are not fabricated when the execution service supplies a complete argument object. Backend MCP results preserve structured content in `mcp_invocations`; their IDs are distinct from tool-call IDs because an unambiguous one-to-one correlation is not always available.

For text presentation, `stream.text_updates()` yields cumulative text per message/part. On hydration and recovery, `replace=True` tells your renderer to replace its existing value. Do not append the complete string on each update. A run can contain several messages, and message completion is separate from run completion.

For an exact event consumer:

```python
async with session.events(after=last_committed_cursor) as events:
    async for event in events:
        await persist_event_and_cursor(event)
```

The low-level iterator validates the entire session sequence before filtering by run. Gaps raise `RecoveryRequired`; high-level streams recover with a fresh snapshot. Streams have one consumer and require an async context manager for cleanup. The incremental parser bounds unfinished lines and rejects invalid UTF-8 or inconsistent envelopes.

Closing a stream does not cancel execution. `await run.cancel()` is explicit. A terminal run iterator finishes at the terminal event; use the session stream or a later snapshot to observe a late backend invocation outcome attributed to that run.

## Interactions and outcomes

```python
from wkala import InputRequired

try:
    result = await run.wait(timeout=120)
except InputRequired as required:
    for interaction in required.interactions:
        print(interaction.kind, interaction.prompt, interaction.permission_options)
    # After your application obtains an authorized response:
    # await run.reply('Use the revised delivery address.')
    # await run.respond({'confirmed': True, 'quantity': 3})
    # await run.approve()
```

`reply()` targets the single pending question on the run, `respond()` targets a form, and `approve()` selects the unique offered allow-once option. Supply `interaction_id=` when more than one matching interaction is pending. For exact offered permission choices, use `client.interactions.respond(id, option_id=...)`. The client never infers approval from an ordinary message.

The response variants are exclusive: `message`, `data`, `option_id`, or `decision`. Explicit decisions are approve, deny, decline, and cancel. Typed form values preserve booleans, numbers, arrays, and enum values. `interaction.form_schema` exposes its form schema.

`wait(on_input='raise')` is the default. Use `on_input='wait'` when another authorized component handles interactions. Observation timeout raises `ObservationTimeout` and leaves execution running. A failed run is an inspectable `RunResult`, separate from an HTTP error. `status` and `stop_reason` explain completion, refusal, execution limits, cancellation, and interruption. Unknown cost is `None`, never an invented zero; money uses integer micro-USD.

## Rich messages, configuration, and session controls

```python
from wkala import MessageInput, TextContent, ResourceContent, ResourceData

message = MessageInput(parts=[
    TextContent(text='Review this self-contained report.'),
    ResourceContent(resource=ResourceData(
        uri='resource://reports/quarterly', mime_type='text/plain', text='Revenue increased.'
    )),
])
run = await session.send(message)
```

Supported content includes text, images, audio, embedded resources, and resource links, subject to advertised capabilities. Binary content uses strict standard base64. Resource URIs use HTTPS or the opaque `resource:`, `urn:`, and `app:` schemes; local filesystem URLs are rejected. The SDK validates input part counts and decoded/text size limits; the service also enforces serialized message, account, and output limits.

- `sessions.create()` returns a handle whose `.session` holds its DTO. `sessions.get(id)` returns a DTO. `sessions.handle(id)` is a lazy handle with no HTTP call.
- `session.settings()` and `.update_setting(id, value)` use permitted idle-session settings.
- `session.close()`, `.delete()`, and `.fork(idempotency_key=...)` are capability-gated. Close retains history; delete retains operational audit/accounting while hiding the session from lists.
- `profiles.list/create/update` manages versioned behavior. `skills.upload_directory` preserves binary files and immutable digests.
- `mcp_servers.list/create/update/validate/revoke` manages backend capabilities.
- `artifacts.get/content/get_bytes` retrieves authorized artifacts.

An admitted run keeps its effective profile/skills/MCP revisions. An empty tool allowlist exposes no tools; `['*']` explicitly selects all discovered tools. Skills require `SKILL.md`, safe relative paths, at most 64 files, 1 MiB per file and 2 MiB per bundle.

## Define MCP tools inside your existing backend

Install the optional MCP extra and use the standard server object. `BackendMCP` supplies registration, authentication, serving lifecycle, and trusted invocation context. Your functions stay in your backend.

```python
from contextlib import asynccontextmanager
import os
from fastapi import FastAPI
from mcp.server import MCPServer
from pydantic import BaseModel
from wkala import AgentClient
from wkala.mcp import BackendMCP, current_invocation, load_or_create_signing_key

class InventoryItem(BaseModel):
    name: str
    available: int

server = MCPServer('Inventory')

@server.tool()
async def get_inventory(item: str) -> InventoryItem:
    authority = current_invocation()
    # Replace with your own record-level permission and database lookup.
    owned = {'alice': {'notebook': 12}, 'bob': {'pen': 5}}
    stock = owned.get(authority.subject, {})
    if item not in stock:
        raise PermissionError('Item is unavailable to this account member')
    return InventoryItem(name=item, available=stock[item])

binding = BackendMCP(
    server, name='inventory', url=os.environ['INVENTORY_MCP_URL'],
    signing_key=load_or_create_signing_key('./data/inventory-signing.key'),
    allowed_tools=['get_inventory'], state_url=os.environ['CUSTOMER_DATABASE_URL'],
)

@asynccontextmanager
async def lifespan(app):
    async with AgentClient(api_key=os.environ['RELAY_API_KEY']) as client:
        async with binding.lifespan(client):
            app.state.agent = client
            yield

app = FastAPI(lifespan=lifespan)
app.mount(binding.mount_path, binding.app)
```

The endpoint URL is canonicalized with a trailing slash to avoid POST redirects. It must be reachable from the agent infrastructure; a private network is sufficient. The helper does not open an outbound worker tunnel.

Startup registers configuration without probing the endpoint. Validate through `client.mcp_servers.validate(binding.attachment.id)` from bootstrap **after the HTTP application is listening**. Required unready servers refuse admission. Then attach the server ID to a profile or `session.send(..., mcp_server_ids=[...])`. API keys used for registration need configure scope.

The signing key is persistent, write-only during registration, and encrypted by the service. Never generate a replacement key on every startup. The binding journal retains accepted revisions and detects conflicting invocation reuse. Rotating a signing key requires retaining previous keys/revisions for admitted work; `previous_signing_keys=` supports that overlap. Ordinary profile updates do not broaden an active run's permissions.

`current_invocation()` supplies verified account, subject, session, run, server revision, invocation ID, deadline, and request digest. Those values do not enter the model's input schema. An application key can assert its own private `subject={'id': ...}`; derive it from your authenticated user, never browser data. The example proxy enforces this boundary.

A signed request authenticates its issuer; it does not make business side effects exactly once. The complete `apps/customer-backend` implementation demonstrates an order read tool and a write tool whose operation receipt and side effect share a database transaction, including concurrent repeat deliveries. General tools must supply their own business idempotency and reconcile ambiguous outcomes deliberately.

## Retry, errors, and testing

Pass a durable `idempotency_key` when admitting work so your own backend can recover after process restart. The SDK reuses that key across internal retries. Repeating an identical request recovers the existing run; a changed body conflicts. Stream reconnection never creates another run.

`APIError` preserves status, code, request ID, details, and admission idempotency key. `TransportError`, `StreamProtocolError`, `InputRequired`, and `ObservationTimeout` distinguish transport, protocol, interaction, and observation failures from durable execution outcomes. Request timeout, stream idle timeout, observer timeout, and execution deadline are separate controls.

```bash
uv sync --extra dev --extra mcp
uv run pytest -m 'not integration'
```

Integration tests require `RELAY_TEST_URL`, `RELAY_TEST_API_KEY`, and a registered company server ID in `RELAY_TEST_MCP_SERVER_ID` for the tool scenarios. The complete repository runner provisions these values and distinguishes simulation, actual executable/local-provider, and credentialed acceptance evidence. Passing deterministic tests does not establish paid-provider behavior.

## PostgreSQL binding journal

Install `wkala[mcp,postgres]` and give `BackendMCP` a `state_url` containing your PostgreSQL URL. Registration revisions and signed invocation receipts survive backend restarts. `state_path` remains an optional local SQLite journal for standalone SDK applications; do not pass both options. The provided deployed customer backend uses PostgreSQL throughout. Business idempotency still belongs to your application transaction.
