@aliendesk/chat-sdk 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +2 -0
  2. package/USAGE.md +269 -0
  3. package/package.json +3 -2
package/README.md CHANGED
@@ -4,6 +4,8 @@ Build your own chat screen on [Alien Desk](https://aliendesk.io): the AI agent t
4
4
 
5
5
  Full guide: [Build your own chat](https://docs.aliendesk.io/guides/build-your-own-chat).
6
6
 
7
+ **Complete reference: [`USAGE.md`](USAGE.md)**, shipped in the package (`node_modules/@aliendesk/chat-sdk/USAGE.md`). It lists every option, method, event and type, with the rules that are easy to get wrong. AI coding agents: read it before writing code with this SDK.
8
+
7
9
  ## Install
8
10
 
9
11
  ```bash
package/USAGE.md ADDED
@@ -0,0 +1,269 @@
1
+ # @aliendesk/chat-sdk: complete usage guide
2
+
3
+ This file is the full reference for `@aliendesk/chat-sdk`, written so that a developer or an AI coding agent can build a working chat screen from it alone. The same content is on the docs site: <https://docs.aliendesk.io/guides/chat-sdk-reference>. Type definitions ship in `dist/*.d.ts`.
4
+
5
+ ## What it is
6
+
7
+ Alien Desk is an AI customer-support desk. Its AI agent answers from the brand's help center, can act inside the brand's own product for the signed-in user (through the product's MCP server, asking the user before any change), and hands the chat to the support team when needed. The team works these chats in the Alien Desk inbox.
8
+
9
+ This SDK is a thin client for the Alien Desk **Chat API**. It handles the session, sending, live events (Server-Sent Events), reconnecting and the user's tool token. **It draws nothing**: your app renders the messages.
10
+
11
+ Pick the right tool:
12
+
13
+ | You want | Use |
14
+ |---|---|
15
+ | A ready-made chat bubble or side panel | The Alien Desk widget (`loader.js`), not this SDK |
16
+ | Your own chat UI in a browser or app | **This SDK** with the brand's public key |
17
+ | To chat from your own server (a bot on another channel, a mobile backend) | The Chat API over HTTP with a secret key that has the `chat` scope: <https://docs.aliendesk.io/guides/chat-api-from-your-server>. This SDK does not take secret keys. |
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ npm install @aliendesk/chat-sdk
23
+ ```
24
+
25
+ ```js
26
+ import { createChat, ChatError } from '@aliendesk/chat-sdk';
27
+ ```
28
+
29
+ ES modules only. Works in browsers with `fetch` and `ReadableStream`, and in Node 18+. Without a bundler, load `<script src="https://widget.aliendesk.io/sdk.js"></script>`: it defines `window.AlienDeskChat` with the same exports (`AlienDeskChat.createChat`).
30
+
31
+ ## Before you write code
32
+
33
+ 1. **Public key.** The brand's key starts with `pk_`. It is in Alien Desk under Brand settings → Chat widget (the `data-brand` value of the widget snippet). It is safe in a page.
34
+ 2. **Allowed domains.** Every site the chat runs on must be listed in Brand settings → Chat widget → Allowed domains. A browser call from any other origin is refused with `403`. A brand with no allowed domains can't be used from a browser at all. Calls without an `Origin` header (Node, native apps) are not checked.
35
+ 3. **Signed-in users need a `userHash`**, computed on **your server**, never in the browser: HMAC-SHA256 of the user id with the brand's identity secret (Brand settings → Chat widget → Identity verification), as lowercase hex.
36
+
37
+ ```js
38
+ // Node, on your server
39
+ import { createHmac } from 'node:crypto';
40
+ const userHash = createHmac('sha256', process.env.ALIENDESK_IDENTITY_SECRET).update(String(user.id)).digest('hex');
41
+ ```
42
+
43
+ Optional `emailHash` = HMAC-SHA256 of `` `${userId}:${email}` `` with the same secret: the email is then trusted too.
44
+ 4. **Never put a secret API key (`adk_live_...`) in a page or an app.**
45
+
46
+ ## Quick start
47
+
48
+ ```js
49
+ import { createChat } from '@aliendesk/chat-sdk';
50
+
51
+ const chat = createChat({ key: 'pk_live_...' });
52
+
53
+ // Signed-in user (userHash from your server). For an anonymous visitor: await chat.start();
54
+ const session = await chat.identify({ userId: user.id, userHash, name: user.name, email: user.email });
55
+
56
+ // Carry on with the latest open chat, if there is one.
57
+ const open = session.conversations.find((c) => c.status !== 'closed');
58
+ if (open) render((await chat.open(open.id)).messages);
59
+
60
+ const byId = new Map();
61
+ const upsert = (m) => { byId.set(m.id, m); render([...byId.values()]); };
62
+
63
+ chat.on('message', upsert); // every new message, the user's own included
64
+ chat.on('message.updated', upsert); // a confirmation answered, feedback given
65
+ chat.on('delta', ({ text }) => showDraft(text)); // the AI's answer while it is written
66
+ chat.on('message', (m) => { if (m.kind === 'ai') hideDraft(); });
67
+ chat.on('sync', ({ messages }) => { byId.clear(); messages.forEach(upsert); }); // after a reconnect
68
+ chat.on('confirmation', ({ message }) => showConfirmCard(message.confirmation, (yes) => chat.confirm(yes)));
69
+ chat.on('error', (e) => console.warn('chat', e.code, e.message));
70
+
71
+ const { message } = await chat.send('Pause my Diwali campaign');
72
+ upsert(message);
73
+ ```
74
+
75
+ ### React
76
+
77
+ ```jsx
78
+ import { useEffect, useMemo, useState } from 'react';
79
+ import { createChat } from '@aliendesk/chat-sdk';
80
+
81
+ export function useAlienDeskChat({ publicKey, user }) {
82
+ const chat = useMemo(() => createChat({ key: publicKey }), [publicKey]); // one instance per key
83
+ const [messages, setMessages] = useState([]);
84
+ const [draft, setDraft] = useState('');
85
+
86
+ useEffect(() => {
87
+ const upsert = (m) => setMessages((list) => {
88
+ const i = list.findIndex((x) => x.id === m.id);
89
+ return i === -1 ? [...list, m] : list.map((x, j) => (j === i ? m : x));
90
+ });
91
+ const offs = [
92
+ chat.on('message', (m) => { upsert(m); if (m.kind === 'ai') setDraft(''); }),
93
+ chat.on('message.updated', upsert),
94
+ chat.on('delta', ({ text }) => setDraft(text)),
95
+ chat.on('sync', ({ messages }) => setMessages(messages)),
96
+ ];
97
+ (async () => {
98
+ const s = user ? await chat.identify(user) : await chat.start(); // user = { userId, userHash, name, email }
99
+ const open = s.conversations.find((c) => c.status !== 'closed');
100
+ if (open) setMessages((await chat.open(open.id)).messages);
101
+ })();
102
+ return () => { offs.forEach((off) => off()); chat.close(); };
103
+ }, [chat, user?.userId]);
104
+
105
+ return { chat, messages, draft, send: (text) => chat.send(text) };
106
+ }
107
+ ```
108
+
109
+ Render `message.text` as text (`{message.text}` in JSX, `textContent` in the DOM). **Never as HTML**: it comes from users, the team and the AI.
110
+
111
+ ## Lifecycle
112
+
113
+ 1. `createChat({ key })`: one instance per page (or per app). Nothing is sent yet.
114
+ 2. `identify(user)` for a signed-in user, or `start()` for an anonymous visitor. Both open or resume the session and start the live events. Any other call opens the session itself if needed.
115
+ 3. `open(id)` to show an existing chat, or just `send(text)`: with no open chat it starts one.
116
+ 4. Listen with `on(...)`.
117
+ 5. `signOut()` when the user signs out of your product. When another user signs in on the same device, call `identify()` with them: they get their own session.
118
+ 6. `close()` when the screen goes away (stops events; the session stays for next time).
119
+
120
+ The session token is kept in `localStorage` (key `aliendesk.chat.<publicKey>`) in browsers, in memory elsewhere, so a reload continues the same chats. `storage: null` keeps it in memory only.
121
+
122
+ ## API
123
+
124
+ ### `createChat(options)`
125
+
126
+ | Option | Type | Default | |
127
+ |---|---|---|---|
128
+ | `key` | `string` | required | The brand's public key (`pk_...`). |
129
+ | `apiUrl` | `string` | `https://app.aliendesk.io` | The Alien Desk app address. |
130
+ | `storage` | `{ get, set, remove } \| null` | `localStorage` in browsers, memory elsewhere | Where the session token is kept. `null`: memory only. |
131
+ | `stream` | `boolean` | `true` | Read live events. `false`: poll `open()` yourself. |
132
+ | `locale` | `string` | | The user's language for a new session (`en`, `hi-IN`). |
133
+ | `fetch` | `typeof fetch` | global `fetch` | Your own fetch (tests, old runtimes). |
134
+ | `retryDelaysMs` | `number[]` | `[1000, 2000, 5000, 10000, 30000]` | Waits before a reconnect or a send retry; the last one repeats. |
135
+
136
+ Returns a `Chat`.
137
+
138
+ ### Session
139
+
140
+ | Method | Returns | |
141
+ |---|---|---|
142
+ | `start()` | `Promise<ChatSession>` | Open or resume the session and read events. |
143
+ | `identify(user)` | `Promise<ChatSession>` | Sign the user in. `user`: `{ userId, userHash, emailHash?, name?, email?, phone?, attrs?, toolToken?, toolTokenExpiresAt? }`. Throws `ChatError` `bad_request` without `userId` and `userHash`. A wrong hash: `403`. |
144
+ | `signOut()` | `Promise<void>` | End the session, forget its token, close the stream. |
145
+ | `close()` | `void` | Stop events and the token timer. `start()` resumes. |
146
+ | `session` (getter) | `ChatSession \| null` | The current session. |
147
+ | `connection` (getter) | `'connecting' \| 'open' \| 'reconnecting' \| 'closed'` | Live events state. |
148
+
149
+ `ChatSession`: `{ sessionToken, stream, contact: { name, email, verified }, conversations: ChatConversation[] (newest first), brand: { name, logoUrl }, assistant: { name, avatarUrl }, team: { status: 'online' | 'away' | 'offline', hours }, toolTokenStored? }`.
150
+
151
+ ### Chats and messages
152
+
153
+ | Method | Returns | |
154
+ |---|---|---|
155
+ | `conversations()` | `Promise<ChatConversation[]>` | The user's recent chats, newest first (up to 10). |
156
+ | `open(conversationId)` | `Promise<{ conversation, messages }>` | Load a chat (messages oldest first, up to 200) and make it the one `send()` writes to. |
157
+ | `newConversation()` | `void` | The next `send()` starts a new chat. |
158
+ | `conversationId` (getter) | `string \| null` | The chat `send()` writes to. |
159
+ | `send(text, { conversationId?, clientMessageId? }?)` | `Promise<{ conversation, message, newConversation }>` | Send the user's message (1 to 4,000 characters). `message` is the user's own message; the answer arrives as events. `newConversation: true` when it started a chat (none open, or the open one was closed). |
160
+
161
+ The following act on the open chat, or on the chat id passed as the last argument:
162
+
163
+ | Method | Returns | |
164
+ |---|---|---|
165
+ | `confirm(yes)` | `Promise<void>` | Answer the AI's confirmation card. A second answer does nothing. |
166
+ | `askForPerson()` | `Promise<{ conversation, team: { status } }>` | Hand the chat to the team. If `conversation.awaitingEmail` is `true`, ask the user for an email and call `setEmail`. |
167
+ | `setEmail(email)` | `Promise<ChatConversation>` | Where replies go if the user leaves. |
168
+ | `end()` | `Promise<ChatConversation>` | End the chat. |
169
+ | `rate('good' \| 'poor', comment?)` | `Promise<ChatConversation>` | Rate it (when `ratingRequested`, or after it ended). |
170
+ | `markRead()` | `Promise<void>` | The user sees the latest replies; the team sees them as read. |
171
+ | `feedback(messageId, helpful)` | `Promise<void>` | Thumbs up or down on an AI answer. |
172
+
173
+ ### Your product (connected product)
174
+
175
+ | Method | |
176
+ |---|---|
177
+ | `identify({ ..., toolToken, toolTokenExpiresAt })` | Pass the user's short-lived token for your product's tools (minted by your server, ~15 minutes). Only accepted with a valid `userHash` in the same call. |
178
+ | `onTokenRequest(fn)` | `fn` returns `{ toolToken, toolTokenExpiresAt }` or the token string (sync or async), or `null` if the user is signed out. Called about a minute before expiry and when the AI finds the token expired. Errors are emitted as `error`, not thrown. |
179
+ | `setToolToken(token, expiresAt?)` | `Promise<boolean>`: pass a fresh token yourself. Needs a prior `identify()`. `false` when it was already expired. |
180
+ | `context(object \| null)` | `Promise<void>`: where the user is (`{ page: 'campaign', campaignId: 'c_42' }`). A hint only; never put secrets in it. |
181
+ | `clientTools(tools \| null)` | `Promise<void>`: page actions the AI may trigger: `[{ name, description, parameters? (JSON Schema) }]`. They arrive as `action` events. |
182
+
183
+ `expiresAt` / `toolTokenExpiresAt` accept an ISO date or Unix seconds or milliseconds.
184
+
185
+ ### Events: `chat.on(name, fn)` returns a function that stops listening
186
+
187
+ | Event | Payload | |
188
+ |---|---|---|
189
+ | `session` | `ChatSession` | A session opened (first call, `identify`, or a new one after the old ended). |
190
+ | `message` | `ChatMessage` | A new message, **including the user's own** (also returned by `send`): key your list by `id`. |
191
+ | `message.updated` | `ChatMessage` | A message changed (confirmation answered, feedback): replace it by `id`. |
192
+ | `conversation` | `ChatConversation` | Status, stage or assignee changed. |
193
+ | `delta` | `{ conversationId, text }` | The AI's answer so far (the full text so far, not a fragment). Replaced by the final `message`. |
194
+ | `step` | `{ conversationId, title, status: 'running' \| 'done' \| 'failed' }` | Something the AI does in your product ("List campaigns"). |
195
+ | `typing` | `{ conversationId, who: 'ai' \| 'agent', name, on }` | Someone is writing. |
196
+ | `confirmation` | `{ conversationId, message }` | The AI asks the user to confirm a change: show `message.confirmation`, then `confirm(true \| false)`. |
197
+ | `action` | `{ conversationId, name, args }` | One of your `clientTools` was triggered. Validate `args`. Fire and forget. |
198
+ | `sync` | `{ conversation, messages }` | After a reconnect: the open chat as it is now. Replace what you show. |
199
+ | `connection` | `'connecting' \| 'open' \| 'reconnecting' \| 'closed'` | |
200
+ | `event` | `ChatEvent` | Every raw stream event. |
201
+ | `error` | `ChatError` | A background failure (token request, stream). Calls you make throw instead. |
202
+
203
+ ### Types
204
+
205
+ `ChatMessage`:
206
+
207
+ | Field | |
208
+ |---|---|
209
+ | `id`, `conversationId` | |
210
+ | `kind` | `customer` (the user), `ai`, `agent` (a person on the team), `event` (handed over, assigned, solved: see `event.type`). |
211
+ | `author` | `{ type: 'contact' \| 'membership' \| 'ai' \| 'system', name }` |
212
+ | `text` | The message. AI answers may use simple Markdown (lists, links, bold): render it with a safe Markdown renderer or as plain text. |
213
+ | `steps` | `{ title, status }[]`: what the AI did in your product for this answer. Never arguments or results. |
214
+ | `confirmation` | `{ status, title, fields: { label, value }[] } \| null`. `title` is null for an action without a card (the text asks). |
215
+ | `suggestions` | Up to 3 short replies the user might send next: show them as buttons that call `send`. |
216
+ | `offerHuman` | The AI suggests talking to a person: show a button that calls `askForPerson()`. |
217
+ | `sources` | `{ title, url, articleId }[]`: help articles the answer came from. |
218
+ | `attachments` | `{ id, name, mime, size }[]` (downloading is not in the Chat API yet). |
219
+ | `feedback` | `{ helpful } \| null` |
220
+ | `event` | For `kind: 'event'`: `{ type, data }`. |
221
+ | `createdAt` | ISO date. |
222
+
223
+ Step and confirmation `status`: `done`, `failed`, `unknown`, `awaiting_confirmation`, `declined`, `expired`. **`unknown`** means the change was sent to the product and no answer came back: it may or may not have happened. Tell the user to check before trying again.
224
+
225
+ `ChatConversation`: `{ id, number, subject, status: 'open' | 'pending' | 'solved' | 'closed', stage: 'ai' | 'queued' | 'assigned', assignee: { name } | null, preview, unread, awaitingEmail, ratingRequested, csat: { label, submittedAt } | null, lastMessageAt, createdAt }`. `stage`: `ai` = the AI agent answers, `queued` = waiting for a person, `assigned` = a person has it.
226
+
227
+ ### Errors
228
+
229
+ Failed calls throw `ChatError` with `status` (HTTP status; `0` = no connection, or refused before sending), `code`, `message` and sometimes `fields` (validation errors per field).
230
+
231
+ | Status | Code | What to do |
232
+ |---|---|---|
233
+ | `400` | `bad_request` | Fix the input; see `fields`. |
234
+ | `401` | `unauthorized` | The SDK reopens the session and retries once by itself. |
235
+ | `403` | `forbidden` | Usually the page's origin is not in the brand's Allowed domains, or `userHash` is wrong. Read `message`. |
236
+ | `404` | `not_found` | Unknown chat or message id. |
237
+ | `409` | `in_progress` | The same message is still being sent. `send()` already retries this. |
238
+ | `429` | `rate_limited` | Too many calls: wait and retry. |
239
+ | `0` | various | Network down. `send()` retries with the same `clientMessageId`, so the message is never sent twice. |
240
+
241
+ ## Rules that are easy to get wrong
242
+
243
+ - Create **one** `Chat` per key and reuse it. Several instances each open their own event stream.
244
+ - `send()` returns the user's message **and** the `message` event delivers it too: upsert by `id`, never append blindly.
245
+ - `delta` carries the whole answer so far. Replace the draft, don't append. Drop the draft when the AI's `message` arrives.
246
+ - After `sync`, replace the visible messages: events may have been missed while offline.
247
+ - Call `identify()` with `userHash` on every page load of a signed-in user (not only at sign-in), and `signOut()` when they sign out. Otherwise the next user on the device could see their chats.
248
+ - When `onTokenRequest` is set, `identify()` must have been called on that page: the fresh token is sent with the last `userId` and `userHash`.
249
+ - Show the confirmation card only for `confirmation.status === 'awaiting_confirmation'`, and disable it after the first click.
250
+ - `context()` and `clientTools()` come from the browser: your server must still check every action against the user's own token.
251
+ - Never log the session token, the tool token or the identity secret.
252
+
253
+ ## Limits
254
+
255
+ | | |
256
+ |---|---|
257
+ | Message length | 4,000 characters |
258
+ | Calls per session | 120 a minute |
259
+ | Messages per session | 20 a minute |
260
+ | Live event streams per session | 5 (a sixth closes the oldest) |
261
+ | `context` | 2,000 characters of JSON |
262
+ | `clientTools` | 10 tools; `name` lower_snake_case up to 40 characters; `description` up to 300 |
263
+
264
+ ## Links
265
+
266
+ - Guide: <https://docs.aliendesk.io/guides/build-your-own-chat>
267
+ - Connect your product (tool tokens, MCP): <https://docs.aliendesk.io/guides/connect-your-product>
268
+ - Chat API reference: <https://docs.aliendesk.io/api-reference/chat/openChatSession>
269
+ - Source: <https://github.com/A2Dweb/aliendesk-chat-sdk>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aliendesk/chat-sdk",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Build your own chat on Alien Desk: the Chat API from a browser or Node, with live events.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://docs.aliendesk.io/guides/build-your-own-chat",
@@ -29,7 +29,8 @@
29
29
  }
30
30
  },
31
31
  "files": [
32
- "dist"
32
+ "dist",
33
+ "USAGE.md"
33
34
  ],
34
35
  "publishConfig": {
35
36
  "access": "public"