# Ursly Go SDK

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

A typed, context-first client for the stateless Ursly v1 intent API. The module is `ursly.io/sdk/go`, the package is `ursly`, and `ursly.Version` identifies its version. Go 1.23 or newer is required. Runtime dependencies are entirely in the standard library.

The API matches a voice transcript or normalized motion gesture supplied by your adapter against your rules. It returns declarative intents. Your application explicitly dispatches them to registered handlers. This package does not acquire audio or video, recognize speech or gestures, run shell commands, or relay HTTP requests on the server.

## Install

Use the versioned Go SDK archive from the website's downloads when a Go release is available. The source repository is private; this module path is not distributed through a module proxy. Current source may be newer than a published download. Replace `<version>` with `release.version` in `/downloads/manifest.json`, and compare the archive's SHA-256 with the manifest before extracting.

```sh
# Linux:
sha256sum ursly-sdk-go-<version>.zip
# macOS equivalent: shasum -a 256 ursly-sdk-go-<version>.zip
mkdir -p third_party/ursly-go
unzip ursly-sdk-go-<version>.zip -d third_party/ursly-go
# The extracted go.mod must be at third_party/ursly-go/go.mod.
go mod edit -require=ursly.io/sdk/go@v<version> \
  -replace=ursly.io/sdk/go=./third_party/ursly-go
```

Run these commands in an application with its own `go.mod` (`go mod init example.com/myapp` creates one). A directory replacement needs no `go.sum` entry and no module proxy; the SDK can build with `GOPROXY=off`. Run `go mod tidy` after your code imports the package: before that, tidy removes unused requirements. For an authorized checkout, replace the module with that checkout's `sdk/go` directory.

## First request: resolve, inspect, dispatch

Save this as `main.go` after adding the dependency. Set `URSLY_API_URL` to your API host; there is no default destination. The public API host is `https://ursly.io`; pass it explicitly through `URSLY_API_URL`. The handler only prints a requested route, so the example compiles without an application router.

```go
package main

import (
    "context"
    "fmt"
    "os"
    "time"

    ursly "ursly.io/sdk/go"
)

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}

func run() error {
    client, err := ursly.New(os.Getenv("URSLY_API_URL"), ursly.WithTimeout(5*time.Second))
    if err != nil {
        return err
    }
    unregister := client.RegisterHandler(ursly.ActionNavigationOpen,
        func(_ context.Context, action ursly.Action, intent ursly.Intent) (any, error) {
            // Replace with an authorized operation in your application.
            fmt.Println("rule", intent.RuleID, "requested route", action.Target)
            return nil, nil
        })
    defer unregister()

    ctx := context.Background()
    req := ursly.ResolveRequest{
        Input: ursly.Input{Sense: ursly.SenseVoice, Transcript: "open home"},
        Rules: []ursly.Rule{{ID: "home", Match: "open home",
            Action: ursly.Action{Type: ursly.ActionNavigationOpen, Target: "/"}}},
    }
    resolution, err := client.Resolve(ctx, req) // One HTTP call; executes nothing.
    if err != nil {
        return err
    }
    fmt.Println("resolved", len(resolution.Intents), "intent(s)")
    executed, err := client.Dispatch(ctx, resolution) // Dispatches that same response.
    if err != nil {
        return err
    }
    fmt.Println("completed", len(executed.Results), "handler(s)")
    return nil
}
```

`ResolveAndDispatch(ctx, req)` is a convenience alternative when you do not need to inspect the resolution first. It makes its own resolve request; calling it after Resolve would resolve twice. [example_test.go](example_test.go) is an executable example backed by a local HTTP fixture.

## API reference

| Operation                       | Behavior                                                                                                   |
| ------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `New(baseURL, options...)`      | Constructs the client. `WithTimeout` changes the request deadline; `WithTransport` injects a RoundTripper. |
| `Capabilities(ctx)`             | GET `/api/v1/capabilities`; reports stages and input availability.                                         |
| `Actions(ctx)`                  | GET `/api/v1/actions`; returns the declarative action catalog.                                             |
| `Templates(ctx)`                | GET `/api/v1/templates`; returns editable, validated example requests.                                     |
| `Validate(ctx, req)`            | POST `/api/v1/validate`; returns `ValidationResponse{Valid: true}` or an error.                            |
| `Resolve(ctx, req)`             | POST `/api/v1/resolve`; returns validated intents and performs no effect.                                  |
| `Dispatch(ctx, resolution)`     | Validates and dispatches a supplied resolution without HTTP.                                               |
| `ResolveAndDispatch(ctx, req)`  | Resolves once, then dispatches with the same context.                                                      |
| `RegisterHandler(type, fn)`     | Replaces that action type's handler and returns its unregister function.                                   |
| `Float64(value)`, `Bool(value)` | Builds pointers for optional confidence and enabled fields.                                                |
| `ErrorCode(err)`                | Extracts a stable SDK code through wrapped errors, or returns an empty string.                             |

Every context argument must be non-nil; use `context.Background()` without a caller context. New ignores nil options. A nil transport, including a typed nil pointer or function held in a RoundTripper interface, is a configuration error.

## Inputs, rules and actions

Use `Input{Sense: SenseVoice, Transcript: "..."}` or `Input{Sense: SenseMotion, Gesture: "swipe_left"}`. The other senses have no API input adapter. Confidence and MinConfidence are optional `*float64`; Enabled is an optional `*bool`.

| Action                                       | Required fields in `Action`                                   | Optional fields                                                                    |
| -------------------------------------------- | ------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| `ActionNavigationOpen` / `navigation.open`   | `Target`: application-relative path, at most 2048 UTF-8 bytes | None                                                                               |
| `ActionTextInsert` / `text.insert`           | `Text`: nonblank text, at most 4096 UTF-8 bytes               | None                                                                               |
| `ActionMediaPlay` / `media.play`             | `Target`: identifier                                          | None                                                                               |
| `ActionMediaPause` / `media.pause`           | `Target`: identifier                                          | None                                                                               |
| `ActionSceneFocus` / `scene.focus`           | `Target`: identifier                                          | None                                                                               |
| `ActionWorkflowTrigger` / `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 allows up to 32 rules with unique IDs. Voice transcripts and rule matches allow up to 4096 UTF-8 bytes. Text cannot be blank or 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. Set only fields belonging to an action's type.

The API matches normalized input text, preserves rule order and defaults omitted Enabled to true. Confidence values are in [0, 1]. A rule with a minimum matches only when a confidence was supplied and is at least that minimum. No confidence does not satisfy even a zero threshold.

JSON omission and null both decode to nil confidence pointers, and nil pointers encode by omission; the API treats both states identically. Nil Rules and nil Intents encode as empty arrays. Enabled and workflow parameters may be omitted, but API response validation rejects explicit null for them. Semantic request errors come from the API; Validate checks editable requests without resolving.

## Dispatch and concurrency

Handlers receive the context, action and intent and return `(any, error)`. The client and its registry are safe for concurrent use. Transport and handler implementations must support the concurrency with which your application invokes them.

Dispatch validates a copy of the resolution and preflights every handler. It snapshots the handler functions, releases the registry lock, then executes them in intent order. Registry changes affect subsequent dispatches. An unregister function removes only its own current registration; an old function cannot remove a replacement. RegisterHandler panics for an unknown action type or nil handler.

The first handler error stops later effects. Completed effects are not retried or rolled back, and a separate second Dispatch can execute the same actions again. The SDK does not recover handler panics. Handlers own authorization, deduplication across calls, and the safety of their effects.

## Transport, timeout and cancellation

The base URL must be HTTP(S) with a host and may include a proxy prefix. Trailing slashes are trimmed. Credentials, queries and fragments are rejected with `*ConfigurationError`. Calls target `<base>/api/v1/<endpoint>`.

The default timeout is 10 seconds; WithTimeout must be positive. It covers waiting for response headers and body. Requests send `Accept: application/json`, JSON `Content-Type` for POST, and `User-Agent: ursly-sdk-go/<version>`.

WithTransport accepts an `http.RoundTripper`. The client wraps it in an `http.Client` that refuses redirects; a 3xx response becomes `*APIError`. The SDK schedules no retries. Go's standard HTTP transport can retry an idempotent GET after a failure on a reused connection; it does not automatically replay these POST requests. Custom RoundTrippers control their own behavior and must not introduce redirects or unexpected replay.

Caller cancellation, including the caller's own deadline, returns `*CancelledError` (code `cancelled`). Expiry of the client's request timeout returns `*TimeoutError` (code `timeout`). Waiting stops even if a transport or response body ignores its context; that exchange may finish in a background goroutine. Such a transport must eventually return to release its resources. A sent request cannot be unsent, and an abandoned response never dispatches actions.

Dispatch checks cancellation after validation and all-handler preflight, including with zero intents, and before each handler. It does not interrupt a handler already running or impose the client timeout on handler work. Handlers should use the supplied context for their own cancellable work.

Request encoding disables HTML escaping and measures exact bytes sent. More than 32768 bytes fails before sending as `payload_too_large`; unencodable values such as non-finite confidence fail as `invalid_request`. The client reads at most 1 MiB plus one byte to detect an oversized response, then returns `*InvalidResponseError`.

## Errors and response contracts

| Error type / code                                      | Meaning                                                                            |
| ------------------------------------------------------ | ---------------------------------------------------------------------------------- |
| `*APIError`                                            | Non-2xx HTTP response; Status and server Code/Message, with `http_error` fallback. |
| `*ConfigurationError` / `invalid_configuration`        | Invalid URL, nonpositive timeout or nil transport.                                 |
| `*SDKError` / `invalid_request` or `payload_too_large` | Local request encoding or size failure.                                            |
| `*InvalidResponseError` / `invalid_response`           | Oversized/malformed response or invalid supplied resolution.                       |
| `*TimeoutError` / `timeout`                            | Client request deadline; unwraps to `context.DeadlineExceeded`.                    |
| `*CancelledError` / `cancelled`                        | Caller context ended; unwraps to its cancellation/deadline error.                  |
| `*TransportError` / `transport_error`                  | Sanitized network/transport failure.                                               |
| `*MissingHandlerError` / `missing_handler`             | Handler absent; no effect has run.                                                 |
| `*HandlerError` / `handler_error`                      | Handler failed; carries ActionType/RuleID and unwraps to its cause.                |

All error types embed SDKError. Use `errors.As` for details, `errors.Is` for cancellation/handler causes, or `ursly.ErrorCode(err)`. HTTP 400 `invalid_request` is an API validation error; HTTP 422 `sense_unavailable` identifies an unsupported adapter. The SDK's transport/handler messages hide underlying details, and it does not log request data. API error messages come from the server.

Catalogs and templates are validated before return. Resolutions need consistent matched/unmatched status and at most 32 intents with valid, unique rule IDs. Actions reject unknown fields, external navigation, invalid identifiers and oversized UTF-8 text before handlers run. Duplicate JSON object fields use the last decoded value; typed responses are built only from that validated value, preventing earlier unvalidated fields from merging into maps or structs. Direct Dispatch applies the same validation to constructed resolutions.

## Development and evidence

```sh
cd sdk/go
gofmt -l .
go vet ./...
go test ./...
go test -race -coverprofile=coverage.out ./...
URSLY_TEST_URL=http://127.0.0.1:PORT go test -run Real -v ./...
```

Real-API tests require an isolated running Ursly API and explicitly skip without `URSLY_TEST_URL`. Default tests use injected transports and real local HTTP servers. Live tests cover all five endpoints, six actions for voice/motion, normalization, confidence boundaries, disabled rules, 32/33-rule limits, all unavailable senses and the shared validation corpus. [SOURCES.md](SOURCES.md) records tested runtimes, references and evidence boundaries.

## Product and release boundaries

Voice production and motion in development are founder-reported stages, not proof of hardware performance, recognition accuracy or commercial integration. 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 and prevents duplicate JSON decoding from introducing unvalidated fields. Updating source does not modify older archives; distribution requires a checked, versioned release.

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