> ## Documentation Index
> Fetch the complete documentation index at: https://docs.praxis-ai.com/llms.txt
> Use this file to discover all available pages before exploring further.

# JavaScript SDK

> Use the JavaScript SDK to interact with your Digital Twin programmatically from any web application.

## Client SDK

The JavaScript SDK is available as soon as you integrate your application with either the Web SDK or via Canvas Theme. It enables client-side automation with your Digital Twin—such as sending messages, listing favorites, and running assistant instructions.

> [!WARNING]
>
> To use the JavaScript SDK, your Digital Twin must be integrated into a web application using the Web SDK or injected into Canvas via Theme.

## Integration Options

Integrate your Digital Twin in one of these ways to access the SDK:

* **Web SDK:** Embed the Digital Twin directly in your web app by installing the Web SDK for easy setup, user management, and customization.
* **Canvas Theme:** Inject the Digital Twin into Canvas using the Theme for direct access to SDK features within the Canvas LMS.

Both methods offer secure, flexible options to maximize your Digital Twin’s functionality. Select the approach that best fits your environment.

## Global Window Object

When your Digital Twin is integrated, the `pria` object is injected directly onto the global window (DOM), making it the central access point for all Pria SDK API calls from anywhere in your application. This allows you to easily interact with Pria’s messaging, UI control, and event management methods without additional imports or setup—simply reference `window.pria`.

```javascript theme={null}
const pria = {
    load: priasdk,                // Initialize the Pria SDK and establish middleware connection
    send: priaSend,               // Send API requests/messages to Pria
    subscribe: priaSubscribe,     // Listen for Pria responses or callback events
    unsubscribe: priaUnsubscribe, // Remove listeners or callbacks from Pria
    setVisible: priaSetVisible,   // Show or hide Pria entirely (removes from DOM view)
    isVisible: priaIsVisible,     // Check if Pria is currently visible
    isDisplayed: priaIsDisplayed, // Check if Pria UI panel is expanded
    display: priaDisplay,         // Expand or collapse the Pria UI panel
    setConvoActive: priaSetConvoActive, // Apply or remove the centered full-screen convo layout
    destroy: priaDestroy,         // Clean up and remove Pria from the page
    priaObj: priaObj,             // Backing property bag that contains current cached user identity
    isReady: priaIsReady,         // True when Pria is ready to receive messages
    isConvoReady: priaIsConvoReady, // True when real-time voice (convo) mode is authorized
    isSessionReady: priaIsSessionReady, // True when a command sent now is delivered rather than held
    isAuthRequired: priaIsAuthRequired, // True while the panel waits for the person to confirm it's them
    version: 1                    // Message-format version for compatibility checks
}
```

> By being attached to the DOM, `pria` acts as your always-available gateway for secure and seamless integration with all Pria interfaces and backend services—enabling features like messaging, automation, and UI control from any context in your client-side code.

### Messaging Technology

Communication between your web application and the Praxis AI Middleware via the Web SDK is powered by [browser messaging](https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage), which securely enables cross-origin interactions between window objects, such as between a main application and an embedded iframe or pop-up. Requests are sent to the backend middleware server using the `pria.send()` API method, ensuring safe and reliable message delivery for seamless integration and robust application workflows.

### Voice (Convo Mode) in Embedded Contexts

When your Digital Twin uses voice conversations (Convo Mode) inside an iframe you control — including LMS embeds such as Canvas — the **host page's iframe must delegate microphone and audio permissions**, or the browser will hard-block voice regardless of what the user allows:

```html theme={null}
<iframe src="…" allow="microphone; autoplay"></iframe>
```

Without this, the in-app "Tap to start talking" screen still renders, but tapping surfaces a microphone-permission error instead of starting the conversation.

If the Digital Twin has **Start Immersive Mode by Default** switched on, the embedded twin shows its "Tap to start talking" screen by itself once the SDK session is up. Anything your page asks for wins over that setting — the `convoMode` display option, or an explicit `convo.start` / `convo.stop` command. (In error messages, Convo Mode is abbreviated **STS** — speech-to-speech.)

## Sending a Request

### Request Message

To make a request, simply compose a Javascript object containing the command and arguments like below:

```javascript theme={null}
const request = {
    command: '<command>',
    ...arguments
}
```

### Available Commands

| Command | Description | Parameters |
| - | - | - |
| `message.post` | Send text message to Pria | `inputs` (array of strings); optional `assistantId`, `selectedCourse`, `contextMode` (with `assistantId`) |
| `assistant.select` | Pre-select an assistant for text mode — stages the choice only; no message is sent and no conversation is created | `assistantId` (string, required); optional `contextMode` |
| `convo.start` | Start speech-to-speech conversation | Optional `assistantId`, `selectedCourse`, `intro`, `transcripts`, `contextMode` |
| `convo.post` | Speak into a conversation that is already running | `inputs` (array of strings); optional `role` (`user` \| `system`, default `user`), `respond` (default `true`) |
| `convo.stop` | Stop speech-to-speech conversation | None |
| `assistants.list` | Get available assistants | None |
| `favorites.list` | Get list of user's favorites | None |
| `conversations.list` | Get list of user's conversations | None |

> [!NOTE]
>
> `post` is accepted as a legacy alias for `message.post`. New integrations should use `message.post`.

### New or continued conversation (`contextMode`)

When your page picks an assistant, `contextMode` decides which conversation it lands in:

| Value | Effect |
| - | - |
| `'fresh'` | A new, empty conversation for that assistant — nothing from the previous one carries over. |
| `'continue'` | The current conversation keeps its history; the assistant takes over from the next turn. |

Defaults when you leave it out: a `convo.start` with a `selectedCourse` continues that conversation. A `convo.start` without one, and `assistant.select`, continue the current conversation in the classic interface and start fresh in the 2026 interface. A `message.post` with an `assistantId` but no `contextMode` posts into the current conversation. Any value other than `'fresh'` or `'continue'` counts as left out.

### Speaking into a running conversation

`convo.post` injects text into a voice conversation that is **already running**. It comes in two
roles, and the difference matters.

`role: 'user'` (the default) is the learner speaking. It is the exact equivalent of them saying
it out loud and having it transcribed — your twin answers it like any other thing they said.

`role: 'system'` is your page *steering* the twin: your instruction reaches the model, the twin
says it in its own words, and nothing is recorded as if the learner had said it. Use it to react
to what someone is doing on your page.

```javascript theme={null}
// The learner is typing into your page instead of speaking.
pria.send({ command: 'convo.post', inputs: ['What does this chart show?'] })

// Your page steering the twin, in its own voice.
pria.send({
    command: 'convo.post',
    inputs: ['The learner just opened the Try It panel — coach them into it.'],
    role: 'system',
    respond: true,
})
```

> [!WARNING]
>
> Two things must be true before `role: 'system'` works: an administrator has turned on **Let the
> embedding page guide live conversations** in the Digital Twin's settings, and the command comes from
> the page that hosts the twin (not a different site or a tab you opened). If either is missing, the
> command comes back refused (HTTP 401). These turns cost credits like any other.

Set `respond: false` to give the twin context **without** making it answer. Support for that
varies by provider, and where it cannot be honoured you get an explicit error rather than
silence:

| Provider | `role: 'user'` | `role: 'system'` | `respond: false` |
| - | - | - | - |
| Anam avatar, Cartesia | Answers | Answers in its own words | `system` only — kept as context for the next turn |
| ElevenLabs | Answers | Context only — lands on the learner's next turn | `system` only |
| Gemini | Answers | Answers | Not supported — returns an error |
| OpenAI Realtime | Answers | Answers | Supported |
| OpenAI GPT-Live | Answers | Answers | `system` only — kept as context |
| xAI | Answers | Not supported — returns an error | Supported for `user` |

A `user` message can be up to 4,000 characters, a `system` message up to 2,000.

### Knowing when the twin is ready

Commands sent before the twin's window is listening are held and replayed, in order, once it is —
so you can send immediately after loading without retry loops. Up to 20 commands are held, each
for at most 30 seconds; one that overflows or expires comes back as a `pria-error`. Pass
`queueUntilReady: false` on a command you would rather have fail than wait.

`pria.isSessionReady()` tells you whether a command sent right now is delivered rather than held.
For voice specifically, the twin also emits `convo.live` once per call, when the conversation can
actually accept `convo.post` — that is a different question from `convo.ready`, which only says
the user is allowed to start one. When a call ends — the person hung up inside the panel, or the
connection closed — the twin emits `convo.ended` once.

### Confirm it's you

When an admin account opens Pria from your page (for example a Canvas course page), the panel may
first show **Confirm it's you** and ask for a 6-digit code. While it waits:

* commands already held fail at once, and new ones are refused, with a `pria-error` whose
  `response.reason` is `'auth_required'` (other errors carry no `reason`);
* `pria.isAuthRequired()` returns `true`;
* the SDK calls your `onAuthRequired` display option once (see
  [Confirm it's you](https://docs.praxis-ai.com/mdx/integrations/web/introduction.md#confirm-its-you-onauthrequired)). The SDK
  does not open the panel by itself.

Nothing is replayed. Once the person confirms, the twin sends `convo.ready` again — send your
commands then.

### How a course-scoped `post` behaves

When a `post` (or `message.post`) carries `selectedCourse`, Pria switches the visible conversation
to that course's own thread before sending, so the question — and the reply — land there instead
of wherever the conversation happened to be pointed before. A few behaviors to design around when
wiring up course buttons or similar triggers:

* **Duplicates are dropped, not resent.** An identical `post` (same text, course and assistant)
  sent again within 5 seconds of the first one — or while the first one is still waiting to go
  out — is dropped, and the page gets a `pria-error` event instead of a second reply. This covers
  both a double-click and a host-side retry.
* **A post waits for Pria to be ready.** A `post` sent before the user is signed in is held — up
  to 16 seconds for sign-in, then up to 10 seconds more for the chat view — and sent once both are
  ready. If either wait times out, the post errors instead of hanging indefinitely.
* **Posts are handled one at a time.** Pria works through held or queued posts in order; a later
  post never jumps ahead of, or interrupts, one that's still being handled.
* **Trigger `post` from a plain button.** A `pria.send()` call immediately followed by a form
  submit or a page navigation can lose a post that is still waiting to be delivered (for example
  while it's held for sign-in). Use a plain button, not a submit button or a navigation handler.
* **Don't retry within 5 seconds.** Because an identical post sent within 5 seconds is dropped as
  a duplicate, a host-side retry issued right after a `post` will itself be dropped — wait past
  the 5-second window (or change the text) before retrying.

> [!NOTE]
>
> This course-switching and duplicate/ready behavior applies to `post` and `message.post`; other
> commands are unaffected.

### Privacy-policy consent

Some accounts set a privacy policy that every user must read and accept before they can chat or
talk with one of that account's Digital Twins — see
[Managing Accounts — Privacy Policy Consent Form](https://docs.praxis-ai.com/mdx/admin-guide/accounts/managing-accounts.md#privacy-policy-consent-form).
Accounts that never set one never trigger any of this.

While the current user has not yet accepted the account's policy:

* `post`, `message.post`, `convo.post` and `convo.start` are all refused with a `pria-error` whose
  `content` is exactly:

  ```
  consent_required: accept the privacy policy in the Pria panel first
  ```

* `convo.ready` reports `authorized: false` with `content.reason === 'consent_required'`, and the
  Pria panel opens by itself so the user can read and accept the policy — you don't need to open it
  yourself.

Once the user accepts, the Digital Twin sends `convo.ready` again, this time with
`authorized: true`. A host that auto-starts voice on load should wait for **this later**
`convo.ready` event rather than acting on the first one it sees, since the first `convo.ready`
after login can still carry `reason: 'consent_required'`.

### Choosing how the conversation opens

`convo.start` takes an optional `intro`:

```javascript theme={null}
pria.send({ command: 'convo.start', intro: 'Welcome back to lesson three.' })  // say this
pria.send({ command: 'convo.start', intro: false })                            // say nothing
pria.send({ command: 'convo.start' })                                          // the twin's own greeting
```

On avatar twins (Anam, Cartesia) the line is spoken word for word. On OpenAI (Realtime and GPT-Live),
Gemini and xAI the twin has no scripted opening line, so your text guides its greeting and it will
paraphrase.
ElevenLabs agents own their first message and ignore `intro`.

#### Pre-selecting an assistant (`assistant.select`)

`assistant.select` stages an assistant for the user's **next** message — nothing is posted, no conversation is created, and the user sees no injected turn. The chat interface shows the assistant as the pending choice, and the user's own first message is routed to it (from then on the conversation keeps that assistant automatically). The `assistantId` is validated against the Digital Twin's assistant list; an unknown id returns an error and the twin stays on its default.

Most integrations don't need to send this command directly — pass the `assistantId` display option at load instead (see [Assistant pre-select](https://docs.praxis-ai.com/mdx/integrations/web/introduction.md#assistant-pre-select-assistantid)) and the SDK sends it for you at the right moment. If the user later picks a different assistant in the interface, their choice wins.

### Sample Requests

> [tab] Post Message
>
> Send a text message to your digital twin:
>
> ```javascript theme={null}
> const request = {
>     command: 'message.post',
>     inputs: ['How are you?', 'Today is my birthday!']
> }
>
> pria.send(request)
> ```

> [tab] Conversation Mode
>
> Start speech-to-speech conversation:
>
> ```javascript theme={null}
> const request = {
>     command: 'convo.start'
> }
>
> pria.send(request)
> ```
>
> Stop conversation mode:
>
> ```javascript theme={null}
> const request = {
>     command: 'convo.stop'
> }
>
> pria.send(request)
> ```

> [tab] List
>
> List Assistants:
>
> ```javascript theme={null}
> const request = {
>     command: 'assistants.list'
> }
>
> pria.send(request)
> ```
>
> List Conversations:
>
> ```javascript theme={null}
> const request = {
>     command: 'conversations.list'
> }
>
> pria.send(request)
> ```
>
> List Favorites:
>
> ```javascript theme={null}
> const request = {
>     command: 'favorites.list'
> }
>
> pria.send(request)
> ```

### Error Handling

The `pria.send()` function may throw these errors:

> [!WARNING]
>
> * "Connect Pria first, then retry." - Pria is not properly initialized
> * "Function requires valid JSON." - Invalid request format

> [!NOTE]
>
> Authorization failures (for example, requesting `convo.start` when voice mode is not enabled for the user) are not thrown by `pria.send()` — they come back asynchronously as an error message with `isError: true`. See [Receiving Responses](#receiving-responses).

## Receiving Responses

### Subscribe to Responses

To receive responses from Pria, you must first subscribe:

```javascript theme={null}
const handlePriaResponse = (response) => {
    console.log('Received from Pria:', response)
    // Process the response here
}

pria.subscribe(handlePriaResponse)
```

### Response Message

A response message from the Pria AI Middleware follows a clear and structured format to ensure consistent integration and robust client parsing. Each response includes standard fields that define its source, content, format, and compatibility.

```json theme={null}
{
    "type": "pria-response",
    "response": {
        "command": "message.post",
        "content": {} | "",
        "isError": false,
        "type": "object"
    },
    "version": 1
}
```

**Response Fields**

| Field | Type | Description |
| - | - | - |
| `type` | String | `"pria-response"` for command results, or `"pria-error"` when a command failed with an unexpected error. Both identify the message as originating from Pria AI Middleware. |
| `response` | Object | Contains the actual payload and control attributes for the message. |
| `response.content` | Mixed | The content of the response—can be a String (error, status) or an Object (structured output). |
| `response.type` | String | Indicates the type of `content`. `"object"` for JavaScript objects, `"string"` otherwise. |
| `response.isError` | Boolean | `true` if the message represents an error, `false` otherwise. |
| `response.command` | String | Indicates the command handled (e.g., `message.post`, `convo.stop`). |
| `version` | Integer | The message version number for client compatibility management. |

**type**
The string constant `"pria-response"` (or `"pria-error"` for failures). Use as a filter or discriminator in your message handling logic — handle both values if you want to surface errors.

**response**
Top-level object that wraps all core response details from Pria AI Middleware.

| Subfield | Description |
| - | - |
| `content` | The main body of the response. Can be a JavaScript object (structured data) or a string (simple message or error). |
| `type` | Specifies the JavaScript type of `content`. Values are `"object"` (for JSON objects) or `"string"` (for plain text). |
| `isError` | Boolean signaling error (`true` for errors, `false` for normal responses). |
| `command` | String describing the executed command (e.g., `message.post`, `convo.start`, or `convo.stop`). |

**version**
Integer value indicating the version of the response structure. Used for ensuring compatibility with various client parsers.

> [!TIP]
>
> Always check the `version` field to ensure your parser correctly supports all required fields and response shapes.

### Sample Responses

> [tab] Successful Message
>
> ```json theme={null}
> {
>     "type": "pria-response",
>     "response": {
>         "command": "message.post",
>         "content": {
>             "success": true,
>             "outputs": ["I am doing great! Happy birthday by the way.."],
>             "usage": 12048,
>             "query_duration_ms": 9404,
>             "model": "us.anthropic.claude-3-5-sonnet-20240620-v1:0"
>         },
>         "isError": false,
>         "type": "object"
>     },
>     "version": 1
> }
> ```

> [tab] Error Response
>
> ```json theme={null}
> {
>     "type": "pria-error",
>     "response": {
>         "content": "Convo Mode (STS) not enabled. Access Unauthorized (401)",
>         "command": "convo.start",
>         "type": "string",
>         "isError": true
>     },
>     "version": 1
> }
> ```

> [tab] Conversation Control
>
> ```json theme={null}
> {
>     "type": "pria-response",
>     "response": {
>         "content": "Convo stopped (STS)",
>         "command": "convo.stop",
>         "type": "string",
>         "isError": false
>     },
>     "version": 1
> }
> ```

> [!NOTE]
>
> See  [Object Definitions](https://docs.praxis-ai.com/mdx/sdk/object-definitions.md) for a complete list of responses

## UI Control Methods

The SDK provides several methods to control Pria's visibility and display state.

### Visibility Control

Control whether Pria is visible on the page at all. When hidden, both the button and UI panel are completely removed from view.

```javascript theme={null}
// Hide Pria entirely (removes from DOM view)
pria.setVisible(false)

// Show Pria (makes button/UI available)
pria.setVisible(true)

// Check if Pria is currently visible
const visible = pria.isVisible()  // Returns true or false
```

### Display Control

Control whether the Pria UI panel is expanded or collapsed to the button.

```javascript theme={null}
// Expand the Pria UI panel
pria.display(true)

// Collapse to button only
pria.display(false)

// Check if UI panel is currently expanded
const expanded = pria.isDisplayed()  // Returns true or false
```

### Ready State

Check if Pria is fully initialized and ready to receive commands before sending messages:

```javascript theme={null}
// Check if Pria is ready to receive messages
const ready = pria.isReady()  // Returns true or false

// Wait for Pria to be ready before sending commands
if (pria.isReady()) {
    pria.send({ command: 'assistants.list' })
}
```

> [!TIP]
>
> Always check `isReady()` before sending commands to ensure the SDK is fully connected to the middleware.

**Recommended Ready Check Pattern:**

When integrating Pria, use this pattern to safely check if the SDK is ready:

```javascript theme={null}
/**
 * Check if Pria SDK is ready to receive messages
 * @returns {boolean} True if SDK is fully connected and ready
 */
function isPriaReady() {
    return window.pria && 
           typeof window.pria.isReady === 'function' && 
           window.pria.isReady();
}

// Usage
if (isPriaReady()) {
    window.pria.send({ command: 'convo.start' });
}
```

### Convo Ready State

After the user authenticates, the Digital Twin sends a `convo.ready` event to the SDK indicating whether real-time voice (speech-to-speech) mode is authorized for the current user. The SDK captures this and exposes it via `isConvoReady()`.

```javascript theme={null}
// Check if real-time voice mode is authorized for this user
const convoReady = pria.isConvoReady()  // Returns true or false
```

> [!NOTE]
>
> `isConvoReady()` returns `false` until the Digital Twin sends the `convo.ready` event after login. This happens automatically — you do not need to request it. If the account has an unaccepted privacy policy, `authorized` stays `false` and `content.reason` is `'consent_required'` — see [Privacy-policy consent](#privacy-policy-consent) above.

**The `convo.ready` event:**

The `convo.ready` event is a proactive notification sent by the Digital Twin after the user logs in. It tells the embedding application whether real-time voice is available. You can listen for this event via `pria.subscribe()`:

```javascript theme={null}
pria.subscribe((data) => {
    if (data?.type === 'pria-response' && data?.response?.command === 'convo.ready') {
        const authorized = data.response.content?.authorized === true;
        console.log('Voice mode authorized:', authorized);

        if (authorized) {
            // Voice is available — render your voice-first UI
        }
    }
});
```

**Full-screen voice mode example (hide UI while loading, show when voice is ready):**

This pattern keeps the Digital Twin hidden during initialization and only reveals it when voice mode is confirmed ready, providing a seamless voice-first experience:

```javascript theme={null}
// Step 1: Load SDK with UI hidden
const displayOptions = {
    fullScreen: true,
    openOnLoad: false,     // Don't open the panel yet
    noUI: true             // Hide button and panel entirely during loading
};

PriaIntegration.loadSdk(
    'https://pria.praxislxp.com',
    displayOptions,
    instanceConfig,
    userConfig
);

// Step 2: Wait for SDK to be ready, then listen for convo.ready
const timer = setInterval(() => {
    if (!window.pria?.isReady()) return;
    clearInterval(timer);

    window.pria.subscribe((data) => {
        if (data?.type !== 'pria-response') return;
        const command = data.response?.command;

        // Step 3: When convo.ready arrives and is authorized, start voice mode
        if (command === 'convo.ready' && data.response.content?.authorized) {
            // Make the widget visible
            window.pria.setVisible(true);

            // Start voice mode (optionally target a specific assistant/conversation)
            window.pria.send({
                command: 'convo.start',
                assistantId: '674e9fd3d7e18aa82eb49fda',  // optional
                selectedCourse: {                               // optional
                    course_id: 123,
                    course_name: 'Customer Onboarding'
                }
            });

            // Expand the UI panel to full screen
            window.pria.display(true);
        }

        // Step 4: When convo starts, the voice interface is live
        if (command === 'convo.start') {
            console.log('Voice mode is live');
        }
    });
}, 500);
```

> [!TIP]
>
> For a simpler approach without custom subscriber logic, use the `convoMode` display option which handles auto-start automatically. See [Convo Mode display option](https://docs.praxis-ai.com/mdx/integrations/web/introduction.md#convo-mode-convomode).

### Live voice transcripts (`convo.transcript`)

When the Digital Twin allows it (**Share voice transcripts with the embedding page** in the twin's settings) and your page asks for it, the twin sends the learner's words and the avatar's answers to your page live, as the voice conversation happens — for every voice provider.

**Ask for them** with the `transcripts` display option (the SDK subscribes for you as soon as the twin is ready), or send the command yourself at any time:

```javascript theme={null}
const displayOptions = { transcripts: true }
// or, later:
pria.send({ command: 'transcripts.subscribe' })    // answer: { subscribed: true, enabled: <twin allows it> }
pria.send({ command: 'transcripts.unsubscribe' })
```

**Receive them** through your subscriber:

```javascript theme={null}
pria.subscribe((data) => {
    if (data?.type !== 'pria-response') return
    const { command, content } = data.response
    if (command === 'convo.transcript') {
        // content: { schema: 1, role: 'user' | 'assistant', text, final, turnId, seq, ts, reason,
        //            provider, sessionId, assistantId, confidence, startedAt, endedAt }
        upsertLine(`${content.role}:${content.turnId}`, content.text, content.final)
    } else if (command === 'convo.speech_started' || command === 'convo.speech_ended') {
        // content: { turnId } — drive a "listening…" indicator
    } else if (command === 'convo.stopped') {
        // content: { sessionId } — the call ended; close your transcript pane
    }
})
```

* `final: false` messages are live captions (at most a few per second); `final: true` carries the **full text** of the turn — replace, never stitch.
* `turnId` links the learner's turn and the avatar's reply to it. **A later message with the same `turnId` replaces the earlier one**: on Anam twins a fast learner turn may arrive as `reason: "eager"`, be reopened with `reason: "resumed"` if the learner keeps talking, then be confirmed with `reason: "end_of_turn"`. `interrupted` means the avatar was cut off (barge-in or the call ended), `error` that the answer failed, `intro` the opening greeting, `typed` a message typed during the call, and `empty` that the twin produced no reply to an instruction your page sent with `convo.post` (its `text` is empty).
* `seq` orders messages; `confidence`, `startedAt` and `endedAt` are filled when the speech recogniser reports them (`null` otherwise).
* Transcripts are only ever sent to the page that hosts the Pria frame, at its own origin. They contain personal data: make sure your privacy notice covers them.

### Cleanup and Destroy

Properly destroy and remove Pria when no longer needed:

```javascript theme={null}
// Remove Pria completely and clean up all resources
pria.destroy()
```

The `destroy()` method performs complete cleanup:

* Removes all UI elements (iframe, button, containers)
* Removes injected CSS and OAuth scripts
* Cleans up all event listeners (keyboard shortcuts, drag handlers, message handlers)
* Clears internal state and subscriber callbacks
* Removes `window.pria` and `window.priasdk` references

> [!WARNING]
>
> After calling `destroy()`, the SDK must be completely reloaded to use Pria again. All references to `pria` become invalid.

**Destroy and Reload Pattern:**

If using the Web SDK wrapper (`PriaIntegration`), use these methods for clean lifecycle management:

```javascript theme={null}
// Destroy SDK completely
PriaIntegration.destroySdk();

// Reload SDK with configuration
PriaIntegration.reloadSdk(
    'https://pria.praxislxp.com',
    displayOptions,
    instanceConfig,
    userConfig
);

// Check if SDK is ready via wrapper
if (PriaIntegration.isReady()) {
    window.pria.send({ command: 'assistants.list' });
}
```

### UI Control Reference

| Method | Purpose | Effect |
| - | - | - |
| `isReady()` | Check ready state | Returns `true` if SDK is fully connected and ready |
| `isSessionReady()` | Check delivery | Returns `true` if a command sent now is delivered rather than held |
| `isConvoReady()` | Check voice readiness | Returns `true` if real-time voice mode is authorized for this user |
| `isAuthRequired()` | Check for a pending code | Returns `true` while the panel waits for the person to confirm it's them |
| `setVisible(false)` | Hide Pria entirely | Button and UI panel are hidden from view |
| `setVisible(true)` | Show Pria | Button and UI panel become available |
| `display(false)` | Collapse UI | UI panel closes, button shows |
| `display(true)` | Expand UI | UI panel opens, button hides |
| `isVisible()` | Check visibility | Returns `true` if Pria is visible |
| `isDisplayed()` | Check panel state | Returns `true` if UI panel is expanded |
| `destroy()` | Remove Pria | Cleans up all resources and removes from page |

## Working with the SDK

### Authentication & Security

> [!NOTE]
>
> The SDK uses the identity of the user currently connected to the digital twin. Ensure proper authentication is in place before making requests.

### Requirements

* Pria must be properly configured and fully connected
* User must be authenticated with appropriate permissions
* Valid session must be established

### Content Format

> [!NOTE]
>
> Pria outputs content in [Markdown format](https://en.wikipedia.org/wiki/Markdown). Parse responses accordingly in your application.

### Error Handling

It is best practice to wrap function calls in a try/catch block to avoid unhandled exceptions:

```javascript theme={null}
const sendMessage = async (message) => {
    try {
        const request = {
            command: 'message.post',
            inputs: [message]
        }
        
        pria.send(request)
    } catch (error) {
        console.error('Failed to send message:', error)
        // Handle error appropriately
    }
}
```

### Response Processing

It is best practice to handle responses from Pria by looking at the response message `type`, `isError`, `command`, etc. so your handler covers every situation:

```javascript theme={null}
const handleResponse = (responseMessage) => {
    
    // Accept both normal responses and error messages
    if (responseMessage?.type !== "pria-response" && responseMessage?.type !== "pria-error") return 

    const response = responseMessage?.response 
    if (!response) return;

    if (response.isError) {
        console.error('Pria error:', response.content)
        return
    }

    // handle content as String 
    if (response.type==='string') {
        
        console.log("Response:", response.content)

    }
    // handle response as object 
    else {
        

        // handling a response from message.post
        if (response.command == "message.post"){
        
            const outputs = response.content?.outputs
            if (outputs){
                outputs.forEach(output => {
                    // Display or process each output
                    console.log(output)
                })
            }
        }
    }
}
```

### Cleanup

Consider removing the event handlers you have declared when subscribing to receive response messages before your application terminates. Pass the **same function reference** you subscribed with:

```javascript theme={null}
// Unsubscribe when component unmounts or page unloads
window.addEventListener('beforeunload', () => {
    pria.unsubscribe(handlePriaResponse)
})
```

## Troubleshooting

### Common Issues

| Issue | Solution |
| - | - |
| "Connect Pria first" error | Ensure SDK is loaded and initialized |
| No responses received | Check if you've subscribed to responses |
| Unauthorized errors | Verify user authentication and permissions |
| Invalid JSON errors | Validate request format and structure |

### Debugging

The SDK logs its lifecycle to the browser console — watch for messages such as `Pria SDK initialization started`, `PriaIntegration already loaded`, and `Failed to load Pria SDK` while troubleshooting. Logging every message your subscriber receives is the quickest way to see exactly what the middleware returned:

```javascript theme={null}
pria.subscribe((message) => {
    console.log('Pria message:', JSON.stringify(message, null, 2))
})
```

## Examples

See complete, runnable integration examples — the live SDK Playground and a full `PriaTestHarness` API class you can adapt for your own application.

> [card] [JavaScript SDK Examples](https://docs.praxis-ai.com/mdx/sdk/javascript-examples.md)
>
> The SDK Playground demo plus a complete `PriaTestHarness` class showing clean initialization, connection detection, and command handling (`message.post`, `convo.start`/`convo.stop`, `assistants.list`, and more).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.