@meandr/chat-sdk 0.0.0-stage → 0.0.2
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/LICENSE +201 -0
- package/README.md +338 -2
- package/dist/api.d.ts +24 -0
- package/dist/client.d.ts +2 -0
- package/dist/errors.d.ts +18 -0
- package/dist/global.d.ts +3 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +1585 -0
- package/dist/index.js.map +7 -0
- package/dist/markdown.d.ts +17 -0
- package/dist/markdown.js +927 -0
- package/dist/markdown.js.map +7 -0
- package/dist/meandr-chat.js +11 -0
- package/dist/meandr-chat.js.map +7 -0
- package/dist/sse.d.ts +17 -0
- package/dist/token.d.ts +26 -0
- package/dist/types.d.ts +127 -0
- package/package.json +53 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Meandr, Inc.
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,339 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @meandr/chat-sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The JavaScript client for Meandr Chat. It opens the visitor's session, sends their messages and streams the answers,
|
|
4
|
+
which come from a model that uses your workspace's tools. It has no dependencies, and draws nothing: your page renders
|
|
5
|
+
its state. `@meandr/chat-sdk/markdown` renders the answers' Markdown safely.
|
|
6
|
+
|
|
7
|
+
It speaks Meandr Chat's API v1, served at your workspace's URL.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm install @meandr/chat-sdk
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Or load the script file, which defines `window.MeandrChat`:
|
|
16
|
+
|
|
17
|
+
```html
|
|
18
|
+
<script src="https://cdn.jsdelivr.net/npm/@meandr/chat-sdk@0.0.1/dist/meandr-chat.js"
|
|
19
|
+
integrity="sha384-…" crossorigin="anonymous"></script>
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
The script runs with your page's rights, so pin the version and keep its `integrity` hash: each release's notes on
|
|
23
|
+
GitHub give the whole tag.
|
|
24
|
+
|
|
25
|
+
## Use
|
|
26
|
+
|
|
27
|
+
```js
|
|
28
|
+
import { createChat } from "@meandr/chat-sdk";
|
|
29
|
+
|
|
30
|
+
const chat = createChat({
|
|
31
|
+
url: "https://calm-otter.meandr.io", // your workspace's URL
|
|
32
|
+
tokenUrl: "/chat_token", // or token, or getToken: who your user is
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
chat.subscribe(render); // render(state) now and on every change
|
|
36
|
+
|
|
37
|
+
launcher.onclick = () => chat.open(); // when the visitor shows interest
|
|
38
|
+
const result = await chat.send("Where is my order?");
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
The client does nothing until it's used, so create it with the page: until then it sends nothing, loads nothing and
|
|
42
|
+
leaves nothing behind. Create one client per page, not one per component render. It activates in one of three ways:
|
|
43
|
+
|
|
44
|
+
- **`open()`**, when the visitor shows interest: opens the chat, or starts typing. It loads their latest conversation.
|
|
45
|
+
- **`send(text)`** opens by itself.
|
|
46
|
+
- **`start()`** has the assistant speak first, such as a greeting or a summary of what needs the visitor's attention.
|
|
47
|
+
What it does is the chat's own start instructions, set in its settings (`CHAT_START_PROMPT`), so a page or a visitor
|
|
48
|
+
can't supply them; the visitor sees only the answer. Without them, it's refused (`start_not_allowed`). With no
|
|
49
|
+
conversation shown, after `newConversation()` say, it speaks in a new one.
|
|
50
|
+
|
|
51
|
+
## Who the user is
|
|
52
|
+
|
|
53
|
+
Give the client one way to get your user's token. A token is a JWT your backend signs with the chat's **Session
|
|
54
|
+
signing secret**. See the help center's "Sign your users in to Meandr Chat".
|
|
55
|
+
|
|
56
|
+
| Option | For | The client |
|
|
57
|
+
|---|---|---|
|
|
58
|
+
| `token` | pages your server builds: it writes the token in, or `null` when nobody is signed in | uses it as it is. It can't renew it: when it expires, the client asks for a reload (`token_expired`) |
|
|
59
|
+
| `tokenUrl` | sites that know their user by a cookie | sends `GET` with your site's cookies and reads `{"token": "…"}`. A 401, a 403 or `{"token": null}` means nobody is signed in |
|
|
60
|
+
| `getToken` | sites whose requests need more than a cookie, such as a bearer token kept in JavaScript | calls `getToken({ expired, signal })`, which returns the token, or `null` when nobody is signed in. `expired` is true when the chat refused the last token as expired, so skip any cache of yours |
|
|
61
|
+
| none | sites without sign-in, or whose server forwards the chat (below) | resumes the browser's session, whoever's it is, or starts an anonymous one |
|
|
62
|
+
|
|
63
|
+
On a site with sign-in, every page that shows the chat must say who is signed in, `null` included. A page that says
|
|
64
|
+
nobody is signed in ends a signed-in session the browser still holds, so the next visitor of a shared computer never
|
|
65
|
+
inherits it. A page that gives no way resumes it.
|
|
66
|
+
|
|
67
|
+
- **Failures:** any other failure of `tokenUrl` or `getToken`, such as a 500, a network error or a function that throws,
|
|
68
|
+
is an error to show and retry (`token_failed`), never a sign-out.
|
|
69
|
+
- **Where tokens go:** a token goes only to the chat its `aud` claim names, or to your page's own origin.
|
|
70
|
+
- **Memory only:** the client keeps tokens in memory, never in storage, the state or an error. The session lives in the
|
|
71
|
+
chat's own cookie, which no script can read.
|
|
72
|
+
- **Your token address:** answer `Cache-Control: no-store`, sign tokens that expire within minutes, and answer 401
|
|
73
|
+
rather than redirecting to a sign-in page. It's best on your page's own origin; on another, it needs CORS with
|
|
74
|
+
credentials for your page's origin.
|
|
75
|
+
|
|
76
|
+
## Options
|
|
77
|
+
|
|
78
|
+
| Option | |
|
|
79
|
+
|---|---|
|
|
80
|
+
| `url` | required: your workspace's URL, `https://<slug>.meandr.io`, or your own address when your server forwards the chat |
|
|
81
|
+
| `token` | `string \| null` |
|
|
82
|
+
| `tokenUrl` | `string`: an address, absolute or relative to the page |
|
|
83
|
+
| `getToken` | `({ expired, signal }) => string \| null \| Promise<string \| null>` |
|
|
84
|
+
| `fetch` | your own `fetch`, for tests or a wrapper. Add no headers: the chat's CORS allows only `Authorization` and `Content-Type`, so a tracing header such as `traceparent` fails every request |
|
|
85
|
+
| `context` | `() => PageContext \| undefined \| Promise<PageContext \| undefined>`: what your page tells the model of itself, read at each `send()` and `start()`: see [Page context](#page-context) |
|
|
86
|
+
|
|
87
|
+
An option the client doesn't know, or a token option set to `undefined`, is an error, so a typo or a missing value
|
|
88
|
+
can't silently resume someone's session.
|
|
89
|
+
|
|
90
|
+
## The client
|
|
91
|
+
|
|
92
|
+
| Member | |
|
|
93
|
+
|---|---|
|
|
94
|
+
| `getState()` | the current state, below |
|
|
95
|
+
| `subscribe(listener)` | calls `listener(state)` now and on every change; returns the function that unsubscribes |
|
|
96
|
+
| `open()` | opens the session: call it when the visitor shows interest. Calling it again while open does nothing. Resolves with the state once it opened, or failed for a reason waiting won't fix: see `status` and `error` |
|
|
97
|
+
| `send(text, { files })` | sends the message and streams the answer into the state. `files` are those `attach` gave, as ChatFiles or ids; with any, `text` may be `""`. Resolves with `{ ok: true, message, stop }`, the stored answer, or `{ ok: false, error }` |
|
|
98
|
+
| `attach(file, { name, onProgress, signal })` | uploads a `File` or `Blob` for a message of the visitor's within the hour, opening the session if need be: see [Files](#files). `name` is the file's own unless given, else `"file"`; `onProgress(sent, total)` follows its bytes; `signal` cancels it. Resolves with `{ ok: true, file }`, a ChatFile, or `{ ok: false, error }`, and changes nothing in the state |
|
|
99
|
+
| `readFile(file, { signal })` | fetches a file the visitor attached, by its ChatFile or id, with the session's credentials, opening the session if need be. Resolves with `{ ok: true, blob }` or `{ ok: false, error }` |
|
|
100
|
+
| `start()` | has the assistant speak first, as the chat's start instructions say, and streams the answer: in the user's latest conversation, usually the one shown, or a new one when none is shown or the chat is set so. Resolves as `send` does |
|
|
101
|
+
| `newConversation()` | forgets the current conversation: the next message, or `start()`, starts a new one |
|
|
102
|
+
| `reopen({ token })` | the user changed without a page load: signed in, signed out or switched team. Forgets everything shown and, if the chat was open, opens it again. Pass `token` when you give `token` |
|
|
103
|
+
| `signOut()` | ends the session and forgets the user, even if the page never showed the chat. Call it from your sign-out and await it before you navigate: it settles within three seconds, and never rejects |
|
|
104
|
+
| `destroy()` | stops everything this client does; it sends nothing more |
|
|
105
|
+
|
|
106
|
+
No member rejects for a chat failure: the result and the state carry it. Members work passed around on their own, as
|
|
107
|
+
in `onClick={chat.newConversation}` or `onFocus={chat.open}`; `send`, `attach`, `readFile` and `reopen` take arguments,
|
|
108
|
+
so call those yourself rather than handing them an event.
|
|
109
|
+
|
|
110
|
+
## The state
|
|
111
|
+
|
|
112
|
+
| Field | |
|
|
113
|
+
|---|---|
|
|
114
|
+
| `status` | `"idle"` before opening, `"opening"`, `"ready"`, or `"error"` when opening failed (`error` says why) |
|
|
115
|
+
| `anonymous` | whether the session is an anonymous visitor's; `null` before opening |
|
|
116
|
+
| `conversation` | `{ id, createdAt, updatedAt }`, or `null` before the first message |
|
|
117
|
+
| `messages` | the conversation's stored messages, oldest first: `{ id, role, text, tools?, toolTitles?, files?, createdAt }`. `tools` names the tools the answer used, and `toolTitles`, with it, gives each one's title by name, its name where the chat knows none; `files` are the ChatFiles the visitor attached |
|
|
118
|
+
| `outgoing` | the text of the message being sent, `""` with files alone, until the page shows it stored. With `error` set, it may not have reached the chat: offer to send it again, with its files, which never stores it twice |
|
|
119
|
+
| `answer` | the answer being written in this page: `{ text, tools: [{ name, status, title }] }`, or `null`. Show a tool's `title`: its name when the chat knows none |
|
|
120
|
+
| `answering` | an answer is being written in this conversation: in this page, or one the page lost or a previous page left running |
|
|
121
|
+
| `waiting` | `{ code, until }` while the client waits by itself, such as `rate_limited`, or `null`. `until` is a time in milliseconds, as from `Date.now()` |
|
|
122
|
+
| `stop` | why the last answer ended: `"end"`, `"max_tokens"` (cut short), `"refusal"` or `"paused"`; `null` when unknown |
|
|
123
|
+
| `error` | the last failure, until the next action |
|
|
124
|
+
| `files` | what the chat takes, as its session says: `{ types, maxBytes, perMessage }`, the media types, a file's most bytes and a message's most files. `null` before opening and while it takes no file: offer attaching only when it isn't `null` |
|
|
125
|
+
|
|
126
|
+
Show `messages`, then `outgoing`, then `answer`. Disable sending while `answering` or `status` is `"opening"`. An
|
|
127
|
+
assistant's `text` is Markdown from a model: render it with `@meandr/chat-sdk/markdown`, or another renderer that
|
|
128
|
+
never passes raw HTML through. A user's text is plain text.
|
|
129
|
+
|
|
130
|
+
The state is replaced, never changed in place. Messages that didn't change keep their objects, and so does `files`.
|
|
131
|
+
|
|
132
|
+
## Files
|
|
133
|
+
|
|
134
|
+
Where the chat's settings take files (`CHAT_ATTACHMENTS`), a visitor may attach them to a message for the model to
|
|
135
|
+
read: images (PNG, JPEG, WebP, GIF), PDFs, and text (plain, Markdown, CSV). They never reach your workspace's tools.
|
|
136
|
+
|
|
137
|
+
```js
|
|
138
|
+
const { types } = state.files; // offer attaching only while state.files isn't null
|
|
139
|
+
input.accept = types.concat(types.includes("text/plain") ? [".txt", ".md", ".csv"] : []).join(",");
|
|
140
|
+
|
|
141
|
+
const files = []; // the message's, as the visitor picks them
|
|
142
|
+
const picked = await chat.attach(input.files[0], { onProgress: (sent, total) => (bar.value = sent / total) });
|
|
143
|
+
if (picked.ok) files.push(picked.file); // or picked.error, such as unsupported_type
|
|
144
|
+
await chat.send(text, { files }); // once every upload is in; text may be ""
|
|
145
|
+
|
|
146
|
+
const read = await chat.readFile(message.files[0]);
|
|
147
|
+
if (read.ok) img.src = URL.createObjectURL(read.blob);
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
- **Offer attaching only while the state's `files` isn't `null`.** Its `types` can be your `<input>`'s `accept`:
|
|
151
|
+
browsers often give Markdown and CSV files no type, so add `.txt`, `.md` and `.csv` when it lists `text/plain`, which
|
|
152
|
+
the chat takes with the other two. A message takes at most `perMessage` files.
|
|
153
|
+
- **Upload each file as it's picked**, showing its progress, and send the message once all are in. The chat deletes a
|
|
154
|
+
file no message takes within an hour, and a message takes each file once.
|
|
155
|
+
- **A ChatFile** is `{ id, name, type, size, createdAt }`: its name as the chat keeps it, its media type as the chat
|
|
156
|
+
reads it from its bytes, and its size in bytes.
|
|
157
|
+
- **Progress** comes from `XMLHttpRequest`, since `fetch` reports none: with `onProgress`, the upload doesn't go through
|
|
158
|
+
a `fetch` you gave.
|
|
159
|
+
- **Refused before sending,** with status 0, since a browser may see a refusal that comes mid-upload as a network
|
|
160
|
+
error: a file past `maxBytes` (`too_large`), and any file once a session says the chat takes none (`attachments_off`).
|
|
161
|
+
Until a session says, or from a chat that doesn't, a file past 10 MiB, which no chat takes, is refused the same way.
|
|
162
|
+
- **Showing a file:** `readFile` fetches it with the session's cookie or token, so make an object URL of its blob: an
|
|
163
|
+
`<img>` pointing at the chat can't carry the token. The blob keeps an image's type; anything else is
|
|
164
|
+
`application/octet-stream`, a file to save rather than one the browser renders. Files already sent stay readable
|
|
165
|
+
while the chat takes no new ones.
|
|
166
|
+
|
|
167
|
+
## Page context
|
|
168
|
+
|
|
169
|
+
Each message and start can tell the model what the visitor's page shows, so "this order" or "the drawer I have open"
|
|
170
|
+
means something to it. The `context` option is read at each `send()` and `start()`, so it's always the current view:
|
|
171
|
+
|
|
172
|
+
```js
|
|
173
|
+
const chat = createChat({
|
|
174
|
+
url: "https://calm-otter.meandr.io",
|
|
175
|
+
tokenUrl: "/chat_token",
|
|
176
|
+
context: () => ({
|
|
177
|
+
url: location.origin + location.pathname, // the query and hash can carry tokens
|
|
178
|
+
title: document.title,
|
|
179
|
+
view: { section: "Orders", drawer: { open: true, order: "A-1042", tab: "Refunds" } },
|
|
180
|
+
}),
|
|
181
|
+
});
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
The chat gets, beside the message:
|
|
185
|
+
|
|
186
|
+
```json
|
|
187
|
+
{"timezone":"Europe/Tallinn","url":"https://console.shop.example/orders","title":"Orders · Console","view":{"section":"Orders","drawer":{"open":true,"order":"A-1042","tab":"Refunds"}}}
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
- **Known keys,** all optional: `url` (at most 2048 bytes), `title` (512) and `timezone` (an IANA name, 64). Any other
|
|
191
|
+
key goes as you give it.
|
|
192
|
+
- **The browser's time zone** goes by default, under what the option gives, so the model knows the visitor's local
|
|
193
|
+
time: give `timezone` to name another, or `timezone: undefined` to send none. Without the option, every message and
|
|
194
|
+
start carries the time zone alone.
|
|
195
|
+
- **Send only what you mean to.** The model reads it as what the page reports, information rather than instructions,
|
|
196
|
+
and the chat stores it with the message. URLs can carry tokens, such as a reset link's or a sign-in code:
|
|
197
|
+
`location.origin + location.pathname` leaves out the query and the hash.
|
|
198
|
+
- **The visitor's browser sends it,** so a visitor can change it, fooling only their own conversation: never let it
|
|
199
|
+
decide what a user may do. Facts your backend vouches for, such as the user's name, go in the token's `profile`
|
|
200
|
+
claim instead.
|
|
201
|
+
- **Never at the message's cost:** past the chat's limit (8 KiB by default, as its session says), with a `url`,
|
|
202
|
+
`title` or `timezone` the chat would refuse, or when the option throws, gives no object or takes over 5 s, the
|
|
203
|
+
message goes without the page's part, keeping the time zone, and the console warns once for each reason. A chat
|
|
204
|
+
older than page context, whose session says no limit, gets the time zone alone.
|
|
205
|
+
|
|
206
|
+
## Errors
|
|
207
|
+
|
|
208
|
+
A `ChatError` has a `code`, the HTTP `status` (0 when there was no answer), `retryAfter` in seconds when the chat said
|
|
209
|
+
when to try again, `partial` when an answer failed after storing part of it, and `retryable`, whether trying again may
|
|
210
|
+
work. `isChatError(e)` recognizes one even from another copy of the SDK.
|
|
211
|
+
|
|
212
|
+
Show your own words for the code:
|
|
213
|
+
|
|
214
|
+
| `code` | Suggested words |
|
|
215
|
+
|---|---|
|
|
216
|
+
| `unauthorized` | Sign in to chat. (Nobody is signed in and the chat takes no anonymous visitors, or the token isn't valid.) |
|
|
217
|
+
| `token_expired` | Your session has expired. Reload the page. |
|
|
218
|
+
| `session_expired` | Your session has ended. |
|
|
219
|
+
| `token_failed` | We couldn't check who you are. Try again. |
|
|
220
|
+
| `origin_not_allowed`, `origin_required` | The chat isn't available on this site. (The error's message names the site.) |
|
|
221
|
+
| `workspace_not_available`, `not_connected` | The chat isn't available right now. |
|
|
222
|
+
| `start_not_allowed` | (nothing: the chat isn't set to speak first) |
|
|
223
|
+
| `attachments_off` | This chat doesn't take files. |
|
|
224
|
+
| `unsupported_type` | That kind of file can't be attached. |
|
|
225
|
+
| `storage_full` | You can't attach more files for now. (The visitor's files, those in conversations included, fill the space the chat allows.) |
|
|
226
|
+
| `not_found` | This conversation is gone. (From `readFile`: That file is gone.) |
|
|
227
|
+
| `busy` | Still answering your previous message. |
|
|
228
|
+
| `too_large` | That message is too long. (From `attach`: That file is too large.) |
|
|
229
|
+
| `rate_limited` | You're sending messages too fast. Try again in a moment. |
|
|
230
|
+
| `overloaded` | The chat is busy. Try again in a moment. (The chat's machine is short of memory.) |
|
|
231
|
+
| `model_busy` | The assistant is busy. Try again in a moment. |
|
|
232
|
+
| `interrupted`, `timeout`, `unavailable`, `no_answer` | The answer failed. Try again. |
|
|
233
|
+
| `network` | We couldn't reach the chat. |
|
|
234
|
+
| `aborted` | (nothing: your page cut the message short) |
|
|
235
|
+
| `bad_request`, `internal`, `protocol` | Something went wrong. Try again. |
|
|
236
|
+
|
|
237
|
+
Codes the client doesn't know may come: show a general error for those.
|
|
238
|
+
|
|
239
|
+
## What the client does by itself
|
|
240
|
+
|
|
241
|
+
- **Opening:** with a token, the browser's session resumes if it's this user's, or a new one starts. When the page says
|
|
242
|
+
nobody is signed in, the client asks whether the browser holds a signed-in session, ends it if so, then opens.
|
|
243
|
+
- **Browsers that don't keep the chat's cookie** (Safari before 26.2, for one): the client notices after opening, then
|
|
244
|
+
sends the token with every request, or, for an anonymous visitor, the session token the chat gives it.
|
|
245
|
+
- **An expired token:** with `tokenUrl` or `getToken`, it gets a new one and tries again, once.
|
|
246
|
+
- **An ended session:** it opens one again and sends the message once more. If the session it reopens is someone
|
|
247
|
+
else's, it wipes what the page shows instead, the unsent message included.
|
|
248
|
+
- **Opening never gives up** while the chat can't be reached or isn't serving yet, as while it restarts after a
|
|
249
|
+
settings change: it tries again briskly through the first minute, then every 15 to 30 s, until the chat answers or
|
|
250
|
+
the page leaves. `waiting` says so meanwhile, so the page never needs a reload, and a `send` or `start` called
|
|
251
|
+
meanwhile waits with it.
|
|
252
|
+
- **Waiting:** it waits as long as the chat says, up to a minute, when the visitor writes too fast or the chat's
|
|
253
|
+
machine is short of memory, and up to two minutes when the user's previous answer is still running, in another tab
|
|
254
|
+
perhaps. Past the answers the chat writes at once, an answer waits its turn on the open stream, so nothing is
|
|
255
|
+
refused for it.
|
|
256
|
+
- **Nothing twice:** it tries a message again only when the chat refused it before storing it. When the connection
|
|
257
|
+
drops or the chat fails while sending, it looks for the message in the conversation before saying it failed. A
|
|
258
|
+
start that fails with `network` may have begun, so calling it again can have the assistant speak twice.
|
|
259
|
+
- **Files:** an upload the chat refused before keeping it is tried again as a message is: an ended session is opened
|
|
260
|
+
again once, and it waits up to a minute as the chat says. One whose answer was lost, such as with `network`, isn't,
|
|
261
|
+
since the chat may have kept it: attach it again. An upload is given up on when it stops moving for 30 s, or, without
|
|
262
|
+
`onProgress`, when no answer starts within 30 s plus its size's time at 32 KB/s.
|
|
263
|
+
- **A lost stream:** the answer runs on and is stored. The client asks for the conversation every few seconds, for up
|
|
264
|
+
to ten minutes, until the answer ends, as it does when it opens on an answer a previous page left running. An answer
|
|
265
|
+
still waiting its turn when its stream closed was dropped: that's `no_answer`, and sending again stores the message
|
|
266
|
+
a second time.
|
|
267
|
+
|
|
268
|
+
## Frameworks
|
|
269
|
+
|
|
270
|
+
React:
|
|
271
|
+
|
|
272
|
+
```jsx
|
|
273
|
+
const chat = createChat({ url, tokenUrl: "/chat_token" }); // once, outside components
|
|
274
|
+
|
|
275
|
+
function Chat() {
|
|
276
|
+
const state = useSyncExternalStore(chat.subscribe, chat.getState, chat.getState);
|
|
277
|
+
return <ChatPanel state={state} onOpen={chat.open} onSend={(text) => chat.send(text)} />;
|
|
278
|
+
}
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
A dashboard that wants the assistant to speak first calls `chat.start()` where it shows the chat, in an effect say.
|
|
282
|
+
|
|
283
|
+
Create the client at module scope or in a context, not in an effect that destroys it: React's development mode runs
|
|
284
|
+
effects twice. Vue: keep the state in a `shallowRef` set by `subscribe`. Svelte: the client is a store, so `$chat` is
|
|
285
|
+
the state.
|
|
286
|
+
|
|
287
|
+
## Markdown
|
|
288
|
+
|
|
289
|
+
```js
|
|
290
|
+
import { parseMarkdown, renderMarkdown } from "@meandr/chat-sdk/markdown";
|
|
291
|
+
|
|
292
|
+
bubble.replaceChildren(renderMarkdown(message.text)); // DOM nodes, never HTML
|
|
293
|
+
const tree = parseMarkdown(message.text); // plain objects, for React and friends
|
|
294
|
+
```
|
|
295
|
+
|
|
296
|
+
Paragraphs, headings, emphasis, code, lists, quotes, tables and links. Raw HTML stays text. Only `https:`, `http:` and
|
|
297
|
+
`mailto:` links become links, opening in a new tab with `rel="noopener noreferrer"`, and never one carrying a user
|
|
298
|
+
name or password. Images show as links to them, so nothing loads without a click.
|
|
299
|
+
|
|
300
|
+
Model answers can carry a link planted in a tool's output, so every link shows where it goes:
|
|
301
|
+
|
|
302
|
+
- **An address on its own** shows its address: the host as the browser parses it, spaces and invisible characters
|
|
303
|
+
left encoded, at most 200 characters.
|
|
304
|
+
- **A link with text of its own** has its host right before that text, as in "[nodejs.org] the docs", unless the
|
|
305
|
+
text already is that address. Nothing in the text can push the host away.
|
|
306
|
+
- **A `mailto:` link** has its whole address before its text.
|
|
307
|
+
|
|
308
|
+
A link's text is kept to one line of at most 120 characters. Hosts in other scripts show in punycode, an address
|
|
309
|
+
whose host holds anything but letters, digits, dots and hyphens isn't a link, link titles are dropped, and the
|
|
310
|
+
controls that reorder text (embeddings, overrides and isolates) are removed. A link that has its destination before
|
|
311
|
+
it carries it as `dest`, so your renderer can style that string.
|
|
312
|
+
|
|
313
|
+
`parseMarkdown` returns strings for text and `{ tag, children }` for elements, with `href` on `a`, `start` on `ol`,
|
|
314
|
+
`language` on `pre`, and `align` on `th` and `td`. Every `tag` is one an HTML renderer may create as it is:
|
|
315
|
+
|
|
316
|
+
```jsx
|
|
317
|
+
function Md({ node }) {
|
|
318
|
+
if (typeof node === "string") return node;
|
|
319
|
+
const kids = node.children?.map((c, i) => <Md key={i} node={c} />);
|
|
320
|
+
if (node.tag === "a") return <a href={node.href} target="_blank" rel="noopener noreferrer">{kids}</a>;
|
|
321
|
+
if (node.tag === "pre") return <pre><code>{kids}</code></pre>;
|
|
322
|
+
return createElement(node.tag, { start: node.start, style: node.align && { textAlign: node.align } }, kids);
|
|
323
|
+
}
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
## Behind your own server
|
|
327
|
+
|
|
328
|
+
Your server may forward `/chat/*` from your own domain to the workspace's URL, adding your user's token to each request
|
|
329
|
+
and dropping the browser's `Origin`. Then give `url` your own address and no token option. The browser holds nothing of
|
|
330
|
+
the chat's, and only signed-in users can chat: your server must answer for them.
|
|
331
|
+
|
|
332
|
+
## Content Security Policy
|
|
333
|
+
|
|
334
|
+
Allow `connect-src` for your workspace's URL and your token address, and `img-src blob:` to show files through object
|
|
335
|
+
URLs.
|
|
336
|
+
|
|
337
|
+
## License
|
|
338
|
+
|
|
339
|
+
Apache-2.0. See [LICENSE](LICENSE).
|
package/dist/api.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { ChatError } from "./errors.js";
|
|
2
|
+
export type Fetch = typeof fetch;
|
|
3
|
+
export interface Call {
|
|
4
|
+
method: "GET" | "POST" | "DELETE";
|
|
5
|
+
path: string;
|
|
6
|
+
body?: unknown;
|
|
7
|
+
type?: string;
|
|
8
|
+
bearer?: string | null;
|
|
9
|
+
signal?: AbortSignal;
|
|
10
|
+
stream?: boolean;
|
|
11
|
+
progress?: (sent: number) => void;
|
|
12
|
+
}
|
|
13
|
+
export declare function apiBase(url: string): string;
|
|
14
|
+
export declare function aborted(): ChatError;
|
|
15
|
+
export declare function within<T>(p: Promise<T>, signal: AbortSignal | undefined, ms: number, late: () => Error): Promise<T>;
|
|
16
|
+
export declare function timed(fetchFn: Fetch, url: string, init: RequestInit, signal?: AbortSignal, ms?: number): Promise<Response>;
|
|
17
|
+
export declare function request(fetchFn: Fetch, base: string, c: Call): Promise<Response>;
|
|
18
|
+
export declare function discard(res: Response): void;
|
|
19
|
+
export declare function chunks(res: Response, signal?: AbortSignal): Promise<Uint8Array<ArrayBuffer>[]>;
|
|
20
|
+
export declare function body(res: Response, signal?: AbortSignal): Promise<unknown>;
|
|
21
|
+
export declare function readJSON(res: Response, signal?: AbortSignal): Promise<unknown>;
|
|
22
|
+
export declare function failure(res: Response, signal?: AbortSignal): Promise<ChatError>;
|
|
23
|
+
export declare function retryAfter(res: Response): number | null;
|
|
24
|
+
export declare function sleep(ms: number, signal: AbortSignal): Promise<void>;
|
package/dist/client.d.ts
ADDED
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Message } from "./types.js";
|
|
2
|
+
export type ChatErrorCode = "unauthorized" | "token_expired" | "token_failed" | "session_expired" | "origin_not_allowed" | "origin_required" | "workspace_not_available" | "start_not_allowed" | "attachments_off" | "storage_full" | "not_found" | "busy" | "too_large" | "unsupported_type" | "rate_limited" | "overloaded" | "not_connected" | "interrupted" | "timeout" | "unavailable" | "model_busy" | "no_answer" | "network" | "aborted" | "bad_request" | "internal" | "protocol";
|
|
3
|
+
export interface ChatErrorInit {
|
|
4
|
+
status?: number;
|
|
5
|
+
retryAfter?: number | null;
|
|
6
|
+
partial?: Message | null;
|
|
7
|
+
cause?: unknown;
|
|
8
|
+
}
|
|
9
|
+
export declare class ChatError extends Error {
|
|
10
|
+
readonly code: ChatErrorCode | (string & {});
|
|
11
|
+
readonly status: number;
|
|
12
|
+
readonly retryAfter: number | null;
|
|
13
|
+
readonly partial: Message | null;
|
|
14
|
+
readonly cause?: unknown;
|
|
15
|
+
constructor(code: string, message: string, init?: ChatErrorInit);
|
|
16
|
+
get retryable(): boolean;
|
|
17
|
+
}
|
|
18
|
+
export declare function isChatError(e: unknown): e is ChatError;
|
package/dist/global.d.ts
ADDED
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { createChat } from "./client.js";
|
|
2
|
+
export { ChatError, isChatError } from "./errors.js";
|
|
3
|
+
export type { ChatErrorCode } from "./errors.js";
|
|
4
|
+
export type { Answer, AttachOptions, AttachResult, Chat, ChatFile, ChatOptions, ChatState, ChatStatus, Conversation, FileLimits, Message, PageContext, ReadFileOptions, ReadFileResult, ReopenOptions, SendOptions, SendResult, Stop, TokenRequest, TokenSource, ToolProgress, ToolStatus, Waiting, } from "./types.js";
|