# Ursly Rust SDK

Public documentation: [developer.ursly.io](https://developer.ursly.io/).

A typed, synchronous client for the stateless Ursly v1 intent API. The package is `ursly-sdk`; Rust imports the library as `ursly`. The source declares Rust 1.85 and edition 2024. The default `http` feature supplies a blocking reqwest/Rustls adapter. With `default-features = false`, the crate depends on serde, serde_json and url, and your application supplies a transport.

The API matches an explicit voice transcript or normalized motion gesture against your rules and returns declarative intents. Your application decides when to execute them through registered handlers. The SDK does not acquire audio or video, recognize speech or gestures, execute shell commands, or relay HTTP requests on the server.

## Install

Use the versioned `.crate` archive from the website's downloads when a Rust SDK release is available. The archive is produced by `cargo package`; this crate is not published to crates.io. The source repository is private, and the checked source version can be newer than the published download. Read the download manifest and compare its SHA-256 before extracting.

Replace `<version>` below with the archive's version; `release.version` in `/downloads/manifest.json` identifies the published release.

```sh
# Linux:
sha256sum ursly-sdk-<version>.crate
# macOS equivalent: shasum -a 256 ursly-sdk-<version>.crate
mkdir -p vendor
tar -xzf ursly-sdk-<version>.crate -C vendor
```

```toml
[dependencies]
ursly-sdk = { path = "vendor/ursly-sdk-<version>" }
```

Cargo still needs this crate's dependencies in its registry cache or a configured vendor directory. A path dependency alone does not make a fresh Rust build offline. For an authorized checkout, point the dependency at `sdk/rust`.

## First request: resolve, inspect, dispatch

Save this as `src/main.rs` in your application after adding the dependency. It uses a print-only handler so the example has no application navigation side effect. Set `URSLY_API_URL` to your API host; the client has no default destination. The public API host is `https://ursly.io`; pass it explicitly through `URSLY_API_URL`.

```rust
use std::time::Duration;
use ursly::{Action, ActionRule, ActionType, Client, ResolveRequest, SenseInput, Value};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let base = std::env::var("URSLY_API_URL")?;
    let client = Client::builder(base)
        .timeout(Duration::from_secs(5))
        .build()?;
    let registration = client.register_handler(ActionType::NavigationOpen, |action, intent| {
        if let Action::NavigationOpen { target } = action {
            // Replace with an authorized operation in your application.
            println!("rule {} requested route {target}", intent.rule_id);
        }
        Ok(Value::Null)
    });
    let request = ResolveRequest::new(
        SenseInput::voice("open home"),
        vec![ActionRule::new(
            "home",
            "open home",
            Action::NavigationOpen { target: "/".into() },
        )],
    );
    let resolution = client.resolve(&request)?; // One HTTP call; executes nothing.
    println!("resolved {} intent(s)", resolution.intents.len());
    let executed = client.dispatch(&resolution)?; // Dispatches that same response.
    println!("completed {} handler(s)", executed.results.len());
    client.unregister_handler(registration);
    Ok(())
}
```

`resolve_and_dispatch(&request)` is the convenience alternative when your application does not need to inspect the resolution first. It makes its own resolve request. Calling it after `resolve` would resolve twice.

## API reference

| Operation                        | Behavior                                                                                 |
| -------------------------------- | ---------------------------------------------------------------------------------------- |
| `Client::new(base_url)`          | Builds the default HTTP client; available with the `http` feature.                       |
| `Client::builder(base_url)`      | Configures `timeout` and an optional injected `transport`, then `build()`.               |
| `base_url()`, `timeout()`        | Exposes the normalized base URL and configured request deadline.                         |
| `capabilities()`                 | GET `/api/v1/capabilities`; reports sense stages and input availability.                 |
| `actions()`                      | GET `/api/v1/actions`; returns the declarative action catalog.                           |
| `templates()`                    | GET `/api/v1/templates`; returns editable, validated example requests.                   |
| `validate(&request)`             | POST `/api/v1/validate`; returns `ValidationResponse { valid: true }` or an error.       |
| `resolve(&request)`              | POST `/api/v1/resolve`; returns validated intents and performs no effect.                |
| `dispatch(&resolution)`          | Validates and dispatches a supplied resolution without an HTTP request.                  |
| `resolve_and_dispatch(&request)` | Resolves once, then dispatches with the same cancellation view.                          |
| `register_handler(type, fn)`     | Replaces that action type's handler and returns a `HandlerId`.                           |
| `unregister_handler(id)`         | Removes only that exact registration; a stale or foreign ID cannot remove a replacement. |
| `with_cancel(&AtomicBool)`       | Returns a `Cancellable` view exposing all five API calls and both dispatch methods.      |

Handlers are synchronous `Send + Sync` closures receiving `&Action` and `&Intent`, returning `Result<Value, Box<dyn Error + Send + Sync>>`. The client is `Send + Sync` and can be shared with `Arc<Client>`. Dispatch snapshots the handler registry and checks that every intent has a handler before any handler runs. Registering or removing handlers during a dispatch affects subsequent dispatches.

A handler error stops later handlers. Completed effects are not retried or rolled back, and there is no persisted deduplication between separate calls to `dispatch`. A panicking handler unwinds through dispatch; return `Err` for expected failures. Handlers own authorization and the safety of every effect.

## Inputs, rules and actions

Use `SenseInput::voice(transcript)` or `SenseInput::motion("swipe_left")`. `with_confidence(score)` supplies the adapter's confidence for those two inputs; it does not add fields to unavailable senses. `sense()` identifies the input channel. `ActionRule::new`, `with_enabled` and `with_min_confidence` configure rules; `Action::action_type()`, `ActionType::as_str()` and `Display` expose the action's v1 identifier.

| Action             | Required payload                                              | Optional payload                                                                   |
| ------------------ | ------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| `navigation.open`  | `target`: application-relative path, at most 2048 UTF-8 bytes | None                                                                               |
| `text.insert`      | `text`: nonblank text, at most 4096 UTF-8 bytes               | None                                                                               |
| `media.play`       | `target`: identifier                                          | None                                                                               |
| `media.pause`      | `target`: identifier                                          | None                                                                               |
| `scene.focus`      | `target`: identifier                                          | None                                                                               |
| `workflow.trigger` | `target`: identifier                                          | `parameters`: up to 16 identifier/string pairs, each value at most 256 UTF-8 bytes |

Identifiers match `[A-Za-z0-9._:-]{1,64}`. A request can contain at most 32 rules with unique IDs. Voice transcripts and rule matches allow up to 4096 UTF-8 bytes. Text is nonblank and cannot contain control characters other than whitespace. Navigation paths start with `/`, contain no backslash or whitespace, and have no `//`, `.` or `..` path segment, including `%2e` spellings; query and fragment portions can carry ordinary URL values.

The API matches normalized text and preserves rule order. Omitted `enabled` means enabled. Confidence and minimum confidence range from 0 to 1. A threshold matches when the supplied confidence is at least the minimum; without confidence, a rule with a minimum does not match, even when that minimum is zero.

Rust preserves three states for confidence fields: omitted (`None`), JSON `null` (`Some(None)`), and a number (`Some(Some(score))`). Omission and null both mean no supplied confidence to the API. `enabled` and workflow `parameters` may be omitted but cannot be null. Non-finite confidence values are rejected locally as `invalid_request`. Other semantic request errors are reported by the API, so `validate` remains useful for editable requests.

## Transport, cancellation and errors

The required base URL accepts HTTP(S) and a proxy path prefix. Embedded credentials, query strings and fragments are rejected. Trailing slashes are trimmed. Requests go to `<base>/api/v1/<endpoint>`.

The default timeout is 10 seconds, must be nonzero, and cannot exceed 2^31 - 1 milliseconds. The default HTTP adapter applies the deadline from connecting through reading the response body, sends `Accept: application/json`, JSON `Content-Type` for POST, and `User-Agent: ursly-sdk-rust/<version>`. It follows no redirect and schedules no retry. Redirect responses become API errors with their 3xx status.

`with_cancel` checks its flag before sending, after the blocking transport returns, after dispatch preflight (including an empty resolution), and before every handler. Cancellation does not interrupt a blocking network call or a handler already running. An in-flight response is discarded once the transport returns. Invalid-resolution and missing-handler checks precede the dispatch cancellation check. The timeout applies to HTTP requests; it does not impose a deadline on handler work.

An injected transport implements `Transport`, or a closure `Fn(&TransportRequest) -> Result<TransportResponse, Error>`. Its request contains the method, full URL, encoded body and deadline. It must enforce its own I/O deadline and avoid retries and redirects; the synchronous client cannot forcibly stop a custom transport.

| Error/code                                | Meaning                                                                            |
| ----------------------------------------- | ---------------------------------------------------------------------------------- |
| `Error::Api { status, code, message }`    | Non-2xx response; preserves the server's code/message, with `http_error` fallback. |
| `invalid_configuration`                   | Invalid base URL or timeout, or no transport when HTTP is disabled.                |
| `invalid_request`                         | A request cannot be represented as JSON, such as a non-finite confidence.          |
| `payload_too_large`                       | Encoded request exceeds 32768 bytes; nothing is sent.                              |
| `invalid_response`                        | Response exceeds 1 MiB or violates the v1 response contract.                       |
| `timeout`, `cancelled`, `transport_error` | Deadline, caller cancellation or sanitized transport failure.                      |
| `missing_handler`                         | At least one action lacks a handler; no handler has run.                           |
| `handler_error`                           | A handler failed; later handlers do not run.                                       |

Use pattern matching on `Error` and `Error::code()` for application handling. HTTP 400 `invalid_request` is an API validation rejection; HTTP 422 `sense_unavailable` identifies an input adapter that does not exist. The SDK does not log requests, and its own transport/handler error messages omit underlying details. API error messages are supplied by the server.

Every catalog/template response is validated before return. Returned and directly dispatched resolutions must have a consistent matched/unmatched status and at most 32 intents with unique valid rule IDs. Invalid action fields or values cannot reach a handler. Re-dispatching the same valid resolution is still an explicit new request to your application's handlers.

## Async applications and optional HTTP

Build, use and drop a reqwest blocking client outside async runtime threads. Share it with `Arc` and move blocking work to `tokio::task::spawn_blocking`:

```rust
use std::sync::Arc;

let client = Arc::new(
    tokio::task::spawn_blocking(|| Client::new("https://YOUR-API-HOST")).await??,
);
let worker = Arc::clone(&client);
let resolution = tokio::task::spawn_blocking(move || worker.resolve(&request)).await??;
// When disposing of the last owner, move its drop to a blocking thread too.
tokio::task::spawn_blocking(move || drop(client)).await?;
```

This fragment assumes a Tokio runtime, the SDK imports, and an owned `request`. Dropping the future returned by `spawn_blocking` does not stop the request. Use the cancellation view to discard its outcome and prevent dispatch.

To omit the built-in HTTP adapter:

```toml
[dependencies]
ursly-sdk = { path = "vendor/ursly-sdk-<version>", default-features = false }
```

Then supply `Client::builder(base).transport(your_transport).build()?`; `Client::new` and `HttpTransport` are unavailable in this configuration.

## Development and evidence

Run from the repository root:

```sh
cargo fmt --manifest-path sdk/rust/Cargo.toml --all --check
cargo clippy --manifest-path sdk/rust/Cargo.toml --locked --all-targets --all-features -- -D warnings
cargo clippy --manifest-path sdk/rust/Cargo.toml --locked --no-default-features --all-targets -- -D warnings
cargo test --manifest-path sdk/rust/Cargo.toml --locked
cargo test --manifest-path sdk/rust/Cargo.toml --locked --no-default-features
URSLY_TEST_URL=http://127.0.0.1:PORT cargo test --manifest-path sdk/rust/Cargo.toml --locked --test real_api
cargo package --manifest-path sdk/rust/Cargo.toml --locked
```

The real-API tests require an isolated running Ursly API. Without `URSLY_TEST_URL`, those tests print a skip message and return; a successful default test command alone does not establish server integration. Offline tests exercise injected transports and local HTTP servers. The live matrix covers all five endpoints, all six actions under voice and motion, confidence boundaries, rule limits and every unavailable sense.

`cargo package` writes `sdk/rust/target/package/ursly-sdk-<version>.crate` unless `CARGO_TARGET_DIR` overrides the target directory. Cargo requires a clean checkout by default; use `--allow-dirty` only for an explicitly local audit package. This is an independent Cargo workspace with its own lockfile. [SOURCES.md](SOURCES.md) records tested versions, references and evidence limits.

## Product and release boundaries

Voice production and motion in development describe founder-reported product stages. They do not certify hardware, recognition accuracy or commercial integrations. Smell, taste, view and touch return HTTP 422 `sense_unavailable`.

This SDK is new since the immutable 0.1.0 developer release. Current source rejects unsafe navigation paths and malformed intent identities; older published archives are not modified by a source fix. A checked, versioned release is required to distribute changes.

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