> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.rydhm.ai/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.rydhm.ai/_mcp/server.

# Browser SDK (@rydhm/web)

`@rydhm/web` puts a Rydhm voice expert inside your web app ([Onboarding coach](/engine/onboarding-coach)) and gives your reps a browser phone ([Softphone](/engine/softphone)). It uses a **publishable key** or a **softphone token**, never your secret key. Typed, safe by default, and loadable with one script tag.

```bash
npm install @rydhm/web
```

```html
<!-- or, without a build step: the script the Rydhm app serves -->
<script src="https://staging.rydhm.ai/engine.js" data-key="rydhm_pk_live_…" async></script>
```

The script follows the Rydhm app: `https://staging.rydhm.ai/engine.js` in early access, `https://app.rydhm.ai/engine.js` at launch (the coach's **Setup** tab shows the right one). It is always the current release. A CDN copy of a version published to npm works too, such as `https://cdn.jsdelivr.net/npm/@rydhm/web@0.3.0/dist/engine.js`; pin a version in production.

> **Note**
>
> **npm and the script tag match.** `npm install @rydhm/web` installs 0.3.0, the release this page describes, the same as the script tag serves today. The script tag always follows the current release; pin a version from npm or the CDN for production.

## Rydhm.init options

| Option             | Type                                                | Default                                           | What it does                                                                                                                                                                                                                                                                     |
| ------------------ | --------------------------------------------------- | ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `key`              | `string`                                            | required                                          | The publishable key, `rydhm_pk_…`. A secret key (`rydhm_live_…`) is refused.                                                                                                                                                                                                     |
| `apiUrl`           | `string`                                            | `https://api.rydhm.ai`                            | The API address. https only (http for localhost).                                                                                                                                                                                                                                |
| `user`             | `{ id, hash?, name?, traits? }`                     | anonymous                                         | The signed-in user. `hash` comes from your server ([signed users](/engine/onboarding-coach-code#signed-users)). `traits` up to 4 KB.                                                                                                                                             |
| `ui`               | `'bubble' \| 'none'`                                | `'bubble'`                                        | `'none'` draws nothing: build your own UI from the events.                                                                                                                                                                                                                       |
| `position`         | `'bottom-right' \| 'bottom-left'`                   | the expert's setting                              | The bubble's corner.                                                                                                                                                                                                                                                             |
| `theme`            | `'auto' \| 'light' \| 'dark'`                       | `'auto'`                                          | Bubble and spotlight theme. `'auto'` follows your page as it changes: a `data-theme` (or `data-color-scheme`, `data-bs-theme`) of dark or light, a `dark` / `light` class, or a single `color-scheme` on `<html>` or `<body>`; with none of those, the visitor's system setting. |
| `accent`           | CSS colour                                          | the expert's setting                              | `#hex`, `rgb()`, `hsl()` or `oklch()`.                                                                                                                                                                                                                                           |
| `language`         | BCP 47                                              | the expert's                                      | The language the expert speaks.                                                                                                                                                                                                                                                  |
| `navigate`         | `(path) => void \| 'auto' \| 'history' \| 'reload'` | `'auto'`                                          | How the coach changes page. `'auto'`: `pushState`, and a real page load if nothing changed within 700 ms. Other origins are always refused.                                                                                                                                      |
| `confirm`          | `(req) => Promise<boolean>`                         | the bubble's dialog, or `window.confirm` headless | Ask before a risky click. Resolve `true` only on a clear yes.                                                                                                                                                                                                                    |
| `resume`           | `boolean`                                           | `true`                                            | Keep a conversation going across full page loads (same tab, under 45 seconds).                                                                                                                                                                                                   |
| `learnPages`       | `boolean`                                           | `true`                                            | Let an Onboarding coach learn your app's screens (its app map), names only, when the coach has learning on. `false` never reports.                                                                                                                                               |
| `duckOnSpeech`     | `boolean`                                           | `true`                                            | In a voice conversation, turn the expert's voice down as soon as the person's microphone goes loud over it. The server still decides whether it was an interruption.                                                                                                             |
| `turnstileSiteKey` | `string`                                            | none                                              | When your workspace asks for a [bot check](/engine/onboarding-coach#daily-caps-and-a-bot-check) (Cloudflare Turnstile), the SDK renders the page's own `window.turnstile` (never bundled) with this site key.                                                                    |
| `getBotToken`      | `() => Promise<string>`                             | none                                              | Your own way to get the Turnstile token when `window.turnstile` isn't on the page. With neither, a start fails with `bot_check_required`.                                                                                                                                        |
| `debug`            | `boolean`                                           | `false`                                           | Log the protocol traffic to the console.                                                                                                                                                                                                                                         |

With the script tag, these options have a `data-*` form: `data-api-url`, `data-ui="none"`, `data-position`, `data-theme`, `data-accent`, `data-language`, `data-navigate="reload"`, `data-debug`, `data-resume="false"`, `data-learn-pages="false"`, `data-user-id`, `data-user-hash`, `data-user-name`, and `data-auto-init="false"` to wait for your own `Rydhm('init', …)`.

### The queue stub

Add the stub before the script, and every call made before `engine.js` has loaded is replayed when it does:

```html
<script>window.Rydhm=window.Rydhm||function(){(window.Rydhm.q=window.Rydhm.q||[]).push(arguments)};</script>
<script>
  Rydhm('identify', { id: 'user_42', hash: '…from your server…', name: 'Asha' });
  Rydhm('setContext', { plan: 'pro', seats: 12 });
  Rydhm('on', 'state', (e) => console.log(e.state));
</script>
```

After load both styles work: `Rydhm('start')` and `Rydhm.start()`. `Rydhm.instance` is the instance and `Rydhm.Softphone` the softphone class. A queued `Rydhm('init', { … })` is merged over the `data-*` options: the way to pass a function such as your router.

## Methods

| Method                                                           | What it does                                                                                                                                                                                                                                                         |
| ---------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Rydhm.init(options)`                                            | Start the SDK on the page: one bootstrap request, no voice. The same key twice returns the same instance.                                                                                                                                                            |
| `rydhm.identify(user)`                                           | Set or change the user (after login). Reloads guides and announcements for them.                                                                                                                                                                                     |
| `rydhm.setContext(obj)`                                          | What the expert should know, up to 4 KB of JSON (larger objects are cut and marked `_truncated`). Live in the conversation within 250 ms.                                                                                                                            |
| `rydhm.track(name, data?)`                                       | A custom event, for analytics, guide triggers and step completion. Batched.                                                                                                                                                                                          |
| `rydhm.registerTool(name, { description, parameters }, handler)` | A tool the expert can run in your page. Returns an unregister function. See [Client tools](/engine/client-tools#custom-tools).                                                                                                                                       |
| `await rydhm.start({ mode?, guideId? })`                         | Start a conversation, optionally with a guide. Call it from a click. `mode: 'voice'` talks; `mode: 'text'` types, with no microphone and no sound. Without a mode: the person's last choice, else voice. Resolves when the expert has joined; rejects with a `code`. |
| `await rydhm.stop()`                                             | End it. Nothing is billed after this.                                                                                                                                                                                                                                |
| `await rydhm.startGuide(id)`                                     | Start a guide from your own button, in the conversation's mode.                                                                                                                                                                                                      |
| `await rydhm.setMode(mode)`                                      | Talk (`'voice'`) or type (`'text'`), remembered in this browser. A live conversation in the other mode is replaced by one in this mode; its guide carries on.                                                                                                        |
| `await rydhm.mute(on)`                                           | Mute or unmute the microphone.                                                                                                                                                                                                                                       |
| `await rydhm.send(text)`                                         | Send a typed message to the expert; starts a typed conversation when none is live.                                                                                                                                                                                   |
| `rydhm.levels()`                                                 | `{ input, output }` audio levels, 0 to 1, for your own visualiser.                                                                                                                                                                                                   |
| `rydhm.state`                                                    | The current state event.                                                                                                                                                                                                                                             |
| `rydhm.on(event, cb)`                                            | Subscribe; returns the unsubscribe function.                                                                                                                                                                                                                         |
| `rydhm.destroy()`                                                | Remove everything: the conversation, the bubble, listeners, history patches.                                                                                                                                                                                         |

> **Note**
>
> A typed conversation (`mode: 'text'`) is the same conversation with audio off: the coach answers from its knowledge and uses every page tool and guide, and it is billed like chat, per token. Which modes an expert offers comes from its widget setting **Visitors can**; a mode it does not offer is refused with `mode_not_available`.

## Events

| Event          | Payload                                                                                                                                                   |
| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `state`        | `{ state: 'idle' \| 'connecting' \| 'listening' \| 'thinking' \| 'speaking' \| 'reconnecting', mode?, sessionId?, muted }`                                |
| `transcript`   | `{ id, speaker: 'user' \| 'expert', text, final }`. Interim updates share the `id` of their final line.                                                   |
| `tool`         | `{ callId, name, args, status: 'started' \| 'ok' \| 'error', result?, error?, source: 'browser' \| 'worker' }`                                            |
| `guide`        | `{ type: 'offer', guide, reason, accept(), dismiss() }`, or `{ type: 'started' \| 'step_completed' \| 'completed', guideId, stepId?, stepsDone, source }` |
| `announcement` | `{ type: 'shown', announcement, accept(), dismiss() }`, or `{ type: 'clicked' \| 'dismissed', announcement }`                                             |
| `error`        | `{ code, message, fix?, status?, retryAt? }` (`retryAt` for a daily cap)                                                                                  |

## Error codes

| Code                                   | What it means                                                                                                                                                                                        |
| -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `invalid_key`                          | The publishable key is wrong or revoked.                                                                                                                                                             |
| `key_not_allowed`                      | This website isn't one of the key's allowed websites. Add it to the key.                                                                                                                             |
| `signed_user_required`                 | The key takes only [signed users](/engine/onboarding-coach-code#signed-users), and the user has no valid hash.                                                                                       |
| `rate_limited`                         | Too many requests from this visitor or key.                                                                                                                                                          |
| `offline`, `network_error`             | No network, or the API couldn't be reached (a CORS refusal looks the same to a browser).                                                                                                             |
| `mic_denied`                           | The microphone was blocked. `fix` says how to unblock it in this browser.                                                                                                                            |
| `mic_unavailable`                      | No microphone.                                                                                                                                                                                       |
| `audio_blocked`                        | The browser blocked audio until a tap; the next tap anywhere unlocks it.                                                                                                                             |
| `session_failed`, `expert_unavailable` | The conversation couldn't start, or the expert is switched off.                                                                                                                                      |
| `connection_lost`                      | The call dropped and couldn't reconnect.                                                                                                                                                             |
| `bootstrap_failed`, `server_error`     | The API failed. Retry later.                                                                                                                                                                         |
| `daily_session_cap`                    | 429: this website key has started all the conversations its [daily cap](/engine/onboarding-coach#daily-caps-and-a-bot-check) allows today. `retryAt` says when it can again (the next UTC midnight). |
| `daily_voice_minutes_cap`              | 429: the key's voice minutes for today are used up. Typing still works; `retryAt` as above.                                                                                                          |
| `bot_check_required`                   | 403: the workspace asks for a bot check (Cloudflare Turnstile) and none was given: add Turnstile to the page, or pass `getBotToken`.                                                                 |
| `bot_check_failed`                     | 403: the bot check didn't pass (expired, reused, or a bot). Reload and try again.                                                                                                                    |

## Softphone

```typescript
import { Softphone } from "@rydhm/web";
const phone = new Softphone({ token: await getTokenFromYourServer(), refreshToken: getTokenFromYourServer });
```

| Member                                                                                         | What it does                                                                                                                                                                                                                                  |
| ---------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `new Softphone({ token, url?, apiUrl?, refreshToken?, inputDeviceId?, autoConnect?, debug? })` | `token` is the softphone-token reply your server got (or its `token` string plus `url`). Goes online right away unless `autoConnect: false`.                                                                                                  |
| `connect()`, `disconnect()`                                                                    | Go online or offline. Reconnects with backoff, refreshing the token when it expired.                                                                                                                                                          |
| `join(call)`                                                                                   | Join a call room: the `POST /v1/rep-calls` reply (`{ id, join }`) or `{ url, token, callId? }`. Publishes the mic.                                                                                                                            |
| `answer(callId?)`, `decline(callId?)`                                                          | A ringing callback (the newest when no id).                                                                                                                                                                                                   |
| `hangup()`                                                                                     | Ends the call, then leaves the room.                                                                                                                                                                                                          |
| `mute(on = true)`, `setInputDevice(id)`, `Softphone.inputDevices()`                            | Microphone control.                                                                                                                                                                                                                           |
| `setOutputDevice(id)`, `Softphone.outputDevices()`                                             | Speaker picker, where the browser allows it.                                                                                                                                                                                                  |
| `hangup({ notify: false })`, `decline(id, { notify: false })`                                  | Leave the call, or stop it ringing, in this browser only: your server already ended or declined it.                                                                                                                                           |
| `state`, `duration`, `incoming`, `levels()`                                                    | `{ presence, call, callId?, muted, quality, startedAt?, durationSec }`, seconds, ringing calls, audio levels.                                                                                                                                 |
| `on(event, cb)`                                                                                | `state`, `incoming`, `ringing` (`from`, `to`), `answered`, `screening` (`text?`), `transcript`, `suggestion`, `voicemail` (`kind: detected \| beep \| left`), `ended`, `timer`, `event` (every raw event, such as `call.recording`), `error`. |
| `destroy()`                                                                                    | Leave everything (it doesn't hang the call up for the other side).                                                                                                                                                                            |

See [Browser softphone](/engine/softphone) for the walkthrough.

### A REC badge

When a call is [recorded](/engine/rep-calls#recordings), the softphone gets a `call.recording` event the moment the recording starts, at the answer. It comes through the `event` listener, with `CallRecordingData` as its `data`:

| Field    | What it is                                                                                                      |
| -------- | --------------------------------------------------------------------------------------------------------------- |
| `status` | `recording` in the call room. (`skipped`, `ready` and `failed` reach your server's streams, not the softphone.) |
| `reason` | Why a recording was skipped or failed; `null` while recording.                                                  |
| `notice` | `true` when Rydhm's voice says "Just so you know, this call is recorded." to the prospect.                      |

```typescript
import type { CallRecordingData } from "@rydhm/web";

phone.on("event", (e) => { // phone: your Softphone
  if (e.type !== "call.recording") return;
  const rec = e.data as unknown as CallRecordingData;
  if (rec.status === "recording") showRecBadge({ withNotice: rec.notice });
});
phone.on("ended", () => hideRecBadge());
```

The event reaches 0.3.0 too; the `CallRecordingData` type comes in the next release.

## Exports

`Rydhm`, `Softphone`, `VERSION`, `RISKY_PHRASES` (the words that make a click ask first), the protocol constants (`ROUTES`, `RPC_TOOL_METHOD`, `TOPIC_EVENTS`, `TOPIC_COMMAND`, `ATTR`, `LK`, `BUILTIN_TOOLS`, `DEFAULT_API_URL`), and the types of every option, event and wire message (`RydhmOptions`, `RydhmEvents`, `ToolDefinition`, `EngineEvent`, `SoftphoneEvents`, `IncomingCall`, `CallRecordingData`…).

## Browser support, size and CSP

* Current Chrome, Edge, Firefox and Safari, desktop and mobile (iOS Safari 15+). Needs WebRTC, Shadow DOM and Custom Elements. The script bundle targets ES2019.
* **Two files for the script tag.** `engine.js` is the loader (0.3.0: 184 KB raw, about 60 KB gzipped): the bubble, guides, announcements and page tools. The first time a conversation starts (a coach session, or a softphone going online), it adds `engine-livekit.js` (the voice connection, 739 KB raw, about 200 KB gzipped) from the **same directory** as `engine.js`. Visitors who never talk never download it. To host the files yourself, keep them side by side, or set `data-livekit-src` on the tag to where `engine-livekit.js` is. Both files must come from the same release.
* **With npm**, there is no second file: `livekit-client` is a dependency your bundler splits into its own chunk, loaded on the first conversation.
* **Content Security Policy**: allow **both** script files in `script-src` (the origin they come from, such as `https://staging.rydhm.ai`, later `https://app.rydhm.ai`). If your policy uses a nonce, put it on the `engine.js` tag: the loader copies it to the `engine-livekit.js` tag it adds. Allow the API address and your LiveKit host (`wss:` and `https:`) in `connect-src`, and the expert's photo host in `img-src`. Styles use constructable stylesheets, so `'unsafe-inline'` isn't needed. Sites that enforce Trusted Types add `rydhm` to their `trusted-types` list.
* No cookies, no external fonts, no third-party requests.