@nightzeros/chatai-widget-core 1.0.0 → 1.2.0
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 +205 -0
- package/README.md +72 -0
- package/dist/index.d.ts +301 -2
- package/dist/index.js +1162 -14
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
Copyright 2026 NightZeros and contributors
|
package/README.md
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# @nightzeros/chatai-widget-core
|
|
2
|
+
|
|
3
|
+
Browser client for [ChatAI](https://github.com/nightzeros/chatai) assistants: loads the public widget config, streams chat replies, sends feedback, and runs Voice (preview) sessions. It has no UI and no dependencies.
|
|
4
|
+
|
|
5
|
+
Most sites should use [`@nightzeros/chatai-react`](https://www.npmjs.com/package/@nightzeros/chatai-react), [`@nightzeros/chatai-widget`](https://www.npmjs.com/package/@nightzeros/chatai-widget) or the hosted `chat.js` script. Use this package to build your own chat interface.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @nightzeros/chatai-widget-core
|
|
11
|
+
# or: pnpm add @nightzeros/chatai-widget-core
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Usage
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
import { createWidgetController } from "@nightzeros/chatai-widget-core";
|
|
18
|
+
|
|
19
|
+
const chat = createWidgetController({
|
|
20
|
+
assistantId: "asst_your_public_id",
|
|
21
|
+
apiUrl: "https://app.nightzeros.com",
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
const unsubscribe = chat.subscribe((state) => {
|
|
25
|
+
console.log(state.status, state.messages);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
await chat.load();
|
|
29
|
+
await chat.send("What are your opening hours?");
|
|
30
|
+
|
|
31
|
+
// When finished:
|
|
32
|
+
unsubscribe();
|
|
33
|
+
chat.destroy();
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Controller
|
|
37
|
+
|
|
38
|
+
`createWidgetController(options)` accepts `assistantId`, `apiUrl`, and optional `fetch`, `storage`, `createId` and `signEndpoint` (for assistants that require signed widgets). It returns:
|
|
39
|
+
|
|
40
|
+
| Method | Purpose |
|
|
41
|
+
| -------------------------------------------------------- | -------------------------------------------------------------- |
|
|
42
|
+
| `load()` | Fetch the assistant's public config |
|
|
43
|
+
| `send(message)` | Send a message and stream the reply into state |
|
|
44
|
+
| `sendFeedback(messageId, rating)` | Rate a reply `"positive"` or `"negative"` |
|
|
45
|
+
| `getState()` / `subscribe(listener)` | Read state or listen for changes |
|
|
46
|
+
| `voiceAvailable()` / `voiceSupported()` | Whether the assistant offers Voice and the browser supports it |
|
|
47
|
+
| `voiceConsentRequired()` | Whether a recording notice must be accepted first |
|
|
48
|
+
| `startVoice()` / `endVoice()` | Start or end a Voice (preview) session |
|
|
49
|
+
| `acceptRecordingConsent()` / `declineRecordingConsent()` | Answer the recording notice |
|
|
50
|
+
| `voiceLevels()` / `dismissVoiceError()` | Audio levels for a visualizer; clear a Voice error |
|
|
51
|
+
| `destroy()` | Stop streams and Voice and release the microphone |
|
|
52
|
+
|
|
53
|
+
Other exports include `resolveApiUrl`, `createSseParser`, `clientHistory`, Voice helpers (`createVoiceSession`, `deriveVoicePhase`, `isVoiceActive`, `VOICE_PHASE_LABELS`, `VOICE_ERROR_MESSAGES`, `VOICE_END_NOTICES`), control-health helpers, and TypeScript types such as `WidgetState`, `WidgetMessage` and `WidgetConfig`.
|
|
54
|
+
|
|
55
|
+
## Voice (preview)
|
|
56
|
+
|
|
57
|
+
Voice APIs were added in 1.1.0 and are a preview: their shape may change in minor releases. ChatAI 1.2.0 and later start Voice only for clients that support the playback gate (1.2.0 or later of this package). Voice needs HTTPS (or `localhost`), microphone permission and WebRTC, and a ChatAI server with a Voice provider configured.
|
|
58
|
+
|
|
59
|
+
## Compatibility
|
|
60
|
+
|
|
61
|
+
- Version 1.x works with ChatAI servers exposing `/api/v1`.
|
|
62
|
+
- Runs in modern browsers (`fetch` streaming, `ReadableStream`). ES module only.
|
|
63
|
+
|
|
64
|
+
## Links
|
|
65
|
+
|
|
66
|
+
- Documentation: [docs.nightzeros.com](https://docs.nightzeros.com/docs)
|
|
67
|
+
- Repository: [github.com/nightzeros/chatai](https://github.com/nightzeros/chatai)
|
|
68
|
+
- Changelog: [CHANGELOG.md](https://github.com/nightzeros/chatai/blob/main/CHANGELOG.md)
|
|
69
|
+
|
|
70
|
+
## License
|
|
71
|
+
|
|
72
|
+
[Apache-2.0](./LICENSE)
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,246 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Client supervision of the ChatAI Voice control plane.
|
|
3
|
+
*
|
|
4
|
+
* A live WebRTC connection is not proof that ChatAI still supervises the call: the
|
|
5
|
+
* browser heartbeats ChatAI and, when control is lost, mutes the call and then ends
|
|
6
|
+
* it within a bound.
|
|
7
|
+
*
|
|
8
|
+
* `healthy → suspect → reconnecting → healthy | terminated`, plus `closing` when the
|
|
9
|
+
* server reports the session lost (muted while the provider close lands, then ended).
|
|
10
|
+
*/
|
|
11
|
+
declare const CONTROL_HEALTH_DEFAULTS: {
|
|
12
|
+
intervalMs: number;
|
|
13
|
+
reconnectIntervalMs: number;
|
|
14
|
+
requestTimeoutMs: number;
|
|
15
|
+
failuresToReconnect: number;
|
|
16
|
+
silenceToReconnectMs: number;
|
|
17
|
+
reconnectGraceMs: number;
|
|
18
|
+
lostCloseWindowMs: number;
|
|
19
|
+
tickMs: number;
|
|
20
|
+
};
|
|
21
|
+
type ControlHealthSettings = typeof CONTROL_HEALTH_DEFAULTS;
|
|
22
|
+
type ControlHealthStatus = "healthy" | "suspect" | "reconnecting" | "closing" | "terminated";
|
|
23
|
+
type HeartbeatOutcome = {
|
|
24
|
+
kind: "healthy";
|
|
25
|
+
nextMs?: number;
|
|
26
|
+
} | {
|
|
27
|
+
kind: "degraded";
|
|
28
|
+
nextMs?: number;
|
|
29
|
+
} | {
|
|
30
|
+
kind: "ended";
|
|
31
|
+
endReason: string | null;
|
|
32
|
+
} | {
|
|
33
|
+
kind: "lost";
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* 421 misrouted or 429 rate limited: not a failure, but not proof of control either;
|
|
37
|
+
* only `healthy` restores the call or resets the silence timer.
|
|
38
|
+
*/
|
|
39
|
+
| {
|
|
40
|
+
kind: "neutral";
|
|
41
|
+
nextMs?: number;
|
|
42
|
+
} | {
|
|
43
|
+
kind: "failure";
|
|
44
|
+
};
|
|
45
|
+
type ControlHealthCause = "grace_expired" | "lost" | "ended";
|
|
46
|
+
type ControlHealthState = {
|
|
47
|
+
status: ControlHealthStatus;
|
|
48
|
+
failures: number;
|
|
49
|
+
lastSuccessAt: number;
|
|
50
|
+
reconnectingSince: number | null;
|
|
51
|
+
closingSince: number | null;
|
|
52
|
+
/** Set when terminated: the server's public end reason, or `disconnected`. */
|
|
53
|
+
endReason: string | null;
|
|
54
|
+
cause: ControlHealthCause | null;
|
|
55
|
+
};
|
|
56
|
+
declare function initialControlHealth(now: number): ControlHealthState;
|
|
57
|
+
/** Mic and assistant audio must be silenced in these states. */
|
|
58
|
+
declare function isControlMuted(status: ControlHealthStatus): boolean;
|
|
59
|
+
declare function reduceControlHealth(state: ControlHealthState, input: HeartbeatOutcome | {
|
|
60
|
+
kind: "tick";
|
|
61
|
+
}, now: number, settings?: ControlHealthSettings): ControlHealthState;
|
|
62
|
+
/** Heartbeat HTTP answer → outcome. Anything unexpected counts as a failed attempt. */
|
|
63
|
+
declare function classifyHeartbeatResponse(status: number, body: unknown): HeartbeatOutcome;
|
|
64
|
+
type ControlHealthMonitor = {
|
|
65
|
+
start(): void;
|
|
66
|
+
stop(): void;
|
|
67
|
+
state(): ControlHealthState;
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
70
|
+
* Runs the heartbeat loop: one request in flight at a time, each bounded by
|
|
71
|
+
* `requestTimeoutMs`. A response that arrives after its timeout, or after `stop()`,
|
|
72
|
+
* is ignored, so a stale answer can never restore a newer failed state.
|
|
73
|
+
*/
|
|
74
|
+
declare function createControlHealthMonitor(options: {
|
|
75
|
+
send(signal: AbortSignal): Promise<HeartbeatOutcome>;
|
|
76
|
+
onChange(next: ControlHealthState, previous: ControlHealthState): void;
|
|
77
|
+
intervalMs?: number;
|
|
78
|
+
settings?: Partial<ControlHealthSettings>;
|
|
79
|
+
now?: () => number;
|
|
80
|
+
}): ControlHealthMonitor;
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Browser half of ChatAI's server-authoritative Voice playback gate.
|
|
84
|
+
*
|
|
85
|
+
* The realtime model speaks straight to the browser and ChatAI cannot stop it, so
|
|
86
|
+
* assistant audio and captions stay muted unless ChatAI's latest decision for the
|
|
87
|
+
* call is `open`. Decisions arrive as NDJSON on POST /api/v1/voice/sessions/:id/gate;
|
|
88
|
+
* while that stream is down the gate is closed.
|
|
89
|
+
*/
|
|
90
|
+
declare const PLAYBACK_GATE_DEFAULTS: {
|
|
91
|
+
reconnectMinMs: number;
|
|
92
|
+
reconnectMaxMs: number;
|
|
93
|
+
/** The server sends a keepalive every 10 s; a stream silent this long is dead. */
|
|
94
|
+
staleAfterMs: number;
|
|
95
|
+
};
|
|
96
|
+
type PlaybackGateSettings = typeof PLAYBACK_GATE_DEFAULTS;
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Widget Voice state machine.
|
|
100
|
+
*
|
|
101
|
+
* `connection` is the lifecycle the controller drives; `phase` is what the visitor
|
|
102
|
+
* sees, derived from connection + recent audio/transcript activity. The priority
|
|
103
|
+
* order matches the owner playground: interrupted > user speaking > processing >
|
|
104
|
+
* assistant speaking > listening.
|
|
105
|
+
*/
|
|
106
|
+
type VoiceConnection = "idle" | "requesting_mic" | "connecting" | "connected"
|
|
107
|
+
/** ChatAI control is unreachable: mic and assistant muted, media kept for recovery. */
|
|
108
|
+
| "reconnecting" | "failed" | "ended";
|
|
109
|
+
type VoicePhase = "idle" | "requesting_mic" | "connecting" | "listening" | "user_speaking" | "processing" | "assistant_speaking" | "interrupted" | "reconnecting" | "error" | "ended";
|
|
110
|
+
type VoiceSignals = {
|
|
111
|
+
connection: VoiceConnection;
|
|
112
|
+
now: number;
|
|
113
|
+
/** Last time mic energy or an input transcript delta was observed. */
|
|
114
|
+
userVoiceAt: number | null;
|
|
115
|
+
/** Last time remote audio energy or an output transcript delta was observed. */
|
|
116
|
+
assistantVoiceAt: number | null;
|
|
117
|
+
/** ChatAI is looking something up for the current question. */
|
|
118
|
+
processing: boolean;
|
|
119
|
+
interruptedAt: number | null;
|
|
120
|
+
};
|
|
121
|
+
declare const VOICE_PHASE_LABELS: Record<VoicePhase, string>;
|
|
122
|
+
/**
|
|
123
|
+
* Processing outranks assistant audio because the realtime model may speak a short
|
|
124
|
+
* filler while ChatAI retrieves; that filler is not the grounded answer.
|
|
125
|
+
*/
|
|
126
|
+
declare function deriveVoicePhase(signals: VoiceSignals): VoicePhase;
|
|
127
|
+
declare function isVoiceActive(connection: VoiceConnection): connection is "reconnecting" | "requesting_mic" | "connecting" | "connected";
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Builds the visible Voice transcript from realtime transcript deltas.
|
|
131
|
+
*
|
|
132
|
+
* Input and output deltas share one provider timeline (`start_ms`/`end_ms`), so
|
|
133
|
+
* speech that starts before the assistant's audio has ended overlaps it. Overlapping
|
|
134
|
+
* speech shorter than BARGE_IN_MIN_WORDS ("mm-hm") is a backchannel and never becomes
|
|
135
|
+
* a turn; the ChatAI server applies the same threshold before it treats speech as a
|
|
136
|
+
* barge-in. Longer overlapping speech interrupts the assistant turn.
|
|
137
|
+
*/
|
|
138
|
+
declare const BARGE_IN_MIN_WORDS = 2;
|
|
139
|
+
type VoiceTranscriptTurn = {
|
|
140
|
+
id: string;
|
|
141
|
+
role: "user" | "assistant";
|
|
142
|
+
text: string;
|
|
143
|
+
interrupted: boolean;
|
|
144
|
+
};
|
|
145
|
+
declare function createVoiceTranscript(idPrefix: string): {
|
|
146
|
+
input(delta: string, startMs: number): void;
|
|
147
|
+
output(delta: string, endMs: number): void;
|
|
148
|
+
/** Committed turns in spoken order (copies). */
|
|
149
|
+
turns(): VoiceTranscriptTurn[];
|
|
150
|
+
/** Ends the transcript; short speech still overlapping the assistant is dropped. */
|
|
151
|
+
finish(): VoiceTranscriptTurn[];
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Browser side of a Topology B Voice session: mic + WebRTC media go straight to the
|
|
156
|
+
* realtime provider; ChatAI mints the session (POST /api/v1/voice/sessions), runs
|
|
157
|
+
* delegation/RAG/persistence on the sideband, and finalizes it on end. No provider
|
|
158
|
+
* credential ever reaches the browser: the mint response carries only the SDP answer.
|
|
159
|
+
*/
|
|
160
|
+
type VoiceErrorCode = "unsupported" | "mic_denied" | "mic_unavailable" | "voice_unavailable" | "rate_limited" | "network" | "media_failed" | "server";
|
|
161
|
+
type VoiceError = {
|
|
162
|
+
code: VoiceErrorCode;
|
|
163
|
+
message: string;
|
|
164
|
+
};
|
|
165
|
+
/** ChatAI ended the call itself (end endpoint or heartbeat), in visitor-safe terms. */
|
|
166
|
+
type VoiceServerEndReason = "voice_unavailable" | "superseded" | "disconnected" | "idle" | "max_duration";
|
|
167
|
+
/** Neutral: visitors never see plan, billing, quota, remaining minutes or internals. */
|
|
168
|
+
declare const VOICE_END_NOTICES: Record<VoiceServerEndReason, string>;
|
|
169
|
+
/** Any server end reason → the visitor-safe form (owner-only values collapse). */
|
|
170
|
+
declare function visitorEndReason(reported: unknown): VoiceServerEndReason | null;
|
|
171
|
+
declare const VOICE_ERROR_MESSAGES: Record<VoiceErrorCode, string>;
|
|
172
|
+
type VoiceMediaDeps = {
|
|
173
|
+
getUserMedia(constraints: MediaStreamConstraints): Promise<MediaStream>;
|
|
174
|
+
createPeerConnection(): RTCPeerConnection;
|
|
175
|
+
/** Null when Web Audio is unavailable; levels then fall back to transcript activity. */
|
|
176
|
+
createAudioContext(): AudioContext | null;
|
|
177
|
+
createAudioElement(): HTMLAudioElement | null;
|
|
178
|
+
};
|
|
179
|
+
type ClientHistoryMessage = {
|
|
180
|
+
role: "user" | "assistant";
|
|
181
|
+
content: string;
|
|
182
|
+
};
|
|
183
|
+
type VoiceSessionSnapshot = {
|
|
184
|
+
connection: VoiceConnection;
|
|
185
|
+
phase: VoicePhase;
|
|
186
|
+
error?: VoiceError;
|
|
187
|
+
/** Storage is off for this assistant: nothing from this session is saved. */
|
|
188
|
+
ephemeral?: boolean;
|
|
189
|
+
/** Voice turns are saved as text in the conversation; false keeps them to this session. */
|
|
190
|
+
transcriptSaved?: boolean;
|
|
191
|
+
/** Durable conversation the session writes to (null for no-store). */
|
|
192
|
+
conversationId?: string | null;
|
|
193
|
+
/** Session audio is recorded for the assistant owner (the visitor consented). */
|
|
194
|
+
recording?: boolean;
|
|
195
|
+
/** Set when ChatAI ended the call; `notice` is the visitor-safe explanation. */
|
|
196
|
+
endReason?: VoiceServerEndReason;
|
|
197
|
+
notice?: string;
|
|
198
|
+
/** Mock provider: control plane only, no audio. */
|
|
199
|
+
mock: boolean;
|
|
200
|
+
turns: VoiceTranscriptTurn[];
|
|
201
|
+
};
|
|
202
|
+
type VoiceSessionOptions = {
|
|
203
|
+
apiUrl: string;
|
|
204
|
+
assistantId: string;
|
|
205
|
+
visitorId: string;
|
|
206
|
+
conversationId?: string;
|
|
207
|
+
history: ClientHistoryMessage[];
|
|
208
|
+
/** The visitor accepted the recording disclosure (sent only when true). */
|
|
209
|
+
recordingConsent?: boolean;
|
|
210
|
+
fetch: typeof fetch;
|
|
211
|
+
media: VoiceMediaDeps;
|
|
212
|
+
/** Request headers (Content-Type + optional widget signature). */
|
|
213
|
+
headers(): Promise<Record<string, string>>;
|
|
214
|
+
onChange(snapshot: VoiceSessionSnapshot): void;
|
|
215
|
+
now?: () => number;
|
|
216
|
+
/** Control-health timing overrides (tests). */
|
|
217
|
+
controlHealth?: Partial<ControlHealthSettings> & {
|
|
218
|
+
now?: () => number;
|
|
219
|
+
};
|
|
220
|
+
/** Playback-gate stream timing overrides (tests). */
|
|
221
|
+
playbackGate?: Partial<PlaybackGateSettings>;
|
|
222
|
+
};
|
|
223
|
+
type VoiceEndReason = "close_requested" | "remote_hangup" | "connection_lost" | "error";
|
|
224
|
+
/** Browser capability check; false in SSR, insecure contexts and old browsers. */
|
|
225
|
+
declare function browserVoiceMedia(): VoiceMediaDeps | null;
|
|
226
|
+
declare function createVoiceSession(options: VoiceSessionOptions): {
|
|
227
|
+
snapshot: () => VoiceSessionSnapshot;
|
|
228
|
+
/** Mic/speaker levels (0–1-ish RMS) for visual feedback; read on animation frames. */
|
|
229
|
+
levels(): {
|
|
230
|
+
input: number;
|
|
231
|
+
output: number;
|
|
232
|
+
};
|
|
233
|
+
start(): Promise<void>;
|
|
234
|
+
/**
|
|
235
|
+
* Stops the mic and media immediately, then finalizes the server session.
|
|
236
|
+
* `keepalive` lets the end request outlive a closing page.
|
|
237
|
+
*/
|
|
238
|
+
end(reason?: VoiceEndReason, opts?: {
|
|
239
|
+
keepalive?: boolean;
|
|
240
|
+
}): Promise<void>;
|
|
241
|
+
};
|
|
242
|
+
type VoiceSession = ReturnType<typeof createVoiceSession>;
|
|
243
|
+
|
|
1
244
|
type WidgetSource = {
|
|
2
245
|
documentId: string;
|
|
3
246
|
documentName: string;
|
|
@@ -5,7 +248,7 @@ type WidgetSource = {
|
|
|
5
248
|
page?: number;
|
|
6
249
|
excerpt?: string;
|
|
7
250
|
};
|
|
8
|
-
type WidgetOutcome = "answered_with_context" | "fallback_no_context" | "low_confidence" | "retrieval_failure" | "model_failure" | "processing_failure";
|
|
251
|
+
type WidgetOutcome = "answered_with_context" | "fallback_no_context" | "low_confidence" | "retrieval_failure" | "model_failure" | "processing_failure" | "conversational" | "answered_from_history";
|
|
9
252
|
type WidgetStreamEvent = {
|
|
10
253
|
type: "token";
|
|
11
254
|
text: string;
|
|
@@ -26,6 +269,14 @@ type WidgetConfig = {
|
|
|
26
269
|
settings: Record<string, unknown>;
|
|
27
270
|
/** When true, chat/feedback require X-ChatAI-Signature from the sign endpoint. */
|
|
28
271
|
requireWidgetSigning?: boolean;
|
|
272
|
+
/** Public Voice availability (assistant enabled it and the instance supports it). */
|
|
273
|
+
voice?: {
|
|
274
|
+
enabled: boolean;
|
|
275
|
+
/** Sessions are recorded: the visitor must accept a disclosure before the mic is requested. */
|
|
276
|
+
recording?: {
|
|
277
|
+
consentRequired: boolean;
|
|
278
|
+
};
|
|
279
|
+
};
|
|
29
280
|
};
|
|
30
281
|
type WidgetMessage = {
|
|
31
282
|
id?: string;
|
|
@@ -33,6 +284,28 @@ type WidgetMessage = {
|
|
|
33
284
|
content: string;
|
|
34
285
|
sources?: WidgetSource[];
|
|
35
286
|
feedback?: "positive" | "negative";
|
|
287
|
+
modality?: "text" | "voice";
|
|
288
|
+
/** Voice: the visitor spoke over this assistant turn. */
|
|
289
|
+
interrupted?: boolean;
|
|
290
|
+
/** Voice: still being spoken. */
|
|
291
|
+
live?: boolean;
|
|
292
|
+
/** Voice turn the server did not save (storage on, Voice transcripts off); never reused as history. */
|
|
293
|
+
unsaved?: boolean;
|
|
294
|
+
};
|
|
295
|
+
type WidgetVoiceState = {
|
|
296
|
+
connection: VoiceConnection;
|
|
297
|
+
phase: VoicePhase;
|
|
298
|
+
error?: VoiceError;
|
|
299
|
+
ephemeral?: boolean;
|
|
300
|
+
/** False when Voice turns are not saved as text in the conversation. */
|
|
301
|
+
transcriptSaved?: boolean;
|
|
302
|
+
/** The recording disclosure is showing; the mic has not been requested. */
|
|
303
|
+
consentPending?: boolean;
|
|
304
|
+
/** This session's audio is being recorded (the visitor consented). */
|
|
305
|
+
recording?: boolean;
|
|
306
|
+
/** Visitor-safe explanation when ChatAI ended the call (e.g. usage limit). */
|
|
307
|
+
notice?: string;
|
|
308
|
+
mock?: boolean;
|
|
36
309
|
};
|
|
37
310
|
type WidgetState = {
|
|
38
311
|
status: "loading" | "ready" | "streaming" | "error";
|
|
@@ -40,6 +313,7 @@ type WidgetState = {
|
|
|
40
313
|
conversationId?: string;
|
|
41
314
|
messages: WidgetMessage[];
|
|
42
315
|
error?: string;
|
|
316
|
+
voice: WidgetVoiceState;
|
|
43
317
|
};
|
|
44
318
|
type StorageLike = Pick<Storage, "getItem" | "setItem">;
|
|
45
319
|
type WidgetControllerOptions = {
|
|
@@ -53,7 +327,11 @@ type WidgetControllerOptions = {
|
|
|
53
327
|
* Defaults to `${apiUrl}/api/v1/widget/sign` when config.requireWidgetSigning is true.
|
|
54
328
|
*/
|
|
55
329
|
signEndpoint?: string;
|
|
330
|
+
/** Browser media for Voice; defaults to the real browser APIs (null = unsupported). */
|
|
331
|
+
voiceMedia?: VoiceMediaDeps | null;
|
|
56
332
|
};
|
|
333
|
+
/** Recent turns the server uses when nothing is stored (no-store). */
|
|
334
|
+
declare function clientHistory(messages: WidgetMessage[]): ClientHistoryMessage[];
|
|
57
335
|
declare function resolveApiUrl(value: string): string;
|
|
58
336
|
declare function createSseParser(): {
|
|
59
337
|
push(chunk: string): WidgetStreamEvent[];
|
|
@@ -65,7 +343,28 @@ declare function createWidgetController(options: WidgetControllerOptions): {
|
|
|
65
343
|
load(): Promise<void>;
|
|
66
344
|
send(message: string): Promise<void>;
|
|
67
345
|
sendFeedback(messageId: string, rating: "positive" | "negative"): Promise<void>;
|
|
346
|
+
/** Voice can be offered: enabled for this assistant and supported by this browser. */
|
|
347
|
+
voiceAvailable(): boolean;
|
|
348
|
+
voiceSupported(): boolean;
|
|
349
|
+
/** Voice sessions are recorded, so starting one shows the disclosure first. */
|
|
350
|
+
voiceConsentRequired(): boolean;
|
|
351
|
+
/**
|
|
352
|
+
* Start Voice. When sessions are recorded this only opens the disclosure;
|
|
353
|
+
* the mic and the session wait for `acceptRecordingConsent()`.
|
|
354
|
+
*/
|
|
355
|
+
startVoice(): Promise<void>;
|
|
356
|
+
acceptRecordingConsent(): Promise<void>;
|
|
357
|
+
/** Back to text chat; nothing was requested or started. */
|
|
358
|
+
declineRecordingConsent(): void;
|
|
359
|
+
endVoice(): Promise<void>;
|
|
360
|
+
/** Live mic/speaker levels for the waveform; zeros when Voice is off. */
|
|
361
|
+
voiceLevels(): {
|
|
362
|
+
input: number;
|
|
363
|
+
output: number;
|
|
364
|
+
};
|
|
365
|
+
/** Clears a Voice error or end notice so the visitor can return to text or try again. */
|
|
366
|
+
dismissVoiceError(): void;
|
|
68
367
|
destroy(): void;
|
|
69
368
|
};
|
|
70
369
|
|
|
71
|
-
export { type WidgetConfig, type WidgetControllerOptions, type WidgetMessage, type WidgetOutcome, type WidgetSource, type WidgetState, type WidgetStreamEvent, createSseParser, createWidgetController, resolveApiUrl };
|
|
370
|
+
export { BARGE_IN_MIN_WORDS, CONTROL_HEALTH_DEFAULTS, type ClientHistoryMessage, type ControlHealthMonitor, type ControlHealthSettings, type ControlHealthState, type ControlHealthStatus, type HeartbeatOutcome, VOICE_END_NOTICES, VOICE_ERROR_MESSAGES, VOICE_PHASE_LABELS, type VoiceConnection, type VoiceEndReason, type VoiceError, type VoiceErrorCode, type VoiceMediaDeps, type VoicePhase, type VoiceServerEndReason, type VoiceSession, type VoiceSessionSnapshot, type VoiceTranscriptTurn, type WidgetConfig, type WidgetControllerOptions, type WidgetMessage, type WidgetOutcome, type WidgetSource, type WidgetState, type WidgetStreamEvent, type WidgetVoiceState, browserVoiceMedia, classifyHeartbeatResponse, clientHistory, createControlHealthMonitor, createSseParser, createVoiceSession, createVoiceTranscript, createWidgetController, deriveVoicePhase, initialControlHealth, isControlMuted, isVoiceActive, reduceControlHealth, resolveApiUrl, visitorEndReason };
|