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

# Web SDK API reference

> Reference for window.ChatWidget and the optional Web Push add-on.

The widget script defines `window.ChatWidget`. Call `init()` once, then wait for the promise it returns before calling other methods. See [Installation](https://docs.sagepilot.ai/sdks/web/installation.md). The optional `@sagepilot-ai/web-push-addon` has a separate lifecycle documented below.

## Methods

| Method | Returns |
| - | - |
| `ChatWidget.init(config)` | `Promise<void>` |
| `ChatWidget.open()` | `boolean` |
| `ChatWidget.close()` | `boolean` |
| `ChatWidget.toggle()` | `boolean` |
| `ChatWidget.isOpen()` | `boolean` |
| `ChatWidget.identify(identity)` | `Promise<IdentifyResult>` |
| `ChatWidget.logout()` | `void` |
| `ChatWidget.getIdentityState()` | `{ identified, pending, customer }` |
| `ChatWidget.onIdentify(callback)` | `void` |
| `ChatWidget.setDraft(text)` | `Promise<CommandResult>` |
| `ChatWidget.sendMessage(text)` | `Promise<CommandResult>` |

## Setup

### `init(config)`

Loads the channel and adds the launcher and chat to the page. Resolves when the widget is ready to use. See [Configuration](https://docs.sagepilot.ai/sdks/web/configuration.md) for every option.

* Call it once per page. Later calls are ignored and log a warning.
* If `key` is missing or not in the format `workspace_id:channel_id`, it logs an error and resolves without loading the widget. `open()` then returns `false`.
* If the channel cannot be loaded, the promise rejects.

## Opening and closing

### `open()`

Opens the chat. Returns `true` if the chat is open, including when it was already open. Returns `false` if the widget is not ready. Skips the welcome popup and the two-step intro card.

### `close()`

Closes the chat. Returns `true`, or `false` if the widget is not ready.

### `toggle()`

Opens the chat if it is closed, and closes it if it is open. Returns `true` when it opened the chat and `false` when it closed it. Call it only after the widget is ready.

### `isOpen()`

Returns `true` if the chat is currently open.

See [Open chat from your own button](https://docs.sagepilot.ai/sdks/web/opening-chat.md).

## Identity

### `identify(identity)`

Links the visitor to a customer. Accepts `user_id` (required), `email`, `name`, `phone`, `custom_properties`, and `user_hash`. Resolves to `{ success: true, customer }` or `{ success: false, error }`. Never rejects.

### `logout()`

Clears the customer identity from the widget and this browser. The chat resets to an anonymous session.

### `getIdentityState()`

Returns `identified`, `pending`, and `customer` synchronously.

### `onIdentify(callback)`

Calls `callback` immediately if the visitor is already identified, or when an in-progress `identify()` succeeds. Does nothing otherwise.

See [Identity](https://docs.sagepilot.ai/sdks/web/identity.md).

## Messages

### `setDraft(text)`

Puts `text` in the chat's message box without sending it. Resolves to a result with `status` `drafted`, `failed`, or `requires_input`.

### `sendMessage(text)`

Sends `text` as the visitor. Resolves to a result with `status` `sent`, `requires_input`, `failed`, or `unknown`. Never retry automatically.

See [Draft and send messages](https://docs.sagepilot.ai/sdks/web/sending-messages.md) for every status and code.

## Timing

| Situation | Behavior |
| - | - |
| Called before `init()` finishes | `open()`, `close()`, and `toggle()` do nothing, and `open()` and `close()` return `false`. `setDraft()` and `sendMessage()` resolve with `not_initialized`. Calls are not queued. |
| Chat not ready after 15 seconds | `setDraft()` and `sendMessage()` resolve with `not_ready`. |
| No result 60 seconds after sending | `sendMessage()` resolves with `unknown` and code `timeout`. |
| `identify()` or `logout()` in progress | `setDraft()` and `sendMessage()` resolve with `identity_pending`. |

## Web Push add-on

Install and import the optional browser Push API separately from the widget script:

```bash theme={null}
npm install @sagepilot-ai/web-push-addon
```

```ts theme={null}
import {
  SagepilotWebPush,
  SagepilotWebPushError,
  isWebPushSupported,
} from "@sagepilot-ai/web-push-addon";
```

Follow [Web Push integration](https://docs.sagepilot.ai/sdks/web/push-notifications.md) before using these methods. The guide covers the required worker asset, backend identity proof and consent flow.

### Constructor

```ts theme={null}
const push = new SagepilotWebPush({
  key: "workspace_id:push_channel_id",
  onError: (error) => console.error(error),
});
```

Construction does not register a worker or request notification permission.

| Config field | Type | Required | Description |
| - | - | - | - |
| `key` | `string` | Yes | Public `workspace_id:push_channel_id` integration key. |
| `host` | `string` | No | Sagepilot origin. Defaults to `https://app.sagepilot.ai`. Use another host only when Sagepilot provides one. |
| `onError` | `(error: unknown) => void` | No | Receives failures from automatic repair and analytics retries. |
| `storage` | Storage-compatible object | No | Injectable durable storage for restricted runtimes and tests. |
| `fetch` | `typeof fetch` | No | Injectable fetch implementation for restricted runtimes and tests. |

### Capability and lifecycle methods

| Method | Returns | Behavior |
| - | - | - |
| `isWebPushSupported()` | `boolean` | Checks the required secure-context, service-worker, Push, Notification and cryptographic capabilities without prompting. |
| `push.identify(identityToken)` | `Promise<void>` | Exchanges a backend-signed five-minute proof. It never prompts and repairs a previously granted eligible subscription. |
| `push.subscribe(options?)` | `Promise<RegistrationResult>` | Requests permission, registers the endpoint and enables the web preference. Call only from an explicit customer action. |
| `push.sync()` | `Promise<RegistrationResult>` | Reports and silently repairs the current granted subscription without prompting. |
| `push.getPreferences()` | `Promise<Preferences>` | Returns the identified customer's global and per-platform Push preferences. |
| `push.setPreferences(preferences)` | `Promise<Preferences>` | Saves explicit global, `web` or `app` notification preferences. |
| `push.flush()` | `Promise<void>` | Uploads retained signed observations and waits for completion. Normal uploads are automatic. |
| `push.unsubscribe()` | `Promise<void>` | Persists `web.enabled = false`, revokes this browser endpoint and disables automatic repair. |
| `push.logout()` | `Promise<void>` | Revokes this browser installation before clearing its in-memory customer session. It leaves category preferences unchanged. |
| `push.destroy()` | `void` | Removes listeners and in-memory state. It does not revoke the endpoint or change consent. |

`subscribe()` accepts one optional consent field:

```ts theme={null}
await push.subscribe({ marketingConsent: true });
```

Set `marketingConsent` only when the customer's action explicitly disclosed marketing notifications. Omitting it leaves the existing marketing preference unchanged.

Use stable, non-token customer IDs of 1–45 characters for new integrations. Existing longer IDs are lookup-only. Include backend-verified contacts for new identified customers; an ID-only proof can resolve a contactless customer and be rejected by the anonymous-push policy. See the [proof contract](https://docs.sagepilot.ai/sdks/web/push-notifications.md#3-generate-a-customer-identity-proof-on-your-backend).

The exchanged Push authorization lasts 24 hours. Call `identify()` with a fresh backend proof to renew it before expiry; the add-on does not fetch proofs for you. Stop renewal before logout or account changes.

### Registration result

`subscribe()` and `sync()` return:

```ts theme={null}
type SagepilotWebPushRegistrationResult = {
  permission: "default" | "granted" | "denied";
  status:
    | "registered"
    | "not_subscribed"
    | "permission_required"
    | "permission_denied";
  endpointId: string | null;
};
```

| Status | Meaning |
| - | - |
| `registered` | Permission is granted and Sagepilot has registered the browser endpoint. |
| `permission_required` | The customer has not decided. Show your own notification opt-in UI. |
| `permission_denied` | The browser blocks notifications for this origin. The add-on cannot override it. |
| `not_subscribed` | Permission is granted, but the customer previously removed this subscription. Require an explicit subscribe action. |

`registered` does not mean marketing consent is enabled or that a notification was delivered.

### Preferences

Supported preference keys are `enabled`, `marketing_enabled` and `support_enabled` at the global level or under `web` and `app` overrides:

```ts theme={null}
await push.setPreferences({
  web: {
    enabled: true,
    marketing_enabled: true,
    support_enabled: false,
  },
});
```

Omitted fields are preserved. Top-level `enabled: false` blocks all Push; `web.enabled: false` blocks Web Push. A web category override takes precedence over the matching global category. New SDK customers default to marketing disabled. Read the effective preferences before showing an enabled state; `subscribe({ marketingConsent: true })` does not override a global opt-out. These settings apply to the customer's devices in the selected scope.

### Errors

Operational failures are instances of `SagepilotWebPushError`:

```ts theme={null}
try {
  await push.sync();
} catch (error) {
  if (error instanceof SagepilotWebPushError) {
    console.error({
      code: error.code,
      status: error.status,
      message: error.message,
      retryAfterMs: error.retryAfterMs,
    });
  }
}
```

| Field | Description |
| - | - |
| `code` | Stable classification when available, such as `unsupported`, `invalid_config`, `network_error`, `worker_failed` or `session_changed`. |
| `status` | HTTP status when the failure came from Sagepilot. |
| `message` | Human-readable diagnostic. Do not branch application logic on message text. |
| `details` | Optional bounded API details. Do not expose them directly to customers. |
| `retryAfterMs` | Bounded retry hint when the server supplies `Retry-After`. |

Endpoint registration automatically retries transient network errors, `408`, `429` and `5xx` responses with bounded delays. Explicit opt-out, logout and customer-account changes are never retried as a new subscription without customer intent.


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