@ownhelp/widget 0.0.0-stage → 0.1.1
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.
- package/API_CONTRACT.md +199 -0
- package/LICENSE +21 -0
- package/README.md +110 -2
- package/dist/lib/index.js +725 -0
- package/dist/widget.js +190 -0
- package/package.json +60 -5
- package/types/index.d.ts +67 -0
package/API_CONTRACT.md
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
# Chat API Contract: `POST /api/chat`
|
|
2
|
+
|
|
3
|
+
This is the contract between the embeddable widget (`widget/`) and the Orchestration Gateway.
|
|
4
|
+
The real implementation is `gateway/src/routes/chat.js`. `widget/mock/mock_gateway.js` is an
|
|
5
|
+
executable reference mock (no retrieval, no generation, no database), and
|
|
6
|
+
`widget/tests/mock_gateway.test.js` checks the widget client against it. The mock does not
|
|
7
|
+
enforce every gateway rule (session id format, per-tenant origins, body size); the real gateway does.
|
|
8
|
+
|
|
9
|
+
## Request
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
POST /api/chat
|
|
13
|
+
Content-Type: application/json
|
|
14
|
+
Accept: text/event-stream, application/json
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
```json
|
|
18
|
+
{
|
|
19
|
+
"tenant_id": "example_tenant",
|
|
20
|
+
"message": "What is your return policy?",
|
|
21
|
+
"session_id": "6f1c0c5e-6a34-4f0a-9d53-1b0d2f2b7a10"
|
|
22
|
+
}
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
| Field | Type | Rules |
|
|
26
|
+
| :--- | :--- | :--- |
|
|
27
|
+
| `tenant_id` | string | Required. Must match a `businesses.tenant_id`. Used as the `$vectorSearch` pre-filter. |
|
|
28
|
+
| `message` | string | Required, non-empty, at most 2000 characters. |
|
|
29
|
+
| `session_id` | string | Required. 16 to 128 characters from `A-Za-z0-9_.:-` (a UUID qualifies). Generated and stored by the widget (`localStorage`, per tenant). Not a credential; the gateway keys conversation history on it. |
|
|
30
|
+
|
|
31
|
+
The body is limited to 16 KB. The request carries **no cookies and no `Authorization` header**. It is a
|
|
32
|
+
public, anonymous endpoint. The gateway answers CORS itself (`POST, OPTIONS`, `Content-Type` only, no
|
|
33
|
+
credentials) and checks the request `Origin` against the tenant's allowed origins.
|
|
34
|
+
|
|
35
|
+
## Success response: streaming (preferred)
|
|
36
|
+
|
|
37
|
+
`200 OK`, `Content-Type: text/event-stream`. Events, in this order:
|
|
38
|
+
|
|
39
|
+
| Order | Event | `data` payload | Notes |
|
|
40
|
+
| :--- | :--- | :--- | :--- |
|
|
41
|
+
| 1 | `token` | `{"text": "Items "}` | Zero or more. Text deltas; the widget concatenates them. |
|
|
42
|
+
| 2 | `done` | `{}` | Terminates a successful reply. May include `follow_up` after a saved escalation. |
|
|
43
|
+
| any | `error` | `{"code": "generation_failed", "message": "..."}` | Terminal. Used when a failure happens after the `200` has been sent. No `done` follows. Codes: `generation_failed` (the model failed or produced unusable output), `stream_interrupted` (the connection to the backend was cut mid-reply, or it ended without finishing), `timeout` (the overall time limit passed). |
|
|
44
|
+
|
|
45
|
+
If a human escalation could not be saved as a ticket, the gateway appends one last `token` event with a
|
|
46
|
+
short notice (to contact the business directly) before `done`, and `done` carries no `follow_up`.
|
|
47
|
+
|
|
48
|
+
The `message` text is for developers. The widget never shows it: it shows a fixed, safe sentence per `code`
|
|
49
|
+
(see `src/lib/messages.js`) and offers Retry only when resending can help.
|
|
50
|
+
|
|
51
|
+
The visitor receives the model's reply and, when available, public follow-up options. There is no `sources` event and the stream carries no
|
|
52
|
+
document ids, sections, scores, chunk text, confidence or action (see "What visitors never receive" below).
|
|
53
|
+
A widget that sees an unknown event, such as a legacy `sources` event from an older gateway, ignores it.
|
|
54
|
+
|
|
55
|
+
Wire example:
|
|
56
|
+
|
|
57
|
+
```
|
|
58
|
+
event: token
|
|
59
|
+
data: {"text":"Items returned "}
|
|
60
|
+
|
|
61
|
+
event: token
|
|
62
|
+
data: {"text":"within 30 days..."}
|
|
63
|
+
|
|
64
|
+
event: done
|
|
65
|
+
data: {}
|
|
66
|
+
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Required response headers: `Cache-Control: no-cache, no-transform` and `X-Accel-Buffering: no`
|
|
70
|
+
(so nginx and similar proxies do not buffer the stream). Heartbeat comment lines (`: ping`) are allowed.
|
|
71
|
+
|
|
72
|
+
The widget treats a stream that closes **without** `done` or `error` as an interrupted reply and offers Retry.
|
|
73
|
+
If the gateway goes silent for 30 seconds the widget aborts with a timeout.
|
|
74
|
+
|
|
75
|
+
## Success response: non-streaming fallback
|
|
76
|
+
|
|
77
|
+
If the request does not accept `text/event-stream`, the gateway returns one JSON body (the widget always
|
|
78
|
+
asks for SSE first). The widget handles either based on the response `Content-Type`. Because nothing has
|
|
79
|
+
been streamed, a generation failure or timeout in this mode is a plain `503 service_unavailable`
|
|
80
|
+
instead of an in-stream `error` event. The body may also carry `follow_up` (see below).
|
|
81
|
+
|
|
82
|
+
```json
|
|
83
|
+
{
|
|
84
|
+
"answer": "Items returned within 30 days are eligible for a full refund.",
|
|
85
|
+
"session_id": "6f1c0c5e-6a34-4f0a-9d53-1b0d2f2b7a10"
|
|
86
|
+
}
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## What visitors never receive
|
|
90
|
+
|
|
91
|
+
Retrieval details and the model's decision stay on the server. Neither the streaming nor the JSON response
|
|
92
|
+
includes: document ids, sections or scores, chunk text, embeddings, the model's confidence or cited sources,
|
|
93
|
+
or the raw action field. Follow-up availability is exposed only after a ticket is saved.
|
|
94
|
+
|
|
95
|
+
### Human escalation and email follow-up
|
|
96
|
+
|
|
97
|
+
When the model decides a question needs a person (`action: "escalate"`), the gateway saves the conversation
|
|
98
|
+
as a ticket in `ticket_logs`, in the schema the dashboard's review queue already reads:
|
|
99
|
+
|
|
100
|
+
- `status: "pending_review"`, `channel: "widget"`, `escalation_reason` (`not_in_docs` when no relevant
|
|
101
|
+
document was found, otherwise `docs_require_human`), and a `ticket_summary` digest.
|
|
102
|
+
- `messages[]`: the whole retained conversation (`customer` / `agent` roles with timestamps), including turns
|
|
103
|
+
that were answered normally.
|
|
104
|
+
- For the reviewer only: `retrieved_chunks` (`doc_id`, `section`, `score`; never chunk text),
|
|
105
|
+
`similarity_score`, `confidence` and `cited_sources`.
|
|
106
|
+
|
|
107
|
+
The visitor gets the normal reply. When the ticket save succeeds, the gateway can offer email follow-up. One ticket exists per
|
|
108
|
+
conversation: a further escalation updates it (and re-opens it if it was resolved) and keeps the admin's notes
|
|
109
|
+
and contact details. Ordinary answered conversations are not written to the database. If saving the ticket
|
|
110
|
+
fails, the visitor's reply is unaffected and the failure is logged.
|
|
111
|
+
|
|
112
|
+
## Error responses (before streaming starts)
|
|
113
|
+
|
|
114
|
+
JSON body, always this shape:
|
|
115
|
+
|
|
116
|
+
```json
|
|
117
|
+
{
|
|
118
|
+
"error": {
|
|
119
|
+
"code": "rate_limited",
|
|
120
|
+
"message": "Too many messages. Please wait a moment."
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
| Status | `code` | When |
|
|
126
|
+
| :--- | :--- | :--- |
|
|
127
|
+
| 400 | `invalid_request` | Missing or wrongly typed field, bad `session_id`, or a body that is not valid JSON or is too large. |
|
|
128
|
+
| 400 | `message_too_long` | `message` over 2000 characters. |
|
|
129
|
+
| 403 | `origin_not_allowed` | Request `Origin` is not on the tenant's allowed list. |
|
|
130
|
+
| 404 | `unknown_tenant` | `tenant_id` does not exist (or is not served by this deployment mode). |
|
|
131
|
+
| 405 | `method_not_allowed` | Not `POST` or `OPTIONS` (`Allow` header set). |
|
|
132
|
+
| 429 | `rate_limited` | Per-IP or per-session limit hit. Includes `Retry-After` (seconds). |
|
|
133
|
+
| 500 | `internal_error` | Unexpected gateway failure. |
|
|
134
|
+
| 503 | `service_unavailable` | Inference engine or vector store unreachable, or the backend failed before producing a reply. |
|
|
135
|
+
| 504 | `timeout` | The overall time limit passed before the first token. |
|
|
136
|
+
|
|
137
|
+
The gateway may start streaming (`200`) as soon as retrieval is done, before the first token; failures after
|
|
138
|
+
that point arrive as an `error` event instead. The widget displays fixed safe messages and never renders the
|
|
139
|
+
server error message.
|
|
140
|
+
|
|
141
|
+
## Conversation memory
|
|
142
|
+
|
|
143
|
+
The widget sends one `message` and a `session_id` per request. Multi-turn context is the gateway's job:
|
|
144
|
+
it keeps a bounded history keyed by tenant and `session_id`. The tenant's `agent_config` is applied
|
|
145
|
+
server-side; the widget never sends or sees it.
|
|
146
|
+
|
|
147
|
+
## Optional follow-up metadata and contact submission
|
|
148
|
+
|
|
149
|
+
Both SSE `done` data and JSON fallback may include:
|
|
150
|
+
|
|
151
|
+
```json
|
|
152
|
+
{
|
|
153
|
+
"follow_up": {
|
|
154
|
+
"available": true,
|
|
155
|
+
"token": "opaque-scoped-capability",
|
|
156
|
+
"contact_email": "support@example.test",
|
|
157
|
+
"contact_phone": "+1 555 123 4567"
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
Omit metadata for ordinary answers or when ticket persistence fails. The client requires
|
|
163
|
+
`available: true` and a non-empty token, returns it as `followUp`, and keeps the capability
|
|
164
|
+
in memory only. It never puts capabilities or visitor contact details in localStorage.
|
|
165
|
+
Phone/email links use validated configured data; they are not extracted from model prose.
|
|
166
|
+
The panel warns that email follow-up is not immediate and never promises a live transfer.
|
|
167
|
+
|
|
168
|
+
`POST /api/chat/contact` uses the same anonymous tenant-origin policy as chat:
|
|
169
|
+
|
|
170
|
+
```json
|
|
171
|
+
{
|
|
172
|
+
"tenant_id": "example_tenant",
|
|
173
|
+
"session_id": "visitor-session-id",
|
|
174
|
+
"follow_up_token": "opaque-scoped-capability",
|
|
175
|
+
"name": "Visitor",
|
|
176
|
+
"email": "visitor@example.test"
|
|
177
|
+
}
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
Return HTTP 200 with `{"status":"saved"}` only after details are persisted to the
|
|
181
|
+
existing ticket. This means saved for staff review; no email delivery or response time
|
|
182
|
+
is promised. First submission wins; resubmitting identical name and email is idempotent (`saved` again). Errors use the standard envelope:
|
|
183
|
+
|
|
184
|
+
| Status | `code` | When |
|
|
185
|
+
| :--- | :--- | :--- |
|
|
186
|
+
| 400 | `invalid_request` | Invalid conversation id, tenant, name (1 to 100 characters, no control characters) or email. |
|
|
187
|
+
| 403 | `origin_not_allowed` | `Origin` not on the tenant's allowed list. |
|
|
188
|
+
| 403 | `invalid_follow_up` | Capability token expired, invalid, or for another tenant or session. |
|
|
189
|
+
| 404 | `unknown_tenant` | Tenant does not exist. |
|
|
190
|
+
| 409 | `contact_already_submitted` | Different details were already saved, or the ticket is missing. |
|
|
191
|
+
| 429 | `rate_limited` | Limit hit; includes `Retry-After`. |
|
|
192
|
+
| 503 | `service_unavailable` | Persistence failed or timed out. |
|
|
193
|
+
|
|
194
|
+
The widget keeps the form available on errors and shows fixed visitor-safe wording.
|
|
195
|
+
|
|
196
|
+
New chat aborts outstanding replies and contact saves, ignores stale callbacks, clears
|
|
197
|
+
local messages and form data, and persists a new per-tenant session ID. Existing server
|
|
198
|
+
history and admin tickets are untouched. Changing tenant or gateway also invalidates
|
|
199
|
+
outstanding callbacks and clears the visible conversation.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Juan Cruz
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,111 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @ownhelp/widget
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
An embeddable chat widget for a self-hosted, multi-tenant support gateway. It talks only to
|
|
4
|
+
`POST {apiUrl}/api/chat` (and `/api/chat/contact`): it never touches a database and holds no secrets.
|
|
5
|
+
Visitors see the assistant's reply, never retrieved chunks or scores.
|
|
6
|
+
|
|
7
|
+
## Install: script tag
|
|
8
|
+
|
|
9
|
+
```html
|
|
10
|
+
<script src="https://support.example.com/widget.js"
|
|
11
|
+
data-tenant-id="your_tenant"
|
|
12
|
+
data-api-url="https://support.example.com"
|
|
13
|
+
data-title="Example Support"
|
|
14
|
+
data-greeting="Hi! Ask me anything."
|
|
15
|
+
data-position="right"
|
|
16
|
+
data-accent-color="#0b6e4f"
|
|
17
|
+
defer></script>
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
The script can come from your gateway (`/widget.js`) or a CDN. Pin an exact version on a CDN:
|
|
21
|
+
|
|
22
|
+
```html
|
|
23
|
+
<script src="https://cdn.jsdelivr.net/npm/@ownhelp/widget@0.1.1/dist/widget.js"
|
|
24
|
+
data-tenant-id="your_tenant"
|
|
25
|
+
data-api-url="https://support.example.com"
|
|
26
|
+
defer></script>
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
`data-api-url` is required unless the gateway itself serves the script: when omitted, the widget
|
|
30
|
+
uses the origin the script was loaded from.
|
|
31
|
+
|
|
32
|
+
| Attribute | Required | Default | Notes |
|
|
33
|
+
| :--- | :--- | :--- | :--- |
|
|
34
|
+
| `data-tenant-id` | yes | | Tenant to chat with. |
|
|
35
|
+
| `data-api-url` | when not served by the gateway | script origin | Gateway base URL. |
|
|
36
|
+
| `data-title` | no | `Support` | Header text. |
|
|
37
|
+
| `data-greeting` | no | `Hi! How can I help you today?` | First message. |
|
|
38
|
+
| `data-position` | no | `right` | `left` or `right`. |
|
|
39
|
+
| `data-accent-color` | no | `#1f6feb` | Any CSS colour. |
|
|
40
|
+
|
|
41
|
+
The widget renders inside a shadow root, so your page's CSS cannot affect it. The React component below is isolated the same way. Theme it with `accentColor` or the `--cw-*` custom properties, which inherit through the shadow boundary; page selectors cannot restyle it.
|
|
42
|
+
|
|
43
|
+
## Install: React component
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
npm install @ownhelp/widget
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
```jsx
|
|
50
|
+
import { ChatWidget } from "@ownhelp/widget";
|
|
51
|
+
|
|
52
|
+
export default function App() {
|
|
53
|
+
return <ChatWidget apiUrl="https://support.example.com" tenantId="your_tenant" accentColor="#0b6e4f" />;
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Props: `apiUrl` and `tenantId` (required), `title`, `greeting`, `position` (`"left"` or `"right"`),
|
|
58
|
+
`accentColor`, `defaultOpen` (start with the panel open) and `fetchImpl` (replace `fetch`, for tests
|
|
59
|
+
or a custom proxy). React 18+ is a peer dependency; styles are injected, so there is no CSS import.
|
|
60
|
+
The package also exports `streamChat`, `submitContact`, `ChatError`, `getSessionId` and
|
|
61
|
+
`newSessionId` for building your own UI, with TypeScript types included.
|
|
62
|
+
|
|
63
|
+
## Gateway requirement: allowed origins
|
|
64
|
+
|
|
65
|
+
The gateway only answers browsers whose origin is in that tenant's `widget_config.allowed_origins`
|
|
66
|
+
(exact origins, no wildcards), whichever host served the script. Otherwise it returns
|
|
67
|
+
`403 origin_not_allowed`. Add your site's origin (for example `https://shop.example.com`) to the
|
|
68
|
+
tenant before going live.
|
|
69
|
+
|
|
70
|
+
## Theming and behavior
|
|
71
|
+
|
|
72
|
+
- **Theming:** set `accentColor`, or override the `--cw-*` custom properties on `.cw-root`
|
|
73
|
+
(`--cw-accent`, `--cw-bg`, `--cw-surface`, `--cw-text`, `--cw-muted`, `--cw-border`, `--cw-error`).
|
|
74
|
+
A dark palette applies automatically with `prefers-color-scheme: dark`.
|
|
75
|
+
- **Session persistence:** each tenant gets a random session id in `localStorage` so a reload continues
|
|
76
|
+
the conversation on the server side. If storage is blocked (private window) it falls back to memory.
|
|
77
|
+
The id is not a credential.
|
|
78
|
+
- **Email follow-up:** after a human escalation is saved, the gateway can include `follow_up`
|
|
79
|
+
metadata. The widget then shows optional public contact links and a name and email form, sent to
|
|
80
|
+
`/api/chat/contact`. The UI confirms details were saved for staff review, not that an email went out.
|
|
81
|
+
The follow-up token is kept in memory only.
|
|
82
|
+
- **Start again:** the header's **New chat** button aborts in-flight requests, clears the form and
|
|
83
|
+
follow-up state, and stores a new session id. Server history and admin tickets are untouched.
|
|
84
|
+
- Stop and Retry buttons, and fixed visitor-safe error messages, are built in.
|
|
85
|
+
|
|
86
|
+
## Local development
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
npm install
|
|
90
|
+
npm run mock # mock gateway on :4100 (MOCK_PORT to change), see API_CONTRACT.md
|
|
91
|
+
npm run dev # Vite dev page on :5173
|
|
92
|
+
npm test # node --test tests/*.test.js
|
|
93
|
+
npm run build # dist/widget.js (script tag) and dist/lib/index.js (React import)
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
In the mock, a message containing `human` returns follow-up metadata, `nostream` the JSON fallback,
|
|
97
|
+
and `ratelimit`, `unknown`, `error`, `cutoff` and `slow` exercise failures (see the header of
|
|
98
|
+
`mock/mock_gateway.js`). The mock saves nothing; use fictional data.
|
|
99
|
+
|
|
100
|
+
## Publish checklist
|
|
101
|
+
|
|
102
|
+
1. Bump `version` in `package.json` and update the pinned CDN version above.
|
|
103
|
+
2. `npm test && npm run build` (also run by `prepublishOnly`).
|
|
104
|
+
3. `npm pack --dry-run`: only `dist`, `types`, `README.md`, `LICENSE` and `API_CONTRACT.md` should ship.
|
|
105
|
+
4. `npm publish --access public` (scoped packages are private by default, so the flag is required on
|
|
106
|
+
the first publish; `publishConfig` in `package.json` also sets it).
|
|
107
|
+
|
|
108
|
+
## Reference
|
|
109
|
+
|
|
110
|
+
- [API_CONTRACT.md](API_CONTRACT.md): the `POST /api/chat` request, SSE events, errors and follow-up.
|
|
111
|
+
- [LICENSE](LICENSE): MIT.
|