# Swift SDK

> Install the Thalovant Swift SDK for iOS, macOS, and Linux apps that connect to a hub.

Source: https://docs.thalovant.com/developers/sdks/swift/

---
Use the Swift SDK when your client runs on iOS, macOS, or Swift on Linux.

The package is resolved with Swift Package Manager from the public GitHub repository. Swift 5.9 or newer is required, on iOS 15 or newer, macOS 12 or newer, or Linux with Foundation networking. The SDK has no third-party dependencies.

Source and releases: [thalovant-swift-sdk on GitHub](https://github.com/thalovant/thalovant-swift-sdk).

## Install

Add the package to your `Package.swift` and depend on the `ThalovantSDK`
product. `from:` accepts that version and any later one below 1.0; the current
release is in [Supported Versions](/developers/sdks/#supported-versions).

```swift
dependencies: [
    .package(url: "https://github.com/thalovant/thalovant-swift-sdk", from: "0.11.0"),
]
```

## First Request

This flow signs in, creates a client identity, and sends one request over WSS.

```swift

let api = ThalovantControlPlane()

try await api.login(email: "you@example.com", password: "password")

let result = try await api.createClientIdentity(
    hubId: "hub-id",
    options: CreateClientIdentityOptions(name: "swift-demo-client")
)

let client = try ThalovantClient(identity: result.identity)
do {
    try await client.connect()
    let reply = try await client.ask("Tell me a short clean joke.")
    print(reply.text)
    await client.close()
} catch {
    await client.close()
    throw error
}
```

`ThalovantControlPlane()` uses `https://api.thalovant.com` by default.

  Keep `result.identity` secret. Authenticated API actions require API access on the workspace. Do not log `result.asJSON(includeSecrets: true)`.

## Sign In With MFA

Accounts with multi-factor authentication enabled must include a TOTP code or a one-time recovery code with the login. Without one, the API rejects the sign-in with HTTP 401 and code `mfa_required`, surfaced as `ThalovantApiError.errorCode`.

```swift
try await api.login(email: "you@example.com", password: "password", otpCode: "123456")

// Or use a one-time recovery code instead:
try await api.login(email: "you@example.com", password: "password", recoveryCode: "abcd-efgh-ijkl")
```

The `otpCode` and `recoveryCode` values are sent only when provided.

## Sign In Without A Password

Device login asks your browser to approve the sign-in, so apps and tools never handle your password. The SDK prints a short code and the address `https://dash.thalovant.com/activate`, opens that page when it can, and waits while you approve the request in the dashboard with your normal sign-in, including Google sign-in or MFA. On approval the SDK holds a scoped, revocable API token, returned as a typed `DeviceLoginResult`.

Device login needs SDK 0.1.1 or newer. Approving the request needs a paid workspace plan; a free plan gets HTTP 402.

```swift
let token = try await api.loginWithBrowser(options: DeviceLoginOptions(
    scopes: ["hubs:read", "clients:write"],
    clientName: "my-macbook"
))
print(token.tokenId ?? "", token.scopes)
```

Manage the resulting token on the dashboard's [API Tokens page](/account/api-tokens/).

## Authenticate With An API Token

Pass a stored API token when the process should start authenticated, such as CI jobs and services. Mint one on the [API Tokens page](/account/api-tokens/) or with `loginWithBrowser`; the page shows scopes, expiry, and last use, and can revoke the token at any time.

```swift
let api = ThalovantControlPlane(accessToken: ProcessInfo.processInfo.environment["THALOVANT_API_TOKEN"])
```

## Where The SDK Keeps Its Keys

The SDK connects over WSS. Every connection is encrypted and authenticated before anything is sent. HTTPS and MQTT remain unsupported.

The default `ThalovantFileNoiseStore` keeps the SDK's keys and the hub identities it has recorded under the platform's Application Support directory, scoped to the identity. Keep it across restarts. Pass `noiseStore:` to `ThalovantClient` or `HiveMindWSSTransport` to use another private directory, or implement `ThalovantNoiseStore` for Keychain-backed storage. Use distinct identities for concurrent clients, and never discard a saved hub identity automatically.

  The WSS transport needs a Foundation implementation with WebSocket support. Stock Linux Swift 5.10 and 6.3.3 images fail WebSocket setup because their libcurl lacks that support. The SDK is verified on macOS and on Linux with Swift 6.3.3 plus a WebSocket-enabled libcurl 8.22.0. Use the repository's `tools/interop/build-websocket-curl.sh` script or another verified WebSocket-capable runtime.

Use fresh request IDs for Ask and fresh query IDs for Query; generated IDs are the default. An overlapping collector with the same ID is rejected on the same client. The namespaces are independent. Do not reuse an ID for a later logical operation, even after cancellation: a delayed reply can still carry it. Reuse a session ID for conversation context.

## Supported Runtime Protocol

`ThalovantClient` connects to the hub over WSS only in this release. Constructing it with `hubProtocol: .https` or `.mqtt` throws `ThalovantUnsupportedProtocolError`. Endpoint selection still prefers `wss`, then `https`, then `mqtt`, so identities created for multi-protocol hubs keep working.

Use the [Python](/developers/sdks/python/), [Node.js](/developers/sdks/node/), [Go](/developers/sdks/go/), or [Rust](/developers/sdks/rust/) SDK when the client needs the HTTPS or MQTT data plane today.

Concurrent runtime calls share one connection attempt and wait for authenticated readiness. You can still await `client.connect()` explicitly before starting work. Cancelling or timing out a joining caller ends only its wait; cancelling or timing out the caller that started the connection closes that attempt for everyone waiting on it. Keep the client open for those requests, then await `client.close()` when they finish.

## Use A Saved Identity

Identities can be built from JSON or loaded from a JSON file. The file must not be group- or world-readable; run `chmod 600 <path>` first.

```swift
let identity = try ThalovantIdentity.fromFile("/path/to/identity.json")
let client = try ThalovantClient(identity: identity)
```

The identity document uses the same snake_case fields the API returns, including `access_key`, `password`, `site_id`, and the optional `data_plane_endpoints`, `protocols`, and `mqtt` sections. A `crypto_key` in an older identity file is still parsed and ignored.

## Follow An Operation

Mutating control-plane commands return durable operations. Poll them with the typed helper:

```swift
let operation = try await api.getOperation(id: "operation-id")
print(operation.status)  // .requested, .committed, .applied, .ready, .failed, .timedOut
```

See [Operations](/developers/operations/) for lifecycle and retry guidance.

## Listen For Events

```swift
let subscription = client.on("speak") { event in
    print(event.displayText)
}
// Later, when the listener is no longer needed:
subscription.close()
```

## List What The Hub Can Be Asked

A connected client can list every intent its hub answers, per language, with the sentences a person says to reach each one, over its own session and with no control-plane token. See [What Can My Hub Be Asked?](/concepts/hub-intents/) for what the hub returns, which message types the connection must be allowed to publish, and what a refusal or a failed listing looks like.

Since SDK 0.1.8 the calls are `client.intents(languages:options:)`, which returns the inventory grouped by skill, `client.listIntents(lang:options:)`, which returns the registration rows, and `client.describeIntent(skillId:intentName:lang:options:)`, which returns the definitions behind one intent.

```swift
let client = try ThalovantClient.fromIdentityFile("_identity.json")
do {
    let inventory = try await client.intents(languages: ["en-us", "fr-fr"])
    print(inventory.source, inventory.languages)
    for skill in inventory.skills {
        for intent in skill.intents {
            print(intent.id, intent.engine, intent.examples(lang: "fr-fr"))
        }
    }
} catch let denied as ThalovantPolicyDeniedError {
    print("refused:", denied.deniedType, "allowed:", denied.allowed)
}
await client.close()
```

`intents(languages:)` asks `ovos.intent.list` once per language, then fills in the sentences the listing did not carry, in batches of `defaultDescribeBatchSize` requests so a hub with many intents is never sent the whole burst at once. `IntentInventoryOptions` carries the deadline and the switches: `describe: false` stops at names, engines, and enabled state. `examples(lang:limit:)` prefers whole sentences to ones with a `{slot}`, then fuller wording up to eight words; `phrasesFor(_:)` returns all of them, and the inventory is `Codable`, so `asJSON()` writes the same document the other SDKs write. Language tags compare without regard to case or `_` and `-`, so `fr-fr` and `fr_FR` are one request.

A hub that refuses a query throws `ThalovantPolicyDeniedError` at once with `deniedType`, `code`, `reason`, and `allowed`. With the default `IntentInventoryOptions(fallback: true)`, a refused `ovos.intent.list` returns names only instead: `inventory.source` is `.engineManifests`, `inventory.denied` names the refused query, and `inventory.hasPhrases` is false, so check that flag before promising sentences. A hub that accepts the listing and answers it with `ok: false` is a different case: since 0.1.9 that throws `ThalovantRuntimeError` carrying the hub's own error text, because a failed listing is not an empty hub. `describeIntent` keeps returning an empty list for the same answer, which is a real one: the hub does not know that registration.

The default inventory also falls back when `ovos.intent.list` is silent. Disable fallback to propagate that listing timeout. The `denied` marker names the query that triggered fallback; it does not establish a policy denial. `listFallbacks()` exposes registered fallback handlers, and inventory includes `fallbacksKnown` and `mayAnswer(_:)`.

The optional fallback-handler probe takes at most 1.5 seconds across connection, send, and reply wait. A denied, silent, explicitly failed probe or malformed reply envelope leaves discovery unknown. Accepted arrays retain usable handlers and skip invalid rows. Known empty handlers and unknown discovery are different states: language availability is false only when no enabled intent has phrases for that language and a successful probe reports no fallback handlers. A fallback handler's presence does not guarantee it can answer every language.

## Runtime Helpers And Deadlines

A conversation shares the client's connection, session id, language and context. Each request gets a fresh request id:

```swift
let conversation = client.conversation(sessionId: "checkout", lang: "en-us")
let reply = try await conversation.query("Tell me a short clean joke.", timeout: 12)
print(reply.text)
```

`query` accepts only the matching query id and collects query/cascade replies until `hive.query.complete`. Soft intent misses allow later speech; policy denial and query timeout are terminal and retain partial speech in a failed reply. Its deadline covers connection, queued sending, and collection. Requests are never automatically replayed.

Use `waitForEvent` for one event and `listen` for an `AsyncThrowingStream`. Calling `listen` starts the subscription. Its 64-event buffer reports overflow; timeout, event count, task cancellation and transport loss release subscriptions. `sendAction` and `sendCode` preserve structured input metadata. `connectionInfo`, `connectWithInfo`, `healthcheck` and `doctor` report local authenticated transport state, without guaranteeing every remote skill is healthy.

`connect(timeout:)` uses one budget for socket setup and authenticated readiness, with a six-second default. Cancellation before a queued write is accepted skips that write. Once accepted, caller cancellation stops waiting while the encrypted write retains its place in the send queue under an independent 20-second deadline. A physical write failure or expiry retires the affected connection; cleanup keeps ownership until the write actually stops. Use the platform requirements above when choosing a Swift runtime.

## Control-Plane HTTP Security

Control-plane redirects are rejected. Requests carrying credentials or a JSON body require HTTPS, except explicit `localhost`, `127.0.0.1`, and `[::1]` HTTP development endpoints. Injected headers, cookies, stored credentials and custom trust callbacks also require secure transport. Anonymous reads without those credentials or a body may use HTTP. URLs containing userinfo are rejected before I/O.

When a `URLSession` is supplied, the SDK creates its own session from that configuration and retains redirect decisions. It forwards authentication-challenge callbacks to the supplied delegate for custom trust handling. Supplied URL protocol implementations remain trusted application code. Device login opens only HTTP(S) verification URLs without userinfo or control characters.

## Useful Helpers

  
    Send one request and receive a normalized reply.
  
  
    Observe hub bus events by name with a closeable subscription.
  
  
    Poll a durable control-plane command with a typed status.
  
  
    Discover public hubs before sign-in.
  

For cross-language recipes, see [SDK Functions](/developers/sdk-functions/).

## Provision Hubs

Since SDK 0.1.3 the control plane can create hubs, runtime groups, and skill installs. Browsing the catalog with `listMarketplaceSkills()` needs `hubs:read` and works on any plan. `createHub`, `createRuntimeGroup`, `installRuntimeGroupSkill`, `releaseHub`, and `releaseRuntimeGroup` need `hubs:write` and a paid plan.

```swift
let group = try await api.createRuntimeGroup(["name": "kiosks"])
let hub = try await api.createHub([
    "name": "joke-garden",
    "runtimeGroupId": .string(group["id"]?.stringValue ?? ""),
    "spec": .object([:]),
])

let current = try await api.getHub(hub["id"]?.stringValue ?? "")
_ = try await api.updateHub(
    current["id"]?.stringValue ?? "",
    ["active": false],
    etag: current["etag"]?.stringValue ?? "",
)
```

`updateHub` and `deleteHub` take the hub's current etag as a required argument. See [Provision Hubs](/developers/provisioning/) for the full flow, the immutable fields, and the error table.

## Common Issues

| Symptom | Check |
| --- | --- |
| `ThalovantApiError` with `Missing Thalovant API access token` | Call `api.login(...)` or `api.loginWithBrowser(...)` before private API actions, or pass `accessToken:` to `ThalovantControlPlane`. |
| HTTP 401 with `errorCode` `mfa_required` | Pass `otpCode` or `recoveryCode` to `api.login(...)`. |
| API access requires a paid plan | Upgrade the workspace before provisioning private resources through the API. |
| `ThalovantUnsupportedProtocolError` | The hub does not expose WSS, or the code requested `https` or `mqtt`, which this release does not connect over. |
| `ThalovantIdentityError` | The identity file is malformed or readable by other users. |
## Manage Skills Through A Hub

The SDK can list, install, update, remove and inspect the history of skills on a
hub's runtime group. **Every hub sharing that runtime group is affected.** A hub
UUID selects the group; it does not create an isolated installation for that hub.
A restricted token must cover all hubs served by the group.

Reads require `hubs:inspect` (`hubs:read` includes it). Writes require `hubs:write`,
an eligible paid plan and ownership. Use `latest` or a concrete released version
for installation and updates. An accepted write returns an `operation_id`;
acceptance does not mean the runtime has finished installing the skill.

| Action | Method |
|---|---|
| List | `listHubSkills` |
| History | `listHubSkillHistory` |
| Install | `installHubSkill` |
| Update | `updateHubSkill` |
| Remove | `removeHubSkill` |

History returns the API JSON envelope with newest-first `event` and `operation`
entries, preserving nullable actor/version fields. The limit is 1–200.

Use `HubSkillWaitOptions` to opt into operation waiting (120 seconds, polling every
two seconds by default). For cancellation-sensitive calls, first submit without
waiting, retain the accepted response, then call `waitForHubSkillOperation`.
Cancelling the wait does not undo the accepted server operation. Polling failures
retain the operation ID in the error; inspect that operation instead of repeating
the write. The wait deadline prevents new polls but does not cancel a request
already in flight.

## Request Helpers And Safe Configuration Updates

Request hints carry a recognized language, ordered intent pipeline, and caller
location without changing the caller's context. Empty hints are omitted. The
location helper requires a city and omits invalid or zero/zero coordinates.
The hub validates language hints against its configured languages.

Replies expose their reported language, ordered speech/audio events, and a
count of dropped media. Embedded skill clips are limited to 4 MiB each and
16 MiB per reply, checked before retention and decoding. Audio does not extend
the reply settlement window. Decoding accepts hexadecimal bytes with ASCII
whitespace between bytes; it never fetches a skill-supplied URL or file path.
The application owns playback. Any `play` or `Play` function below belongs to your app.

```swift
let location = buildLocation(city: "Montréal", country: "CA")
let reply = try await client.askWithHints("Quel temps fait-il ?", sttLang: "fr-ca", location: location)
for event in reply.mediaEvents where event.isAudio { play(try event.audioBytes()) }
let examples = intent.examples(lang: "en-us", speakable: true)
try await api.updateRuntimeGroupConfig(groupId, config: delta)
// Explicit full replacement:
try await api.replaceRuntimeGroupConfig(groupId, config: fullConfig)
```

Guarded merging requires the `hubs:read` and `hubs:write` scopes and a paid plan.
Safe merging requires an API whose configuration GET returns a valid `revision`
and whose configuration PUT checks `expected_revision`. The SDK rereads and
reapplies the original delta only after HTTP 412, with at most three attempts.
Arrays and scalar values replace; objects merge recursively. Personas replace
only when explicitly supplied. Connection failures, redirects, other statuses,
and ambiguous write results are never retried. No unsafe PATCH fallback is used.
Unconditional replacements must still be coordinated with other writers.

Use the explicit replacement operation shown above when a complete replacement
is intended, including when working with an older API. Existing code relying on
replacement must opt into it when upgrading. Raw intent patterns remain the
default; speakable examples remove optional parts, choose alternatives, and
substitute caller-supplied slots while retaining complete-phrase priority.

The audio limits use encoded-length upper bounds before decoding, so formatting
whitespace consumes budget too. Like Python's `bytes.fromhex`, ASCII whitespace
alone decodes to zero bytes. Bounded malformed clips remain available as event
metadata and fail when decoded; they are never fetched or played automatically.
Distinct audio events may intentionally repeat identical sound content. Only
repeated delivery of the same event object is suppressed where object identity
is available, without counting it as a dropped clip. Rendered example ranking
uses the original pattern's slot presence even when sample values are supplied.

Guarded merges preserve native `Int` values. Floating-point values in config,
personas, or the stored configuration must be finite and within
±9,007,199,254,740,991. Larger values fail before writing because decoding may
have rounded an integer beyond native storage. Use string identifiers for
integers that exceed native storage.

## Locale-Aware Intent Listings

*Available since `0.6.1`.*

Sentence listings use bundled `thalovant-languages` 0.2.1 data and match Python
0.6.8 with its listing extra. Language selection follows OVOS regional distances,
so a request for `fr-CA` can use a registered `fr-FR` locale.

```swift
let examples = intent.examplesWithListing(lang: "fr-CA", sentence: true)
let text = asSentence("what time is it", lang: "en-US")
let sample = speakableWithLanguage("play {song}", lang: "en-US")
```

Sentence rendering implies speakable rendering. Explicit slot values override
locale samples. Complete phrases rank before prefixes and slot patterns; empty
and duplicate rendered examples do not consume the limit. Unlimited raw examples
keep registration order. Unknown locales retain bare text and slot names.

Existing example methods remain available. Use `ListingRules` to provide a
complete custom data snapshot or select bare rendering without locale data.
No network request is needed to load the bundled rules. See the repository README
for custom-rule construction and regex error handling.

The listing data now describes 270 languages, including regional overrides.
Spanish `qué hora es` becomes `Qué hora es?`, and French `coupe le son`
becomes `Coupe le son.`. Languages without rules, such as `tlh`, remain bare.

## Managed Sessions And Inventory Caches

`HubSession` owns one reusable hub connection. Supply a factory that returns a
connected client and cleans up a failed or cancelled connection attempt. Event
subscriptions survive client replacement. Go and Rust expose a persistent event
stream; the other managed SDKs expose subscription handles. Close the session
when its owner shuts down; close waits for accepted operations and is terminal.

Background connection attempts back off for 10, 20, 40, 80, then 120 seconds.
Foreground calls can try immediately. Your application owns probe scheduling:
use the reported probe delay (60 seconds while held, 5 seconds while down).
The SDK never replays an accepted Ask or Emit after a lost response, because an
Ask can trigger an action. A request timeout applies to the underlying operation;
waiting for the session and your connection factory are separate budgets.

```swift
let session = HubSession(connect: connectClient, warm: false)
do {
    let reply = try await session.ask("What is the weather?")
    await session.close()
} catch {
    await session.close()
    throw error
}
```

`Inventory`, `Skill`, and `Intent` provide a presentable view separate from the
runtime's native intent inventory. Unknown catalogue locales remain unknown;
phrases observed for a language do not prove catalogue support. Examples choose
the closest supported locale. A nonpositive limit returns the raw phrase pool
(Rust uses zero for its unsigned limit). Cache JSON includes explicit intent
language order so serialization cannot change the default example language.

`InventoryCache` is optional, defaults to a one-hour TTL, and returns a miss for
invalid, expired, or unreadable data. Writes use private, unique scratch files
and atomic replacement. POSIX cache files are owner-readable/writable; Windows
uses the user's directory ACLs. Cache keys separate mode, identity path, and the full normalized hub hostname.
Never use inventory caches to store credentials.

`OriginPreference` gives a preferred address its own short connection budget and
cools it down after a failure. In non-Python SDKs the factory must implement the
address binding on its own transport, retain the public host for TLS/SNI, and
finish failed-attempt cleanup before returning. Transport/platform restrictions
still apply. This helper does not change global DNS or disable TLS validation.

## Reply Claims

A reply exposes `reply.pipelineIds`, `reply.skillIds` and `reply.claimed`.

Pipeline and skill IDs are nonempty strings in first-seen order, with duplicates removed. A successful reply with only pipeline IDs containing the case-sensitive text `fallback` reports an unclaimed reply. Any non-fallback stage makes a successful reply claimed. Successful replies from older hubs without stage stamps remain claimed. Failed or unhandled replies are never claimed. Malformed non-string stamps are ignored.

Use this as a hint when deciding whether to continue a conversation. Fallback text and the existing success status are retained. These stamps are not verified peer identity and must not authorize actions.
