# Ursly SDK integration guide

This guide describes the current source contract for the four maintained SDKs. The API resolves an application-supplied transcript or gesture identifier into action intents. Your acquisition adapter supplies the input; your registered handlers own its effects. The resolver does not capture audio/video, recognize gestures, perform language-model inference, or execute actions.

The website's synthetic experience and founder-reported product stages do not establish acquisition accuracy. Voice and motion accept supplied inputs. Smell, taste, view and touch return HTTP 422 `sense_unavailable` in API v1.

## Choose source, release and environment explicitly

The API prefix `/api/v1` and SDK package versions are independent. Current public package names began with developer distribution 0.2.0. Immutable 0.1.0 archives retain earlier names and code. Their compatibility must be measured against the deployed API; the current source manual does not describe every behavior of an older archive. Catalog reads from published 0.1.0 TypeScript/Python packages were verified separately in the October 19, 2026 audit; that result is not a validation of all archived features.

Read `/downloads/manifest.json` before installation. Its `release.version`, `release.sourceSha`, file kind, exact path, byte size and SHA-256 identify the artifact. Verify the downloaded bytes, inspect the manual and package metadata inside the archive, and pin the version in your application's lockfile. A source checkout or green local test does not prove a package was published. An absent kind means that manifest offers no package for that language. Never guess a registry name, filename or release URL.

| Language   | Current package / import                  | Manifest kind    | Declared runtime                                   |
| ---------- | ----------------------------------------- | ---------------- | -------------------------------------------------- |
| TypeScript | `@ursly/sdk`; `UrslyClient`               | `sdk-typescript` | Node 22+ or a browser with Fetch/AbortController   |
| Python     | distribution `ursly-sdk`; import `ursly`  | `sdk-python`     | Python 3.11+; standard library                     |
| Go         | module `ursly.io/sdk/go`; package `ursly` | `sdk-go`         | Go 1.23+; standard library                         |
| Rust       | package `ursly-sdk`; library `ursly`      | `sdk-rust`       | Rust 1.85+ declared; default blocking HTTP adapter |

Runtime declarations are package requirements, not evidence that every runtime/platform combination was tested. Release evidence records actual runs. Neighboring artifacts `typescript.md`, `python.md`, `go.md` and `rust.md` contain language-specific installation and signatures; archived packages carry their own manuals.

### Configure the base URL

Every constructor requires an explicit HTTP(S) base URL. No production endpoint is selected by default. Use the origin of your own running development server, or explicitly choose the public API origin `https://ursly.io`.

Pass the origin or an intentional reverse-proxy prefix, **without appending `/api/v1`**. The SDK appends that path. For example, `https://example.test/ursly` produces `https://example.test/ursly/api/v1/resolve`; your proxy must actually route that prefix. Credentials, query strings and fragments are invalid base-URL configuration. Deployed applications should retain HTTPS certificate verification.

| Configuration      | TypeScript                   | Python                                      | Go                                 | Rust                                                   |
| ------------------ | ---------------------------- | ------------------------------------------- | ---------------------------------- | ------------------------------------------------------ |
| Constructor        | `new UrslyClient({baseUrl})` | `UrslyClient(base_url=...)`                 | `ursly.New(baseURL, options...)`   | `Client::new(base_url)` or `Client::builder(base_url)` |
| Timeout            | `timeoutMs`, milliseconds    | `timeout`, seconds                          | `WithTimeout(time.Duration)`       | builder `.timeout(Duration)`                           |
| Injected transport | `fetch`                      | `transport(method, url, body, timeout)`     | `WithTransport(http.RoundTripper)` | builder `.transport(impl Transport)`                   |
| Cancellation       | per-call `{signal}`          | per-call `cancel_event` (`threading.Event`) | per-call `context.Context`         | `client.with_cancel(&AtomicBool)`                      |

The default request timeout is 10 seconds. It bounds HTTP work according to the adapter, not application handler duration. Python can stop waiting while its transport thread continues. Go bounds the caller's wait even for a custom transport that ignores context. Rust cancellation is cooperative before/after transport and before handlers; custom Rust transports must enforce the supplied deadline. Cancellation never proves that a server did not receive a request or reverses an effect already completed by a handler.

## Every client operation

| Purpose                          | TypeScript                    | Python                          | Go                                 | Rust                             |
| -------------------------------- | ----------------------------- | ------------------------------- | ---------------------------------- | -------------------------------- |
| Read supplied-input availability | `capabilities()`              | `capabilities()`                | `Capabilities(ctx)`                | `capabilities()`                 |
| Read the six action definitions  | `actions()`                   | `actions()`                     | `Actions(ctx)`                     | `actions()`                      |
| Read complete example requests   | `templates()`                 | `templates()`                   | `Templates(ctx)`                   | `templates()`                    |
| Validate input and all rules     | `validate(request)`           | `validate(request)`             | `Validate(ctx, request)`           | `validate(&request)`             |
| Resolve without executing        | `resolve(request)`            | `resolve(request)`              | `Resolve(ctx, request)`            | `resolve(&request)`              |
| Execute an existing resolution   | `dispatch(resolution)`        | `dispatch(resolution)`          | `Dispatch(ctx, resolution)`        | `dispatch(&resolution)`          |
| Resolve once, then dispatch      | `resolveAndDispatch(request)` | `resolve_and_dispatch(request)` | `ResolveAndDispatch(ctx, request)` | `resolve_and_dispatch(&request)` |

TypeScript methods return promises. Python, Go and the Rust SDK use synchronous/blocking calls. The CLI is separate: it prints API results and has no application handler registry. The SDKs do not wrap newsletter, inquiry, persistence or health endpoints.

Catalogs use GET; validation and resolution use POST. Dispatch is local and makes no HTTP request. After inspecting a resolution, pass it to dispatch. Calling the combined method afterwards would resolve the input a second time. A validation result `{"valid":true}` confirms the supplied input and all rules are valid; it does not guarantee a match, a registered handler or successful execution.

## Write a rule and predict its result

```json
{
  "input": {
    "sense": "voice",
    "transcript": "  OPEN   HOME  ",
    "confidence": 0.9
  },
  "rules": [
    {
      "id": "home",
      "match": "open home",
      "enabled": true,
      "minConfidence": 0.9,
      "action": { "type": "navigation.open", "target": "/home" }
    }
  ]
}
```

The resolver collapses Unicode whitespace, trims and lowercases both input and match, then compares for equality. There is no fuzzy/substring matching, synonym expansion or regular expression evaluation. This request matches at the confidence boundary:

```json
{
  "status": "matched",
  "intents": [
    {
      "ruleId": "home",
      "action": { "type": "navigation.open", "target": "/home" }
    }
  ],
  "execution": "client_handler_required"
}
```

For motion, use `{"sense":"motion","gesture":"swipe_left"}` and match `swipe_left`. Your adapter has already recognized the gesture.

Every matching enabled rule emits an intent in supplied order; there is no first-match stop. Distinct rule IDs may emit the same action more than once. Missing `enabled` means true; false disables matching, but disabled rules must still be valid. Missing/null minimum confidence imposes no threshold. A numeric threshold requires numeric input confidence at least as high; absent/null input confidence then produces no match, not a validation error. Confidence comes from your adapter and is not an SDK accuracy score.

Zero rules is valid and returns `unmatched` with an empty intents array. Any valid input without an enabled match does the same. Unknown request/action fields and invalid enum variants are rejected. Rule IDs must be unique within the request.

### Payload and transport limits

Text maxima count **UTF-8 bytes**, not character counts. Text must contain a non-whitespace value and no non-whitespace control characters.

| Field or boundary                                                     | v1 constraint                                                                                                                                  |
| --------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| Encoded POST request                                                  | At most 32,768 bytes, including JSON syntax                                                                                                    |
| Rules                                                                 | 0–32; every rule validated, including disabled rules                                                                                           |
| Voice transcript, rule match, inserted text                           | At most 4,096 UTF-8 bytes each                                                                                                                 |
| Gesture, rule ID, media/scene/workflow target, workflow parameter key | 1–64 ASCII bytes matching `[A-Za-z0-9._:-]+`                                                                                                   |
| Input confidence and minimum confidence                               | Finite number in [0, 1], or omitted/null                                                                                                       |
| Navigation target                                                     | At most 2,048 bytes; starts with `/`; no whitespace/backslash, no `//` in path, no dot/double-dot path segments including percent-encoded dots |
| Workflow parameters                                                   | Optional string map; at most 16 entries; each value at most 256 UTF-8 bytes                                                                    |
| Bundled HTTP response readers                                         | At most 1 MiB                                                                                                                                  |
| Resolution returned to handlers                                       | Valid status/execution and action payloads; at most 32 intents with unique valid rule IDs                                                      |

Queries and fragments are allowed in application-relative navigation targets; path checks apply before `?` or `#`. Your router still owns authorization and destination allowlists.

## The six action types

| Type               | Payload                                                                    | Application handler                                                               |
| ------------------ | -------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
| `navigation.open`  | `target`: application-relative path                                        | Route after permission checks                                                     |
| `text.insert`      | `text`: plain text                                                         | Insert through the editor's text API, without interpreting HTML                   |
| `media.play`       | `target`: registered media identifier                                      | Look up allowed media and start it                                                |
| `media.pause`      | `target`: registered media identifier                                      | Look up allowed media and pause it                                                |
| `scene.focus`      | `target`: registered scene identifier                                      | Focus an allowed scene                                                            |
| `workflow.trigger` | `target`: registered workflow identifier; optional `parameters` string map | Invoke an application-owned workflow with appropriate validation and confirmation |

A workflow target is an identifier, not a URL or shell command. The server never calls arbitrary webhooks. Never evaluate targets or payloads as code.

## Register, dispatch and clean up

Handlers receive the action and its intent, including the rule ID. One handler is current per action type; registering again replaces it. The SDK validates the resolution and checks every intent has a handler **before any handler runs**. Handlers then run sequentially in intent order. TypeScript awaits promises; the other maintained interfaces are synchronous.

On success, dispatch returns the resolution and one result per handler. A missing handler prevents execution from starting. A handler failure stops later handlers; previous effects remain. The SDK does not roll them back or retry them. Cooperative cancellation and request timeout do not interrupt arbitrary handler code; bound long-running application work inside the handler.

| Language   | Register                                                 | Unregister                                                                    |
| ---------- | -------------------------------------------------------- | ----------------------------------------------------------------------------- |
| TypeScript | `const remove = client.registerHandler(type, handler)`   | `remove()`; an obsolete registration cannot remove its replacement            |
| Python     | `client.register_handler(type, handler)`                 | `client.unregister_handler(type)` removes the current handler for that type   |
| Go         | `remove := client.RegisterHandler(type, handler)`        | `remove()`; an obsolete registration cannot remove its replacement            |
| Rust       | `let id = client.register_handler(action_type, handler)` | `client.unregister_handler(id)`; an obsolete ID cannot remove its replacement |

Dispatching the same resolution twice repeats its effects. Rule IDs are not execution IDs or idempotency keys. Consequential workflows need application-owned authorization, confirmation, deduplication and recovery. Log only the operational identifiers your application needs.

## Handle failures by code

Use typed errors and stable codes rather than parsing messages. Only API rejection errors carry an HTTP status; configuration, cancellation and handler failures may involve no HTTP response.

| Code                               | Meaning and response                                                                                         |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| `invalid_configuration`            | Fix the base URL or timeout before sending                                                                   |
| `invalid_request`                  | Fix serialization or server-validation errors; use the error type to distinguish local failure from HTTP 400 |
| `invalid_json`                     | HTTP 400: compare malformed/unknown fields and enum shape to the contract                                    |
| `payload_too_large`                | Reduce the encoded body; local rejection sends nothing, server rejection is HTTP 413                         |
| `unsupported_media_type`           | HTTP 415: a custom transport must send `application/json`                                                    |
| `sense_unavailable`                | HTTP 422: leave this sense unavailable until a supported contract exists                                     |
| `rate_limited`                     | HTTP 429: application-controlled backoff; no handler replay                                                  |
| `not_found` / `method_not_allowed` | HTTP 404 / 405: check origin, prefix and verb                                                                |
| `unavailable` / `internal_error`   | HTTP 503: surface temporary service failure                                                                  |
| `http_error`                       | Non-2xx response without the normal error body; inspect status and proxy configuration                       |
| `timeout`                          | Request deadline elapsed; delivery remains uncertain                                                         |
| `cancelled`                        | Caller cancellation; completed effects remain                                                                |
| `transport_error`                  | Check connectivity, TLS and custom adapter behavior                                                          |
| `invalid_response`                 | Stop before dispatch; response failed the contract/reader limit or package compatibility differs             |
| `missing_handler`                  | Register every required supported action type before dispatch                                                |
| `handler_error`                    | Diagnose using action type/rule ID; reconcile prior effects before retrying                                  |

TypeScript/Python expose classes including `ApiError` and `HandlerError`. Go supports `errors.As` for concrete errors. Rust exposes `ursly::Error` variants and `.code()`. Handler messages are generic. Go can retain the underlying handler error in its chain, so application logging still needs care.

The SDK schedules no retry loop. Bundled adapters refuse redirects; configure the final intended origin. Go's standard HTTP transport can retry an idempotent GET on a reused connection, and injected transports own their network behavior. Do not introduce automatic replay of resolver POSTs or handler effects. POST validation/resolution calls share an address rate-limit bucket; invalid requests can consume its budget. Deployment configuration determines the allowance.

## Verify the integration

The SDK page and Intent Composer provide complete print-only source examples. Each resolves once and dispatches that response without a second request. Success proves that supplied-input/handler path, not a real acquisition system.

Cover these application boundaries:

1. Read all catalogs and match feature availability to the returned capabilities.
2. Validate/resolve both supplied-input senses with all six action types.
3. Check unmatched inputs, disabled rules, multiple matches and confidence below/equal/above threshold.
4. Reject malformed/oversize requests, unsupported senses and malformed responses before dispatch.
5. Exercise missing handlers, replacement/unregister, ordered results and partial failure.
6. Cancel before a request and between handlers; test timeout and transport failure.
7. Test each real router/editor/media/workflow handler with its permissions and recovery behavior.

Use injected transports for deterministic failures, then run exact copied code against a real local API. Mock-only results do not establish server compatibility. The repository's developer-snippet tests check emitted public names and the single-resolution flow; the independent SDK live-contract suites use `URSLY_TEST_URL`. Language manuals give commands. Record source revision, runtime, command and result with release evidence.

The versioned intent API is public and requires no API key. Its CORS policy does not allow credentialed cross-origin calls. The resolver does not persist inputs, but infrastructure may retain operational request metadata. Contact capture has separate consent/persistence rules. No protected-health-information service or compliance certification is established by this SDK.

## Contract sources

Runtime behavior comes from `crates/sense-domain/src/lib.rs`, routes from `crates/sense-domain/src/api.rs`, and HTTP adapters from `src/sense_api.rs` and `cloudflare-worker/src/sense_api.rs`. Four independent SDK implementations live under `sdk/`. Generated OpenAPI, catalogs and templates accompany this guide. Review this narrative when those contracts change.
