# SDK initialization

> You're reading the Mindset v3 documentation. v3 is no longer sold; this is reference for existing customers. Mindset 4 docs are at /docs.

window.mindset.init() and the SDK-level surface: app config, auth, and what stays at the page level.

The Mindset AI SDK is initialized once per page. After the bundle loads from your `<script>` tag, you call `window.mindset.init()` with your app UID and an authentication callback. The init function attaches runtime instances to every `<mindset-agent>` element on the page and watches for new ones added later.

Per-agent setup happens on the element itself, not here. This page covers the page-level API: the things you do once.

---

## `window.mindset.init(config)`

Initialize the SDK. Call once after the bundle loads.

**Signature:**

```ts
window.mindset.init(config: InitConfig): Promise<void>
```

**Returns:** A promise that resolves once the SDK has set up shared resources. The agents themselves initialize in parallel. Listen for `mindset:agent-idle` on each element to know it's ready. Note that an agent configured with an icebreaker will fire that turn immediately after the first idle event. The [`sendWhenIdle` pattern](https://docs4.mindset.ai/v3/deploy/sdk3-client-apis/methods#waiting-for-the-agent-to-be-ready) handles this so you don't need to track which configuration applies.

### `InitConfig`

| Field                          | Type                    | Required                       | Description                                                                                              |
| ------------------------------ | ----------------------- | ------------------------------ | -------------------------------------------------------------------------------------------------------- |
| `appUid`                       | `string`                | Yes                            | Your app's UID. Available in the Agent Management Studio.                                                |
| `fetchAuthentication`          | `() => Promise<string>` | Yes (for authenticated agents) | Async callback the SDK calls to obtain a user token. See [Authentication](#authentication) below.        |
| `extendedSituationalAwareness` | `boolean`               | No                             | Lifts the situational-awareness character limit from 10,000 to 20,000 across the page. Default: `false`. |
| `theme`                        | `ThemeConfig`           | No                             | Page-level theme override. Per-element `theme` attributes override this.                                 |
| `initialQuestion`              | `string`                | No                             | Default first question used by all agents on the page. Per-element `initial-question` overrides.         |

```js
window.mindset.init({
  appUid: 'your-app-uid',
  fetchAuthentication: async () => {
    const r = await fetch('/api/mindset-token', { credentials: 'include' });
    const { authToken } = await r.json();
    return authToken;
  },
});
```

### When to call `init`

You can call `init` before or after `<mindset-agent>` elements are in the DOM. Both orders work:

- If you init first and then add elements (common when you mount agents from a JS framework like React or Vue), the SDK's `MutationObserver` picks up elements as they're added.
- If you add elements first and then init (common with static HTML), the SDK finds existing elements and binds them.

Either way, the page-level config and per-element attributes apply at bind time. Element methods (`setPageTools`, `setSituationalAwareness`, `sendMessage`, thread CRUD, etc.) become callable after `mindset.init()` completes and the element fires `mindset:agent-idle`. See [§ When the element is ready to call](https://docs4.mindset.ai/v3/deploy/sdk3-client-apis/methods#when-the-element-is-ready-to-call).

---

## Authentication

The SDK delegates auth to your `fetchAuthentication` callback. The callback returns a token your app's backend mints from `sdkusersapi`. The SDK exchanges that token for the credentials the runtime needs.

```js
window.mindset.init({
  appUid: 'your-app-uid',
  fetchAuthentication: async () => {
    // Call your own backend, which calls sdkusersapi
    const r = await fetch('/api/mindset-token', { credentials: 'include' });
    const { authToken } = await r.json();
    return authToken;
  },
});
```

The callback runs:

- Once when the SDK first needs a token
- Again whenever the token expires and needs refreshing

You write the callback as if it always fetches fresh. The SDK handles caching and refresh timing internally.

> **Note:** **Token endpoint setup.** Setting up the backend endpoint that mints SDK tokens (calling `sdkusersapi`, configuring API keys, mapping users to Mindset AI identities) is a one-time piece of integration work covered in the existing Mindset AI auth docs.
>
> See the [SDK 3 Authentication guide](https://docs4.mindset.ai/v3/deploy/sdk3/sdk3-authentication) for the end-to-end flow, and the [SDK Users API reference](https://docs4.mindset.ai/v3/deploy/api/sdkusers-api) for the parameter-level detail.

### Anonymous agents

If your agent is configured to allow anonymous access in the Agent Management Studio, you can omit `fetchAuthentication`. The agent will run without identifying the user. Useful for public-facing demos and unauthenticated marketing pages.

For authenticated agents, the callback is required. Without it, the agent fires `mindset:agent-error` with `code: 'agent_loading_failed'` (or `'model_loading_failed'`) instead of reaching `mindset:agent-idle`. Listen for `mindset:agent-error` during integration testing so silent auth misconfigurations are caught early.

---

## Auth state helpers

The SDK exposes Firebase-backed sign-in helpers for apps that use Mindset AI's hosted authentication. These are page-level: you call them on `window.mindset`, not on a specific agent.

| Function                                      | Returns                   | Description                                                                                         |
| --------------------------------------------- | ------------------------- | --------------------------------------------------------------------------------------------------- |
| `window.mindset.onAuthStateChanged(callback)` | unsubscribe function      | Fires whenever the user's auth state changes. Useful for showing or hiding agents based on sign-in. |
| `window.mindset.signInWithGoogle()`           | `Promise<UserCredential>` | Opens the Google sign-in flow.                                                                      |
| `window.mindset.signInWithMicrosoft()`        | `Promise<UserCredential>` | Opens the Microsoft sign-in flow.                                                                   |
| `window.mindset.signOut()`                    | `Promise<void>`           | Signs the user out.                                                                                 |

```js
const unsubscribe = window.mindset.onAuthStateChanged((user) => {
  if (user) {
    showAgentPanel();
  } else {
    hideAgentPanel();
  }
});

// Later
unsubscribe();
```

If your app handles its own auth and uses `fetchAuthentication` to mint tokens server-side, you don't need these helpers.

---

## Page-level utilities

| Function                               | Description                                                                                                                                                                      |
| -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `window.mindset.listWidgetTemplates()` | Returns the catalog of widget templates available to the agents on this page. Useful when you're building a UI that renders tool widgets and need to know what shapes to expect. |

---

## What lives where

| Concern                | Set on             | Example                                                           |
| ---------------------- | ------------------ | ----------------------------------------------------------------- |
| App identity           | `init` config      | `appUid`                                                          |
| User identity          | `init` config      | `fetchAuthentication`                                             |
| Page-wide defaults     | `init` config      | `extendedSituationalAwareness`, `theme`, `initialQuestion`        |
| Auth state listening   | `window.mindset.*` | `onAuthStateChanged`                                              |
| Per-agent identity     | element attribute  | `agent-uid`                                                       |
| Per-agent runtime mode | element attribute  | `headless`                                                        |
| Per-agent context      | element method     | `setSituationalAwareness`, `setPassthroughParams`, `setPageTools` |
| Per-agent turns        | element method     | `sendMessage`                                                     |
| Per-agent threads      | element method     | `newThread`, `switchThread`, etc.                                 |

The boundary: anything that varies across agents lives on the element. Anything page-wide lives on `window.mindset`.

---

## Error handling

`init` rejects if:

- `appUid` is missing or invalid
- The bundle hasn't finished loading (race condition, so use a `defer` script or call `init` from `DOMContentLoaded`)

Errors during agent loading surface on the affected element as `mindset:agent-error` with a code (e.g. `model_loading_failed`, `agent_loading_failed`) and a human-readable message. Listen on the element if you want to handle these:

```js
agent.addEventListener('mindset:agent-error', (e) => {
  console.error(`Agent error [${e.detail.code}]: ${e.detail.message}`);
});
```
