# Website chat

## A chat bubble on your own website

Two lines on your page give every visitor a chat with one of your agents. The
reply appears word by word as it is written, and a visitor who comes back finds
the same chat. No server of yours is in the loop, and no secret is in the page.

That works because the page holds a **publishable key** of its own kind,
`pk_chat_…`: it works only from the websites you list, only for this one
website chat, and only within the caps you set. Anyone can read it in your
page source; that is expected.

## Make one

In the console, open **Website chat** (or Chats, then Website): pick the agent
that answers, list the websites it may run on, choose the look, choose who may
chat, set the caps, and save. The page then shows the key and the two lines to
paste.

From your server, a website chat is a chat channel of provider `web`:

```bash
curl -X POST "$DVAARIK_API/v2/chat-channels" \
  -H "X-Api-Key: $DVAARIK_API_KEY" -H "Content-Type: application/json" \
  -d '{
    "provider": "web",
    "name": "Shop chat",
    "agent_id": "<agent id>",
    "web": {
      "allowed_origins": ["https://www.example.com", "http://localhost:*"],
      "settings": { "title": "Ask us", "greeting": "Hi! How can I help?", "accent": "#0F766E", "identity": "optional" }
    }
  }'
```

The answer's `web.publishable_key` goes in your page, and `web.identity_secret`
(shown only in this answer and after a rotate) stays on your server. Change it
with `PATCH /v2/chat-channels/{channel_id}` and a `web` object (only what you
send changes; `settings` is replaced whole); turn it off with
`DELETE /v2/chat-channels/{channel_id}`, which also stops its key at once.
Each origin is `scheme://host[:port]` with no path; `http://localhost:*` and
`http://127.0.0.1:*` cover every local port. At most 20.

## Put it on your page

```html
<script src="https://developers.dvaarik.com/sdk/web/0.2.0/dvaarik-chat.global.js"></script>
<dvaarik-chat publishable-key="pk_chat_…"></dvaarik-chat>
```

The script is chat only, has no dependencies and asks nothing of the network
until the element is on the page; it makes no session and stores nothing until
the visitor opens the chat.

| Attribute | Meaning |
| --- | --- |
| `publishable-key` | `pk_chat_…` (required) |
| `user-token` | a signed-in visitor: a token your server signed (below); changing it changes who is chatting |
| `storage` | where the visitor's chat credential is kept: `local` (default), `session`, `none` |
| `hide-launcher` | no bubble: open the chat from your own button with `el.open()` |
| `open` | open the chat when the page loads |

Methods: `open()`, `close()`, `identify(token | null)`, `reset()` (a new
chat). Restyle it from your page with `--dvaarik-chat-font` and
`--dvaarik-chat-radius`, or `::part(launcher)`, `::part(panel)`,
`::part(log)`, `::part(send)`.

## How it looks

The title, greeting, colour (`#RRGGBB`), corner (`bottom-right` or
`bottom-left`), button text and an optional https avatar come from the website
chat's `settings`, so a change in the console reaches every page without a
deploy (browsers keep the look up to five minutes). The chat's own words come
in its `language` (English, Hindi, Telugu, Tamil, Kannada, Marathi, Bengali,
Gujarati, Malayalam, Arabic, Urdu; null means the agent's language), right to
left for Arabic and Urdu, and you can reword any of them in `labels`. The
greeting is drawn by the page: it is not a reply and costs nothing. Messages
are text only: nothing is ever read as HTML, and only `https://` addresses
become links.

## Who can chat: signed-in visitors

`settings.identity` is `optional` (anyone on an allowed website can chat) or
`required` (only visitors your server vouches for: the bubble shows only once
the page gives it a user token). `required` is the strongest guard against
abuse for a site with accounts.

A **user token** is a JWT your server signs with HS256 and the website chat's
identity secret (`wcs_…`). Claims:

| Claim | |
| --- | --- |
| `sub` | your user's id, 1 to 128 printable characters (required) |
| `exp` | when it stops working, in Unix seconds, at most 24 hours ahead (required) |
| `name` | what the agent and your Chats page call them, at most 120 characters |
| `variables` | values for the agent's declared variables, as strings |

The chat then belongs to that user (`external_id` `u:<sub>`) on every device,
and the newest token's `name` and `variables` are used. A page cannot send
variables of its own: only your server's signature can put words into the
agent's prompt. Never put the secret in a page or an app; if it leaks, rotate
it in the console or with `POST /v2/chat-channels/{channel_id}/identity-secret`
(the old one stops at once and the answer shows the new one once).

Sign it with what your language already has, no package needed:

```js
// Node: on your server only.
import { createHmac } from "node:crypto";

const part = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");

export function chatUserToken(user, secret) {
  const head = part({ alg: "HS256", typ: "JWT" });
  const body = part({ sub: String(user.id), name: user.name, exp: Math.floor(Date.now() / 1000) + 3600 });
  const signature = createHmac("sha256", secret).update(`${head}.${body}`).digest("base64url");
  return `${head}.${body}.${signature}`;
}
```

```python
# Python: on your server only.
import base64, hashlib, hmac, json, time

def _part(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()

def chat_user_token(user_id: str, name: str, secret: str) -> str:
    head = _part(json.dumps({"alg": "HS256", "typ": "JWT"}).encode())
    body = _part(json.dumps({"sub": user_id, "name": name, "exp": int(time.time()) + 3600}).encode())
    signature = _part(hmac.new(secret.encode(), f"{head}.{body}".encode(), hashlib.sha256).digest())
    return f"{head}.{body}.{signature}"
```

Render it into the page for a signed-in user:

```html
<dvaarik-chat publishable-key="pk_chat_…" user-token="<the token your server signed>"></dvaarik-chat>
```

## Limits and what it can cost

A key in a web page is public, so the caps are what a stranger with a copy of
your page could spend. Each is yours to set; past one the chat says it is busy
and nothing is spent.

| Field | Cap | Default | At most |
| --- | --- | --- | --- |
| `replies_per_minute` (on the website chat) | Replies a minute: For the whole website chat | 20 | 300 |
| `replies_per_day` (on the website chat) | Replies a day: A rolling 24 hours: this is the cost cap | 500 | 50,000 |
| `turns_per_hour` (on the website chat) | Replies an hour, per visitor: For one visitor | 30 | 300 |
| `web.concurrent_replies` | Replies being written at once: Across every visitor of this website chat | 3 | 20 |
| `web.sessions_per_minute` | New visitors a minute: New chats this website chat opens a minute | 20 | 120 |
| `web.sessions_per_ip_per_minute` | Opens a minute from one address: Chats one website and visitor address may open a minute | 5 | 60 |
| `web.messages_per_ip_per_minute` | Messages a minute from one address: Messages one visitor address may send a minute | 10 | 120 |

Every reply is charged like any chat reply, ₹0.05 or $0.0005, once it is written;
visitors' messages, the greeting and refused messages are free. Your own AI
account also bills the tokens of each reply. So the most a website chat can
cost in a rolling day is its `replies_per_day` times the reply price, plus your
AI account's charge for those replies. The first time the day cap refuses a
reply you get the `chat.channel.attention` webhook (`daily_limit_reached`).
A message is at most 2,000 characters, and a visitor waits for one reply before
sending the next.

## What is kept

In the visitor's browser: the chat credential only (`localStorage` key
`dvaarik-chat:<the key's last 12 characters>`, or `sessionStorage`, or nothing
with `storage="none"`), and only after they opened the chat. The 30-minute
session token stays in memory. On our side a website chat's conversation is
kept like every chat (see [Chat agents](/docs/chat-agents#how-long-messages-are-kept));
under zero retention its messages are kept only for the 24-hour reply window
and no visitor name is kept. A visitor's address is never stored.

## Content Security Policy

Nothing inline and nothing evaluated, so a strict policy needs only:

```text
script-src https://developers.dvaarik.com
connect-src https://api.developers.dvaarik.com
img-src <your avatar's host>
```

## Errors

A page is told only these codes, as `{"detail": {"code", "message"}}`
(`Retry-After` on 429 and 503):

| Code | Status | The visitor reads |
| --- | --- | --- |
| `invalid_key` | 401 | This chat is not set up correctly. |
| `origin_not_allowed` | 403 | This website is not allowed to use this chat. |
| `invalid_session` | 401 | This chat session is not valid. Open the chat again. |
| `session_expired` | 401 | This chat session has ended. Open the chat again. |
| `invalid_user` | 401 | The signed-in visitor could not be verified. |
| `identity_required` | 403 | Sign in to chat. |
| `invalid_request` | 422 | The message is empty or too long. |
| `reply_in_progress` | 409 | A reply is still being written. Send your next message after it. |
| `limited` | 429 | Too many messages right now. Try again in a moment. |
| `busy` | 429 or 503 | The chat is busy. Try again in a few seconds. |
| `temporarily_unavailable` | 503 | This chat is not available right now. |

While website chats are not open for your account, the chat-channel doors answer
409 `switched_off` "Website chat is not open yet." and the page reads
`temporarily_unavailable`. An empty wallet, a stopped account or an agent that
cannot chat read the same way: the page never learns why.

## Events

Website chats send the same `chat.*` webhooks as every channel, with
`channel: "web"` and the visitor's `external_id`: `v:<id>` for an anonymous
visitor, `u:<sub>` for a signed-in one. A tool webhook of a website chat's
agent carries `visitor: {external_id, verified}`.

## Build your own chat UI

The script's client drives everything without the element (with
`hide-launcher`, or without the element at all):

```js
const chat = new window.DvaarikChat({ publishableKey: "pk_chat_…" });
chat.on("message", (message) => render(message)); // added or changed (the same id replaces)
chat.on("delta", ({ message }) => render(message)); // the reply so far, while it is written
chat.on("error", (error) => show(error.code, error.message));
await chat.loadConfig(); // the look and the words
await chat.open(); // a session and the chat so far
await chat.send("When do you open on Saturday?");
```

`send()` resolves with the reply once it is written, and rejects (the message
was not taken) with the codes below. Or call the four public routes yourself (CORS from your allowed
websites only, no cookies):

| Route | Credential | What it does |
| --- | --- | --- |
| `GET /v2/web-chat/config?key=pk_chat_…` | the key in the query | the look and the words in the chat's language |
| `POST /v2/web-chat/sessions` | `X-Publishable-Key` | body `{visitor?, user_token?}`: a 30-minute session `token`, the visitor credential to keep, and the last 50 messages |
| `POST /v2/web-chat/messages` | `Authorization: Bearer <token>` | body `{text, client_message_id}` (a UUID): the reply streams back as server-sent events |
| `GET /v2/web-chat/messages` | `Authorization: Bearer <token>` | the chat so far (`limit` at most 50, `before`) |

The stream's events are `message.received` `{message, reply_id}`,
`reply.delta` `{reply_id, text}`, `reply.done` `{message, reply, duplicate,
truncated}` and `error` `{error: {code, message}, reply_id}` (`unknown_outcome`
or `unfinished`), with a `: keep-alive` comment every 15 seconds. Every refusal
comes before the first byte, as a status and a JSON body. If a stream drops,
send the same text with the same `client_message_id` once: a reply already
written comes back as it was and is never charged twice.

---

Source: https://developers.dvaarik.com/docs/web-chat · every page as one file: https://developers.dvaarik.com/docs.md
