---
updatedAt: 2026-08-03T22:48:34.000Z
agentTools:
  projectIndex: https://dev.frontapp.com/llms.txt
---

# Autopilot Resolve SDK Reference

This page documents the JavaScript SDK for embedding <Anchor target="_blank" href="https://help.front.com/en/articles/4836160">Autopilot Resolve</Anchor> on your site. It is intended for developers who need advanced programmatic control over initialization, visibility, layout, and client context.

<Callout icon="📘" theme="info">
  Most customers should use the auto-init embed snippet from <Anchor target="_blank" href="https://help.front.com/en/articles/4836160#settings_deploy">Front admin settings</Anchor> — add the boot script with `data-auto-init` and the widget initializes automatically. This reference topic covers the `window.FrontCompanion` object API for cases where you need more control (SPAs, custom launchers, dynamic context updates, etc.).
</Callout>

<br />

## `FrontCompanion.init(params)`

Use `init()` when you need programmatic control over widget initialization — for example, in a single-page app where the user is not ready at page load, or when you want to use a custom launcher button.

Load the boot script **without** `data-auto-init`, then call `init()` when you are ready to mount the widget:

```jsx
await window.FrontCompanion.init({
  container: document.getElementById('companion-container'),
  companionToken: 'YOUR_COMPANION_TOKEN',
  layout: 'widget-right',
});
```

### Notes

* Call `init()` once per page load unless you call `shutdown()` first.
* `container` and `companionToken` are required.
* Returns a `Promise` that resolves when the Autopilot Resolve widget finishes initializing.
* `window.FrontCompanion` is available as soon as Autopilot Resolve is initialized.

### Init options

| Option           | Required | Description                                                                                                                                                   |
| ---------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `container`      | Yes      | The `HTMLElement` to append the iframe into                                                                                                                   |
| `companionToken` | Yes      | Your companion token from Front admin settings                                                                                                                |
| `layout`         | No       | Layout preset (see [Layout presets](https://dev.frontapp.com/docs/autopilot-resolve-sdk-reference#layout-presets) below)                                      |
| `launcher`       | No       | `default` shows the launcher button; `none` hides the iframe at the launcher view until `show()` is called                                                    |
| `sideMargin`     | No       | Side margin, e.g. `'24px'` (max 100px)                                                                                                                        |
| `bottomMargin`   | No       | Bottom margin, e.g. `'24px'` (max 100px)                                                                                                                      |
| `context`        | No       | Initial client context object (see [Client context](https://dev.frontapp.com/docs/autopilot-resolve-sdk-reference#client-context) below)                      |
| `userJwt`        | No       | JWT for auto-verification of logged-in users (see [Verified identity](https://dev.frontapp.com/docs/autopilot-resolve-sdk-reference#verified-identity) below) |

***

## `FrontCompanion.shutdown()`

Removes the iframe from the page and shuts down all event listeners. Call `init()` again to remount the widget.

```jsx
await window.FrontCompanion.shutdown();
```

***

## `FrontCompanion.show()`

Opens the Autopilot Resolve window.

```jsx
await window.FrontCompanion.show();
```

***

## `FrontCompanion.hide()`

Closes the Autopilot Resolve window. If `launcher` was set to `none`, no launcher button appears after the window closes.

```jsx
await window.FrontCompanion.hide();
```

***

## `FrontCompanion.layout(layoutPreset, marginParams?)`

Changes the widget layout at runtime. The following example switches to a left sidebar with custom margins:

```jsx
await window.FrontCompanion.layout('sidebar-left', {
  sideMargin: '32px',
  bottomMargin: '24px',
});
```

On viewports **639px wide or narrower**, `sidebar-left` and `sidebar-right` automatically adapt to a mobile-friendly fullscreen layout. Sidebar margins configured via `init()`, `layout()`, or `data-*` attributes may not apply at this breakpoint. This behavior is automatic and cannot be configured via the SDK.

***

## Client context

You can pass customer-specific data to Autopilot Resolve to help the AI understand who the user is and where they are on your site.

<Callout icon="📘" theme="info">
  You may not include objects that would cause sensitive personal data to be passed through Front’s products and services based on Front’s [General Terms](https://front.com/legal/saas-services-agreement).
</Callout>

* Up to **10 custom keys** (excluding the reserved `page_details` key)
* Values must be `string`, `boolean`, or `number`
* Key names: max 64 characters; string values: max 512 characters
* `page_details` is reserved and auto-populated by the boot script (URL, title, referrer, etc.) when enabled for your channel

### `FrontCompanion.setContext(context)`

Replaces the entire client context with the object you provide.

```jsx
await window.FrontCompanion.setContext({
  brand_name: 'Osteria Group',
  restaurant_name: 'Osteria Downtown',
  restaurant_id: 'rest_001',
  product_name: 'Margherita Pizza',
});
```

You can also pass `context` in the `init()` call to set the initial context at mount time.

### `FrontCompanion.mergeContext(context)`

Merges new fields into the existing context without overwriting unrelated keys.

```jsx
await window.FrontCompanion.mergeContext({
  product_name: 'Margherita Pizza',
  restaurant_name: 'Osteria Downtown',
});
```

### `FrontCompanion.removeContext(keys)`

Removes one or more context keys by name.

```jsx
await window.FrontCompanion.removeContext(['product_name']);
```

***

## Verified identity

When **auto-verification** is enabled in your Front admin settings, Autopilot Resolve can recognize logged-in users automatically, with no additional verification step required in the widget.

Your **secret key** is available in Front settings under **Security → Auto-verification**.

<Callout icon="❗️" theme="error">
  Never expose this key in client-side code.
</Callout>

### Generate a server-side token

On your server, use your **secret key** to sign a token containing the logged-in user's details.

```typescript
import {SignJWT} from 'jose';

const secret = new TextEncoder().encode('YOUR_SECRET_KEY');

async function main() {
  const token = await new SignJWT({ email: '<USER_EMAIL>' })
    .setProtectedHeader({ alg: 'HS256' })
    .setExpirationTime('1h')
    .sign(secret);

  console.log(token);
}

void main();
```
```python Python
import jwt
from datetime import datetime, timedelta, timezone

secret = "YOUR_SECRET_KEY"
payload = {
    "email": "<USER_EMAIL>",
    "exp": datetime.now(timezone.utc) + timedelta(hours=1),
}

token = jwt.encode(payload, secret, algorithm="HS256")

print(token)
```
```go
package main

import (
    "fmt"
    "time"
    "github.com/golang-jwt/jwt/v5"
)

func main() {
    secret := []byte("YOUR_SECRET_KEY")
    claims := jwt.MapClaims{
        "email": "<USER_EMAIL>",
        "exp":   jwt.NewNumericDate(time.Now().Add(time.Hour)),
    }

    token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString(secret)
    if err != nil {
        panic(err)
    }

    fmt.Println(token)
}
```

### Pass the token to the widget

Once you have generated the token on your server, pass it to the widget during initialization.

**Auto-init:** add the `data-user-jwt` attribute to your boot script tag.

```html
<div id="companion-container"></div>
<script
  type="module"
  id="front-companion-script"
  src="https://companion.frontapp.com/assets/boot.bundle.js"
  data-auto-init
  data-container-id="companion-container"
  data-token="YOUR_COMPANION_TOKEN"
  data-user-jwt="<GENERATED_JWT>"
  data-layout="widget-right"
></script>
```

**FrontCompanion SDK:** pass `userJwt` in the `init()` call.

```jsx
await window.FrontCompanion.init({
  container: document.getElementById('companion-container'),
  companionToken: 'YOUR_COMPANION_TOKEN',
  userJwt: '<GENERATED_JWT>',
  layout: 'widget-right',
});
```

***

## Conversation events

Subscribe to conversation lifecycle events to react to what's happening inside Autopilot Resolve. For example, you could trigger an analytics event in your system when a conversation escalates, or you could update your UI when the end user starts a new conversation, etc.

### Event shape

`on()` and `onConversationEvent` deliver the `FrontCompanionEvent` — which is a union keyed by `type`, so it can grow as new event domains ship without breaking existing handlers. The only field every domain is guaranteed to share is the discriminant itself:

| Field  | Type     | Description                                                     |
| ------ | -------- | --------------------------------------------------------------- |
| `type` | `string` | Domain discriminant. `'conversation'` is the only domain today. |

A conversation event extends the base with the fields below — and its `eventType` values are scoped to `type: 'conversation'`:

| Field            | Type                                                                                                        | Description                                                                                                                               |
| ---------------- | ----------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `type`           | `'conversation'`                                                                                            | Domain discriminant                                                                                                                       |
| `conversationId` | `string`                                                                                                    | The conversation the event belongs to                                                                                                     |
| `createdAt`      | `number`                                                                                                    | Epoch milliseconds when the event occurred                                                                                                |
| `eventType`      | `'created' \| 'viewed' \| 'escalation_offered' \| 'escalated' \| 'escalation_declined' \| 'status_changed'` | The lifecycle transition that occurred                                                                                                    |
| `status`         | `'open' \| 'in_progress' \| 'resolved'`                                                                     | Only present when `eventType` is `'status_changed'` — it's not a generic optional field on every event, it's tied to that one `eventType` |

Because `FrontCompanionEvent` is a union over `type`, always narrow on `event.type` before reading domain-specific fields like `eventType` — that's what keeps a handler written today safe if a non-`'conversation'` event ever reaches it.

### Conversation event types

| Event type            | Fires when                                                                                                        |
| --------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `created`             | The end user starts a new conversation                                                                            |
| `viewed`              | The end user opens or navigates to a conversation, including on initial load if a `conversationId` is already set |
| `escalation_offered`  | Autopilot Resolve offers to hand the conversation off to a human teammate                                         |
| `escalated`           | The conversation is handed off to a human teammate                                                                |
| `escalation_declined` | The end user dismisses an escalation offer                                                                        |
| `status_changed`      | The conversation's status changes (see `status` above)                                                            |

### `FrontCompanion.on(handler)`

Subscribes to every conversation event. Unlike other SDK methods, `on()` is synchronous — it returns an unsubscribe function directly rather than a `Promise`, so you have it immediately.

```jsx
const unsubscribe = window.FrontCompanion.on((event) => {
  if (event.type !== 'conversation') {
    return;
  }

  if (event.eventType === 'escalated') {
    trackAnalyticsEvent('support_escalated', {conversationId: event.conversationId});
  }
});

// Later, when you no longer want to listen
unsubscribe();
```

`on()` is a catch-all: every event, across every domain, is delivered to every listener. Check `event.type` first, then switch on `event.eventType` (and `event.status` for `status_changed`) to handle the ones you care about. A handler that throws is isolated — it won't stop other listeners, or the widget itself, from working.

If you call `init()` yourself (rather than relying on auto-init), calling `on()` first is enough to catch the very first `created`/`viewed` pair — `window.FrontCompanion` (including `on`) exists as soon as the boot script has loaded, before your `init()` call runs:

```jsx
const unsubscribe = window.FrontCompanion.on((event) => {
  console.log('conversation event', event);
});

await window.FrontCompanion.init({
  container: document.getElementById('companion-container'),
  companionToken: 'YOUR_COMPANION_TOKEN',
  layout: 'widget-right',
});
```

<Callout icon="📘" theme="info">
  `shutdown()` clears every listener registered via `on()`. If you `init()` again afterward, call `on()` again too — subscriptions don't survive a shutdown.
</Callout>

### `onConversationEvent` init option

Pass `onConversationEvent` to `init()` to register a listener in the same call, without a separate `on()` line:

```jsx
await window.FrontCompanion.init({
  container: document.getElementById('companion-container'),
  companionToken: 'YOUR_COMPANION_TOKEN',
  layout: 'widget-right',
  onConversationEvent: (event) => {
    console.log('conversation event', event);
  },
});
```

Calling `init()` again with a new `onConversationEvent` replaces the previous handler rather than adding a second one — so re-running your init logic (for example after `enable(false)` → `enable(true)`) doesn't accumulate duplicate listeners.

**Auto-init:** add the `data-on-conversation-event` attribute, pointing at a function defined on `window`, the same way you would wire up `data-on-conversation-change`:

```html
<script>
  window.handleConversationEvent = (event) => {
    console.log('conversation event', event);
  };
</script>
<div id="companion-container"></div>
<script
  type="module"
  id="front-companion-script"
  src="https://companion.frontapp.com/assets/boot.bundle.js"
  data-auto-init
  data-container-id="companion-container"
  data-token="YOUR_COMPANION_TOKEN"
  data-on-conversation-event="handleConversationEvent"
></script>
```

### `companion-conversation-event` window event

Autopilot Resolve also dispatches every conversation event as a `CustomEvent` on `window`, independent of `init()` and `on()`. Because it's a plain DOM event, you can attach a listener before the boot script even loads — for example, from an inline script at the top of the page — and still catch events emitted early in the widget's lifecycle:

```jsx
window.addEventListener('companion-conversation-event', (customEvent) => {
  console.log('conversation event', customEvent.detail);
});
```

`customEvent.detail` has the same shape as the event object documented above.

***

## Integration patterns

### Single-page apps (SPA)

Load the boot script once when your app initializes. On route changes, update context with `mergeContext()` or `removeContext()` rather than reinitializing the widget. Call `shutdown()` only on full logout or when you need to unmount the widget entirely.

```jsx
// After a route change (same integration deployed across multiple restaurant sites/pages)
const restaurant = {
  brand_name: 'Osteria Group',
  restaurant_id: 'rest_014',
  restaurant_name: 'Osteria Waterfront',
};

await window.FrontCompanion.mergeContext(restaurant);

// Optional: clear any keys that no longer apply
await window.FrontCompanion.removeContext(['checkout_step']);
```

### Custom launcher

To use your own button to open the widget, set `launcher: 'none'` (or `data-launcher="none"`) during initialization and wire your button to `FrontCompanion.show()`.

```jsx
await window.FrontCompanion.init({
  container,
  companionToken: 'YOUR_COMPANION_TOKEN',
  layout: 'widget-right',
  launcher: 'none',
});

document.getElementById('help-button').addEventListener('click', () => {
  window.FrontCompanion.show();
});
```

### Multiple instances

Only one instance of the widget is supported per page. Calling `init()` when the widget is already initialized logs a warning and has no effect.

***

## Content Security Policy (WIP)

<Callout icon="📘" theme="info">
  If you encounter any issues with the Content Security Policy, please let us know in the [community](https://community.front.com/developer-q-a-37).
</Callout>

Content Security Policy (CSP) is a browser security mechanism that controls what content can load or execute on your website. If your site uses CSP headers, you may need to update your policy to allow Autopilot Resolve to load and embed correctly.

### How Autopilot Resolve embeds

Autopilot Resolve uses a two-part embed on your page:

1. A **boot script** loaded from `companion.frontapp.com` exposes `window.FrontCompanion` and mounts the widget
2. An **iframe** whose `src` points to a page Front hosts at `companion.frontapp.com`, where the widget app runs

Because the widget runs in a cross-origin iframe on Front's domain, **your CSP mainly needs to allow that embed shell** — the boot script and the iframe. API calls, realtime messaging, and other network activity happen inside the iframe, not on your page.

### Directives for your site

The following directives are required for most customers.

`script-src` — allow the boot script:

```
https://companion.frontapp.com
```

`frame-src` — allow the companion iframe:

```
https://companion.frontapp.com
```

`style-src` — likely required:

```
'unsafe-inline'
```

The boot script applies inline layout styles to the iframe element (position, size, margins). A strict `style-src` without `'unsafe-inline'` may prevent the widget from rendering correctly.

### Example (production)

```
Content-Security-Policy:
  script-src ... https://companion.frontapp.com;
  frame-src ... https://companion.frontapp.com;
  style-src ... 'unsafe-inline';
```

Adjust this example to match your existing policy syntax (Report-Only, meta tag, etc.).

### Troubleshooting (CSP)

* `window.FrontCompanion`**&#x20;is undefined** — The boot script is being blocked by `script-src`.
* **Blank area where widget should appear** — The iframe is being blocked by `frame-src`, or layout styles are being blocked by `style-src`.
* **Widget loads but looks mispositioned** — Try adding `'unsafe-inline'` to `style-src`.

***

## Troubleshooting

* `window.FrontCompanion`**&#x20;is undefined** — The boot script has not finished loading. Wait for the script to load before calling SDK methods.
* **Embed renders blank** — Verify that `container`, `companionToken`, and `data-layout` are all set correctly.
* `file://`**&#x20;protocol** — Local file URLs are not supported. Serve your page over HTTPS.
* **CSP / iframe restrictions** — Ensure your Content Security Policy allows framing from `companion.frontapp.com`.

***

## Reference

### Layout presets

These values correspond to the layout options available in Front admin settings (**Sidebar widget** and **Floating widget**).

| Preset          | Description                   |
| --------------- | ----------------------------- |
| `sidebar-right` | Sidebar panel on the right    |
| `sidebar-left`  | Sidebar panel on the left     |
| `widget-right`  | Floating widget, bottom-right |
| `widget-left`   | Floating widget, bottom-left  |

### Full example (FrontCompanion SDK)

```jsx
const container = document.getElementById('companion-container');

await window.FrontCompanion.init({
  container,
  companionToken: 'YOUR_COMPANION_TOKEN',
  layout: 'widget-right',
  launcher: 'none',
  sideMargin: '24px',
  bottomMargin: '24px',
  userJwt: '<GENERATED_JWT>',
  context: {
    brand_name: 'Osteria Group',
    restaurant_id: 'rest_001',
    restaurant_name: 'Osteria Downtown',
    product_name: 'Margherita Pizza',
  },
});

document.getElementById('help-button').addEventListener('click', () => {
  window.FrontCompanion.show();
});

// Later, when the host app navigates to a different restaurant page
const restaurant = getRestaurantFromUrl(window.location.pathname);

await window.FrontCompanion.mergeContext({
  brand_name: restaurant.brandName,
  restaurant_id: restaurant.id,
  restaurant_name: restaurant.name,
});
```

***