# Ursly TypeScript SDK

An ESM client for the stateless Ursly v1 intent API, with bundled TypeScript declarations and no runtime dependencies. Supported runtimes are Node.js 22+ and browsers with native fetch and AbortController. The SDK accepts explicit voice transcripts and normalized motion gestures; applications own action execution.

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

## Install

Download the checked package and its manifest from the developer website, then install the local archive:

```sh
npm install ./ursly-sdk-<version>.tgz
```

Replace `<version>` with `release.version` in `/downloads/manifest.json`. This directory contains current source, which can include changes newer than a published archive. Registry publication is separate; the package is private and is distributed as checked archives. Use ESM `import`; there is no CommonJS `require` export.

## First request

```ts
import { UrslyClient, type ResolveRequest } from "@ursly/sdk";

const client = new UrslyClient({ baseUrl: "https://YOUR-API-HOST" });
const unregister = client.registerHandler(
  "navigation.open",
  ({ target }, intent) => {
    console.log("Requested route:", intent.ruleId, target);
    return target; // Your router decides whether and how to navigate.
  },
);
const request: ResolveRequest = {
  input: { sense: "voice", transcript: "  OPEN home  " },
  rules: [
    {
      id: "home",
      match: "open home",
      action: { type: "navigation.open", target: "/" },
    },
  ],
};

await client.validate(request); // { valid: true }; no action execution.
const resolution = await client.resolve(request); // One resolve HTTP request.
console.log(resolution.status); // "matched"
const executed = await client.dispatch(resolution); // Uses that same result.
console.log(executed.results); // ["/"]
unregister();
```

The handler above only prints. `resolve()` returns intents without calling handlers. `dispatch()` invokes handlers explicitly and makes no HTTP request. When you do not need to inspect the intermediate resolution, `resolveAndDispatch(request)` combines one resolve call with dispatch.

The annotation `ResolveRequest` keeps string literals such as `"voice"` and `"navigation.open"` within their discriminated unions when storing a request in a variable.

A complete source-checkout example is in [examples/quickstart.mjs](examples/quickstart.mjs). With an API already running on localhost:

```sh
cd sdk/typescript
npm ci
npm run build
URSLY_API_URL=http://127.0.0.1:8787 node examples/quickstart.mjs
```

It validates, resolves once, dispatches a print-only handler and unregisters it. Its 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

| Method                                  | Result and behavior                                                                                                                        |
| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `new UrslyClient(options)`              | Validates the required base URL and timeout; optionally accepts an injected fetch implementation.                                          |
| `capabilities(options?)`                | GET `/api/v1/capabilities`; product stages, API availability and acquisition boundaries.                                                   |
| `actions(options?)`                     | GET `/api/v1/actions`; the six action definitions.                                                                                         |
| `templates(options?)`                   | GET `/api/v1/templates`; validated, editable request examples.                                                                             |
| `validate(request, options?)`           | POST `/api/v1/validate`; returns `{ valid: true }` or throws. Does not resolve or execute.                                                 |
| `resolve(request, options?)`            | POST `/api/v1/resolve`; returns a validated `ResolveResponse`.                                                                             |
| `registerHandler(type, handler)`        | Registers or replaces one typed handler; returns an unregister callback. An old callback cannot remove a newer replacement.                |
| `dispatch(resolution, options?)`        | Validates the supplied resolution, checks every required handler, then awaits handlers in intent order. Returns `{ resolution, results }`. |
| `resolveAndDispatch(request, options?)` | Resolves once, then uses the same cancellation options for explicit dispatch.                                                              |

All request/dispatch options accept `{ signal?: AbortSignal }`. Catalog and response types, `ActionHandler`, configuration/options types and typed errors are exported from the package entry point. `VERSION` is the source package release version.

Handlers receive `(action, intent)` and may return a value or a promise. Every required handler is checked before the first effect. Handler failure stops later handlers; completed effects remain and are never retried or rolled back. An unmatched response has no intents and normally yields `results: []`. A cancelled unmatched dispatch throws cancellation too.

## Requests, rules and actions

Matching compares the complete normalized input and rule phrase. The service collapses Unicode whitespace and lowercases both strings; it does not do substring matching, recognition or infer intent beyond your rules. Multiple matching rules return intents in rule order. `enabled` defaults to true. Disabled rules still need valid payloads.

`confidence` and `minConfidence` accept omission or JSON `null`. Without a threshold, missing confidence does not block a match. With any threshold, including zero, the input needs explicit confidence at least that threshold. Confidence comes from 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" }`; gesture identifiers are supplied by your adapter. The other senses—`smell`, `taste`, `view`, `touch`—return HTTP 422 with `sense_unavailable`.

### Contract limits

Lengths below are UTF-8 bytes, except the 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 `null`                 |
| 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. Query strings and fragments in an action target are allowed. Non-whitespace control characters and unpaired surrogates are invalid in text.

The client checks JSON serializability, finite numbers and the encoded request byte cap before sending. The server validates request field/domain rules. Returned catalogs, templates and resolutions are checked before being exposed as typed values; returned actions and intent IDs are checked before any handler executes.

## Transport, deadlines and cancellation

`baseUrl` must be HTTP(S), without credentials, a query or a fragment; even a bare `?` or `#` is rejected. An application proxy prefix such as `https://example.test/proxy` is retained. `timeoutMs` defaults to 10,000 and must be finite, positive and at most 2,147,483,647.

```ts
import { UrslyClient, RequestAbortedError } from "@ursly/sdk";

const controller = new AbortController();
const client = new UrslyClient({
  baseUrl: "https://YOUR-API-HOST",
  timeoutMs: 5000,
  fetch: globalThis.fetch, // Optional; useful for test doubles and adapters.
});
const pending = client.capabilities({ signal: controller.signal });
controller.abort();
try {
  await pending;
} catch (error) {
  if (!(error instanceof RequestAbortedError)) throw error;
  console.log("Cancelled");
}
```

A request deadline covers transport and response-body reading. Aborting stops client waiting and signals native fetch. An injected transport that ignores abort may keep running, but its abandoned result cannot trigger `resolveAndDispatch` handlers. The signal is checked before sending, including after user-defined request serialization.

Handler execution has its own lifetime: the HTTP timeout does not limit it. Dispatch checks cancellation after validation/handler preflight and between handlers. It awaits an already-started async handler; application handlers must implement any cancellation or deadline they need. Cancellation cannot undo an HTTP request already received by the server or completed application effects.

No request is retried and redirects are never followed. Native Node fetch reports a redirect as `ApiError` with its 3xx status. Browsers hide an opaque redirect's status, so it becomes `ApiError` with status 0; a cross-origin redirect that fails CORS is a `TransportError`.

### Injected fetch responses

Native WHATWG response streams are read up to 1 MiB and decoded as strict UTF-8 JSON. Non-streaming adapters are supported through `text()` or, if absent, `json()`: whatwg-fetch, node-fetch v2 and minimal response test doubles can use this route. The whole non-streaming body is read before enforcing the cap. Its transport has already decoded bytes, so the SDK cannot verify the original UTF-8 on that route.

A `json()`-only result is reserialized with finite-number checks. NaN/Infinity, cycles and unsupported JSON values that fail serialization are `InvalidResponseError`; they are not silently converted into nullable confidence fields. Response objects still need the usual `ok` and `status` HTTP metadata.

Node-compatible runtimes without a DOM send `User-Agent: ursly-sdk-typescript/<VERSION>`. Browsers retain their own User-Agent to avoid a custom-header CORS preflight. Requests use `Accept: application/json` and add `Content-Type: application/json` for POST.

## Errors and recovery

All SDK errors extend `SDKError` and expose `code`. SDK-generated transport/handler messages omit the original exception text; API errors carry server-provided messages. The SDK does not log request bodies or credentials.

| Error                  | Code                        | Meaning                                                                        |
| ---------------------- | --------------------------- | ------------------------------------------------------------------------------ |
| `ConfigurationError`   | `invalid_configuration`     | Fix the URL or timeout before retrying.                                        |
| `SDKError`             | `invalid_request`           | Request cannot be serialized as supported JSON, 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`                   | HTTP deadline expired; server receipt is still possible.                       |
| `RequestAbortedError`  | `cancelled`                 | Caller cancelled; completed effects cannot be undone.                          |
| `TransportError`       | `transport_error`           | Fetch/network failure; original transport error text is not exposed.           |
| `InvalidResponseError` | `invalid_response`          | Response exceeds the cap or fails decoding/contract validation.                |
| `MissingHandlerError`  | `missing_handler`           | Register `actionType`; no handler has run.                                     |
| `HandlerError`         | `handler_error`             | Handler for `actionType`/`ruleId` failed; earlier effects remain.              |

Non-JSON HTTP error bodies use `ApiError(status, "http_error", ...)`. Oversized bodies are rejected as `InvalidResponseError`. Error envelopes with non-string codes or messages fall back to generic values. Decide whether a retry is appropriate in your application; the SDK never retries automatically.

## Verify and build

Run offline and local HTTP adapter tests first, then enable the real service contract suite against an isolated server:

```sh
cd sdk/typescript
npm ci
npm run typecheck
npm test
URSLY_TEST_URL=http://127.0.0.1:8787 npm test
npm run build
npm pack --dry-run
npm pack
```

Without `URSLY_TEST_URL`, real service tests are explicitly skipped. With it, the suite covers every catalog/template, all six action types, voice/motion, unavailable senses, confidence/disabled rules, normalization and UTF-8/count boundaries. Native/injected HTTP tests cover redirects, body limits, malformed responses, cancellation, timeouts and explicit dispatch. [SOURCES.md](SOURCES.md) records versioned references and audit evidence.

The package exports compiled ESM and generated `.d.ts` from `dist/`. Building or packing source does not publish it or update website downloads.

## Compatibility and product boundaries

Since 0.1.0, caller cancellation uses code `cancelled` (the class remains `RequestAbortedError`); redirects are typed API errors; responses have a 1 MiB cap and contract validation; bare query/fragment URL markers and non-finite outbound numbers are rejected. Optional confidence values accept null, and product-stage types accept both current `development` and historical `beta`.

Current source also rejects invalid/duplicate returned intent IDs and more than 32 intents, preserves json-only transport validation and handles cancellation of an empty dispatch. These checks protect explicit application execution and do not add acquisition or execution capabilities.

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

## License

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