# Widgets

Two widgets ship with `saasco-sdk`, and neither needs its own embed. You turn each one on in the dashboard; the SDK checks on start-up and only downloads a widget your project actually has switched on. That single toggle governs every install, whether you loaded the SDK from npm or from a script tag.

## Support widget

An embeddable AI support agent. Customers talk to a streaming model that can call tools you configure in the dashboard; every message is persisted into your Saasco support inbox, and your team can take over at any point.

The widget renders in a frame served by Saasco rather than drawing into your page. Two things follow from that: your styles and the widget's can't collide, and the widget's own code never lands in your bundle.

### Before you embed

Add your site's origin (e.g. `https://example.com`) to the allowlist in **Support → Settings → Security**. Cross-origin requests from unlisted origins are rejected.

The allowlist controls where the widget may appear. It isn't what protects a conversation; each one carries its own secret token for that.

### Install

**With the analytics SDK**

Nothing extra. The tag you already have carries the project id, and the widget appears once you switch it on in the dashboard:

```html
<script
  src="https://www.saasco.com/sdk/saasco-sdk.js"
  data-projectId="YOUR_PROJECT_ID"
  async
></script>
```

`data-placeholder` and `data-base-url` pass through to the widget. Workspace branding (name, greeting, avatar) is configured in the dashboard, not here.

**Standalone loader**

If you don't use the analytics SDK, load the widget on its own. It gives you the same `window.SaascoSupport` API:

```html
<script
  src="https://www.saasco.com/sdk/saasco-support-loader.js"
  data-projectId="YOUR_PROJECT_ID"
  data-base-url="https://www.saasco.com"
  async
></script>
```

Without the analytics SDK nothing forwards identity for you, so call `window.SaascoSupport.identify(...)` yourself.

> There is no React component to import. However you load it, you drive the
> widget through `window.SaascoSupport`.

### Host API

The widget loads asynchronously, so `window.SaascoSupport` isn't there the instant your own script runs. Wait for it:

```js
function whenSupportReady(callback) {
  if (window.SaascoSupport) {
    callback();
    return;
  }
  const interval = setInterval(() => {
    if (window.SaascoSupport) {
      clearInterval(interval);
      callback();
    }
  }, 50);
}

whenSupportReady(() => {
  window.SaascoSupport.setStateSnapshot({ page: location.pathname });
  window.SaascoSupport.open();
});
```

| Method                                    | What it does                                                                                                                               |
| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `identify({ distinctId, email, traits })` | Unsigned CRM attributes. Extra properties go in the nested `traits` object, not on the root. `saasco.identify(...)` already forwards this. |
| `boot({ userJwt, distinctId, email })`    | Supply a [signed identity JWT](#verified-identity). Layers on top of `identify()`; it doesn't replace it.                                  |
| `update({ userJwt })`                     | Refresh the signed identity.                                                                                                               |
| `shutdown()`                              | Call on host logout. Clears the signed identity and the session.                                                                           |
| `setStateSnapshot(value)`                 | Host-only keys layered on top of the live context and appended to the agent's system prompt. Host keys win on conflict.                    |
| `registerTool({ name, execute })`         | Register a [client tool](#tools) the agent can call in your page.                                                                          |
| `open()` / `close()`                      | Drive the widget imperatively.                                                                                                             |

### Verified identity

`identify()` forwards **unsigned** attributes. That's fine for attaching a conversation to a contact, but it isn't proof of who the visitor is, since anyone can type an email into a page.

To let the agent trust a `distinctId` or `email` as a data-connector identifier, sign a short-lived JWT **on your backend** with the project's messenger secret (generate it in **Support → Settings → Security**) and pass it through `boot`:

```js
// on your backend, after auth (HS256 with the messenger secret):
//   jwt.sign({ user_id: user.id, email: user.email, exp }, MESSENGER_SECRET)

window.SaascoSupport.boot({ userJwt });
window.SaascoSupport.shutdown(); // on logout
```

> Never ship the messenger secret in client code. It signs identity claims, so a
> copy of it is a copy of every user.

With **Require verified identity** on, a chat that *claims* an identity without a valid token is rejected. Anonymous chat still works as before. For signed-in visitors it also means the open conversation is looked up on the server, so it survives a reload and follows them to another device.

### Tools

Tools are configured in **Support → Tools**. The agent builds its tool list server-side on every request, so a tampered client can't add or alter one.

- **Server tools** (`execution: server`) are a REST call: a name, a description, JSON Schema arguments, an HTTP method, an `https://` endpoint on a public host, and a mapping of each argument to path, query or body. The agent runs it itself and streams the result inline.
- **Host tools** (`execution: host`) let you author a stub in the dashboard so the agent advertises it, then handle the call in your page. A `registerTool({ name, execute })` handler runs like any other code you ship, so it can call your own signed-in API or change what's on screen; it has 15 seconds to answer. Point it at an endpoint instead and that must be a path on your own site (`/api/…`); full URLs are rejected here.
- **Destructive tools** (`destructive: true`) are always host-executed and paused behind an Approve/Reject card. A decline is reported to the model as `{ ok: false, error: "User declined" }`.

Some parameters are filled in from what Saasco already knows about the visitor rather than by the model: anything you passed to `identify`, the campaign and session details the SDK collects, the verified identity, and any keys you set with `setStateSnapshot`. A parameter bound to `firstName` fills itself once `saasco.identify(...)` has run. A parameter can read from the CRM record instead; you choose which, per parameter, in the dashboard.

The model's arguments are **not** validated server-side, so your endpoint must validate its own inputs.

Four platform tools are server-side and need no registration: `close_conversation`, `request_human_handoff` (when handoff notifications are configured), `understand_product` (knowledge-base search, when a help center exists) and `report_knowledge_gap`.

### Behaviour worth knowing

- New conversations ask for an email before the first message unless `identify` or a verified JWT already supplied one.
- Messages cap at 5,000 characters; visitors can attach up to 5 images per message, 6 MB each.
- The open conversation and the visitor's email are remembered by the widget itself, never stored on your page. Some browsers wall that storage off, which is what [verified identity](#verified-identity) works around by picking the conversation back up from the server instead.
- Human replies are polled every 5 seconds, with a `"{name} is typing…"` indicator while a teammate composes.
- **Human takeover:** once a teammate replies, or toggles the AI off in the inbox, the agent stops responding. The widget shows "Waiting for a teammate…", then `"{name} has joined the conversation"` above the first team message. Toggling the AI back on resumes streaming.

## Social proof

Notifications like "Someone from Berlin just signed up 2 hours ago", rendered from the `track` events you already send. There is no separate embed and no client-side registration; you author templates in **Social Proof → Templates**.

If you don't use the analytics SDK, drop the loader in directly:

```html
<script
  src="https://www.saasco.com/sdk/saasco-social-proof-loader.js"
  data-projectId="YOUR_PROJECT_ID"
  data-base-url="https://www.saasco.com"
  async
></script>
```

### Previewing it

Append these to any page that loads the SDK:

| Parameter                     | Effect                                                                                                                                              |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| `?saasco_notifications=test`  | Render one sample notification from the first template, with placeholder values, no tracking and no caps. Works even with the dashboard toggle off. |
| `?saasco_notifications=reset` | Clear shown-ids, session count, dismissal and the cached widget payload, then run the engine again.                                                 |
