# Ursly Python SDK

A typed, synchronous client for the stateless Ursly v1 intent API, with zero runtime dependencies on Python 3.11+. The SDK accepts explicit voice transcripts and normalized motion gestures. Applications supply and authorize action handlers.

Public reference: [developer.ursly.io](https://developer.ursly.io/). The public API host is `https://ursly.io`; pass it explicitly as `base_url`, because the client has no default destination. An application proxy prefix is supported.

## Install

Install the checked wheel downloaded from the developer website:

```sh
python -m pip install ./ursly_sdk-<version>-py3-none-any.whl
```

Replace `<version>` with `release.version` in `/downloads/manifest.json`. A wheel needs no build backend. The source archive `ursly_sdk-<version>.tar.gz` can also be installed, but pip then obtains setuptools to build it. The project name is `ursly-sdk`; the import is `ursly`.

This directory contains current source and may include changes newer than a published archive. Releases are checked archives; registry publication is separate and the package carries a private distribution classifier.

## First request

```python
from ursly import ResolveRequest, UrslyClient

client = UrslyClient(base_url="https://YOUR-API-HOST", timeout=5)


def navigation(action, intent):
    print("Requested route:", intent["ruleId"], action["target"])
    return action["target"]  # Your router owns navigation policy.


client.register_handler("navigation.open", navigation)
request: ResolveRequest = {
    "input": {"sense": "voice", "transcript": "  OPEN home  "},
    "rules": [
        {
            "id": "home",
            "match": "open home",
            "action": {"type": "navigation.open", "target": "/"},
        }
    ],
}

assert client.validate(request) == {"valid": True}
resolution = client.resolve(request)  # One resolve HTTP request; no handlers.
print(resolution["status"])  # matched
executed = client.dispatch(resolution)  # Uses the result above; no HTTP.
print(executed["results"])  # ["/"]
client.unregister_handler("navigation.open")
```

This handler only prints. `resolve()` never invokes handlers. When you do not need the intermediate result, `resolve_and_dispatch(request)` combines one resolve call with explicit dispatch. `ResolveRequest` and the other exported TypedDict contracts work with type checkers, and the package includes `py.typed`.

A complete source-checkout example is in [examples/quickstart.py](examples/quickstart.py). From the repository root, with an API already running on localhost:

```sh
PYTHONPATH=sdk/python/src URSLY_API_URL=http://127.0.0.1:8787 \
  python3 sdk/python/examples/quickstart.py
```

It validates, resolves once, dispatches a print-only handler and unregisters it. Output includes `matched` and results `['/']`. It exits with an explanatory message if `URSLY_API_URL` is unset. See the [repository README](../../README.md) for starting the service.

## Public methods and types

| Method                                                 | Result and behavior                                                                                                                       |
| ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `UrslyClient(base_url, *, timeout=10, transport=None)` | Validates the required base URL and timeout; optionally accepts a custom transport.                                                       |
| `capabilities(*, cancel_event=None)`                   | GET `/api/v1/capabilities`; stages, API availability and acquisition boundaries.                                                          |
| `actions(*, cancel_event=None)`                        | GET `/api/v1/actions`; six action definitions.                                                                                            |
| `templates(*, cancel_event=None)`                      | GET `/api/v1/templates`; validated, editable request examples.                                                                            |
| `validate(request, *, cancel_event=None)`              | POST `/api/v1/validate`; returns `{"valid": True}` or raises. Does not resolve or execute.                                                |
| `resolve(request, *, cancel_event=None)`               | POST `/api/v1/resolve`; returns a validated `ResolveResponse`.                                                                            |
| `register_handler(action_type, handler)`               | Registers or replaces one synchronous handler; returns `None`.                                                                            |
| `unregister_handler(action_type)`                      | Removes a handler if present; repeated removal is harmless.                                                                               |
| `dispatch(resolution, *, cancel_event=None)`           | Validates the resolution and all required handlers, then calls handlers in intent order. Returns `{"resolution": ..., "results": [...]}`. |
| `resolve_and_dispatch(request, *, cancel_event=None)`  | Resolves once, then dispatches with the same cancellation event.                                                                          |

Exported types include `Sense`, `ActionType`, `VoiceInput`, `MotionInput`, `UnavailableInput`, `TargetAction`, `TextAction`, `WorkflowAction`, `Action`, `ActionRule`, `ResolveRequest`, `Intent`, `ResolveResponse`, the catalog/result TypedDicts, `Transport` and `ActionHandler`.

A handler receives `(action, intent)`; its return value is appended to `results`. Handlers are synchronous: this client does not await coroutine functions. Every required handler is checked before the first effect. Handler failure stops later handlers; completed effects remain without retry or rollback. An unmatched response normally yields an empty results list. A cancelled unmatched dispatch raises cancellation.

## Requests, matching and actions

Matching compares complete normalized input and rule phrases: Unicode whitespace is collapsed and both strings are lowercased. It does not perform substring matching, recognition or inferred intent classification. Multiple matching rules return intents in rule order. `enabled` defaults to true. Disabled rules still need valid payloads.

Optional `confidence` and `minConfidence` accept omission or `None` (JSON null). Without a threshold, missing confidence does not prevent a match. With any threshold, including zero, the input needs explicit confidence at least that threshold. Confidence is supplied by your adapter.

| Action             | Required payload                                        | Application responsibility                |
| ------------------ | ------------------------------------------------------- | ----------------------------------------- |
| `navigation.open`  | `target`: origin-relative path, such as `/home`         | Router/navigation policy                  |
| `text.insert`      | `text`: nonblank text                                   | Destination editor and permissions        |
| `media.play`       | `target`: identifier                                    | Player and media lookup                   |
| `media.pause`      | `target`: identifier                                    | Player and media lookup                   |
| `scene.focus`      | `target`: identifier                                    | Scene/resource lookup                     |
| `workflow.trigger` | `target`: identifier; optional `parameters`: string map | Workflow authorization and implementation |

Voice input is `{"sense": "voice", "transcript": "go"}`. Motion input is `{"sense": "motion", "gesture": "swipe_left"}`; your adapter supplies a normalized gesture. The remaining senses—`smell`, `taste`, `view`, `touch`—return HTTP 422 with `sense_unavailable`.

### Contract limits

Lengths are UTF-8 bytes, except numeric counts. Identifiers are 1–64 ASCII characters from `A–Z a–z 0–9 . _ : -`.

| Field                                                               | Limit                                                         |
| ------------------------------------------------------------------- | ------------------------------------------------------------- |
| Encoded request body                                                | 32,768 bytes                                                  |
| Rules / returned intents                                            | At most 32; rule identifiers must be unique                   |
| Voice transcript, rule match, inserted text                         | Nonblank; at most 4,096 bytes                                 |
| Rule IDs, gesture IDs, resource/workflow targets and parameter keys | Identifier syntax above                                       |
| Navigation target                                                   | At most 2,048 bytes; starts with `/`                          |
| Workflow parameters                                                 | At most 16 entries; each value nonblank and at most 256 bytes |
| Confidence / minimum confidence                                     | Finite number in `[0, 1]`, omitted, or `None`                 |
| Default adapter response body                                       | At most 1 MiB (1,048,576 bytes)                               |

Navigation paths reject `//`, dot or dot-dot path segments (including `%2e` spellings), backslashes and whitespace. Queries and fragments in an action target are allowed. Non-whitespace control characters and unpaired surrogates are invalid in text.

The client checks JSON serializability, non-finite numbers and the encoded request cap before invoking a transport. The server validates request field/domain rules. Returned catalogs, templates and resolutions are validated before being returned; malformed actions, invalid or duplicate rule IDs and more than 32 intents are rejected before any handler.

## Transport, deadlines and cancellation

`base_url` must be HTTP(S), without embedded credentials, a query or a fragment; even a bare `?` or `#` is rejected. Proxy prefixes such as `https://example.test/proxy` are retained. The default timeout is 10 seconds and must be finite and positive.

`cancel_event` accepts a `threading.Event`. A set event prevents a request before sending. The client also checks it while waiting and before dispatching subsequent handlers:

```python
import threading
from ursly import RequestCancelledError, UrslyClient

client = UrslyClient("https://YOUR-API-HOST", timeout=5)
cancelled = threading.Event()
cancelled.set()
try:
    client.capabilities(cancel_event=cancelled)
except RequestCancelledError:
    print("Cancelled before sending")
```

HTTP work runs in a daemon worker. The client enforces an absolute waiting deadline, polling cancellation at intervals of at most about 50 ms while waiting. Timeout or cancellation ends the caller's wait; an already-started HTTP request or custom transport can finish in that worker. Its abandoned result cannot trigger `resolve_and_dispatch` handlers. Requests cannot be unsent.

The HTTP timeout does not limit handler execution. Dispatch checks cancellation after resolution validation/handler preflight and between handlers. An already-running synchronous handler completes under application control; handlers need their own interruption/deadline strategy. Cancellation cannot undo completed effects.

### Default urllib adapter

The default adapter uses JSON requests, `Accept: application/json` and POST `Content-Type: application/json`. Installed distributions identify themselves as `User-Agent: ursly-sdk/<installed-version>`; direct uninstalled source uses `ursly-sdk`.

Response reads are capped at 1 MiB. Successful bodies must decode as strict UTF-8 JSON; UTF-16/UTF-32 bodies and the non-JSON literals NaN/Infinity are rejected. Invalid success bodies raise `InvalidResponseError`. A non-JSON HTTP error body retains its HTTP status through `ApiError` with code `http_error`; an oversized body is an `InvalidResponseError`.

No request is retried and redirects are never followed. A redirect is an `ApiError` carrying its 3xx status.

### Injected transport

A custom transport implements this synchronous signature:

```python
from ursly import ResolveRequest, UrslyClient


def transport(
    method: str,
    url: str,
    body: ResolveRequest | None,
    timeout: float,
) -> tuple[int, object]:
    # A minimal test double; an application adapter performs its own bounded I/O.
    assert method == "POST"
    assert url == "https://example.test/api/v1/validate"
    assert body is not None
    assert timeout > 0
    return 200, {"valid": True}


client = UrslyClient("https://example.test", transport=transport)
assert client.validate(
    {"input": {"sense": "voice", "transcript": "go"}, "rules": []}
) == {"valid": True}
```

The callback receives the method, full endpoint URL, request object (or `None` for GET) and timeout in seconds; it returns an HTTP status and decoded JSON value. The SDK validates the returned contract and maps exceptions into typed errors. Falsey callable objects are valid transports; only `None` chooses the default adapter.

Custom transports own raw-byte decoding, response byte caps and bounded I/O. They run in the same daemon-worker/deadline mechanism. The client can stop waiting, but cannot forcibly stop arbitrary injected code.

## Errors and recovery

All SDK exceptions derive from `SDKError` and expose `code`. SDK-generated transport/handler messages omit the original exception text; API errors carry server-provided messages. The client does not print request bodies, secrets or credential-bearing URLs.

| Exception               | Code                        | Meaning                                                                        |
| ----------------------- | --------------------------- | ------------------------------------------------------------------------------ |
| `ConfigurationError`    | `invalid_configuration`     | Fix the base URL or timeout.                                                   |
| `SDKError`              | `invalid_request`           | Request JSON serialization failed, including non-finite numbers.               |
| `SDKError`              | `payload_too_large`         | Encoded request exceeds 32,768 bytes; transport was not called.                |
| `ApiError`              | Server code or `http_error` | Inspect `status` and `code`; includes invalid requests and unavailable senses. |
| `RequestTimeoutError`   | `timeout`                   | Client HTTP waiting deadline expired; server receipt is still possible.        |
| `RequestCancelledError` | `cancelled`                 | Caller cancelled; completed effects remain.                                    |
| `TransportError`        | `transport_error`           | Network/transport failure.                                                     |
| `InvalidResponseError`  | `invalid_response`          | Response decoding, size or contract failure.                                   |
| `MissingHandlerError`   | `missing_handler`           | Register `action_type`; no handler has run.                                    |
| `HandlerError`          | `handler_error`             | Handler for `action_type`/`rule_id` failed; earlier effects remain.            |

Non-string error-envelope codes/messages fall back to generic values. Decide whether any retry is appropriate in your application; the SDK never automatically retries.

## Verify and build

From the repository root, run the offline/injected tests and local HTTP adapter fixtures. Then enable real service coverage against an isolated server:

```sh
PYTHONPATH=sdk/python/src python3 -m unittest discover -s sdk/python/tests
PYTHONPATH=sdk/python/src URSLY_TEST_URL=http://127.0.0.1:8787 \
  python3 -m unittest discover -s sdk/python/tests
python3 -m compileall -q sdk/python/src sdk/python/examples
```

Without `URSLY_TEST_URL`, real service cases are explicitly skipped. With it, coverage includes every catalog/template, all six action types, voice/motion, unavailable senses, confidence/disabled rules, normalization and UTF-8/count boundaries. Default-adapter fixtures check redirects, decoding and byte caps; injected tests check deadlines, cancellation and handler lifecycle.

Use an isolated development environment for lint and packaging:

```sh
cd sdk/python
python3 -m venv .venv
.venv/bin/python -m pip install -e '.[dev]'
.venv/bin/ruff check .
.venv/bin/ruff format --check .
.venv/bin/python -m build --no-isolation
```

The `dev` extra pins the build backend and tools. The universal wheel includes `py.typed` and has no runtime dependency. Building a wheel/source archive does not publish it or update website downloads. [SOURCES.md](SOURCES.md) records version-matched references and evidence boundaries.

## Compatibility and product boundaries

Since 0.1.0, responses are validated before handlers; optional confidence values accept `None`; bare query/fragment URL markers are rejected; non-string API error fields use generic fallbacks. Product-stage types accept current `development` and historical `beta`.

Current source also rejects invalid/duplicate returned rule IDs and more than 32 intents, reports cancellation for an unmatched dispatch, respects falsey custom transports and enforces UTF-8/JSON decoding in the default adapter. These changes do not alter action ownership.

Voice “production” and motion “development” are founder-reported product stages. The SDK does not acquire microphone/camera data, perform recognition, validate sensors, execute a shell or relay server HTTP actions. Applications own authorization and all handler side effects.

## License

License terms have not yet been published. Public downloads do not grant an open-source license; the source repository remains private.
