react-native-voice-bot-sdk 0.2.0 → 0.2.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/CHANGELOG.md +22 -0
- package/README.md +47 -434
- package/build/VoiceBotClient.d.ts +38 -2
- package/build/VoiceBotClient.js +1 -1
- package/build/protocol.d.ts +13 -0
- package/build/react/VoiceBotProvider.d.ts +16 -3
- package/build/react/VoiceBotProvider.js +1 -1
- package/docs/ACTIONS.md +1 -1
- package/docs/INTEGRATION.md +97 -3
- package/docs/PROTOCOL.md +17 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.2
|
|
4
|
+
|
|
5
|
+
- **Mic-button sessions:** `<VoiceBotProvider connectOn="mic">` (or `VoiceBot.configure({ ..., disconnectOnStop: true })`
|
|
6
|
+
then `start()`) connects only while the mic is on. Pressing the mic connects and starts
|
|
7
|
+
listening; pressing it again stops listening, stops the bot's reply and closes the socket. A
|
|
8
|
+
press while connecting cancels. A phone call, a mic error or a denied mic permission also ends
|
|
9
|
+
the session, so the mic is never off while the socket stays open. Default unchanged (`"mount"`).
|
|
10
|
+
- `disconnect()` now also clears the speaking state right away.
|
|
11
|
+
- **Streamed speech:** replies whose speech arrives as `{type:"tts", data, sample_rate}` messages
|
|
12
|
+
after the reply message now play completely. Before, only the reply's first `buffer` (about
|
|
13
|
+
200 ms) played, so the voice was cut off mid-word. The chunks play as part of the current reply
|
|
14
|
+
(skipped if the user talked over it; a new question still stops the old reply). They reach
|
|
15
|
+
`onMessage` listeners but don't update `lastMessage`, to avoid a re-render per chunk.
|
|
16
|
+
|
|
17
|
+
## 0.2.1
|
|
18
|
+
|
|
19
|
+
- **`userId`:** new option on `VoiceBotProvider` and `VoiceBot.connect()`, sent as `user_id` in the
|
|
20
|
+
connect message (next to `domain_id`). Your app's id for the signed-in user in any format (email, phone number, your own id); `""` for
|
|
21
|
+
guests. Never written to the SDK's logs.
|
|
22
|
+
When the provider's `userId` changes (sign in / sign out) it reconnects, so the server gets the
|
|
23
|
+
new user. Backwards compatible: without it `user_id` is `""`.
|
|
24
|
+
|
|
3
25
|
## 0.2.0
|
|
4
26
|
|
|
5
27
|
**Actions:** the AI server can now run operations that the app registers, not only open screens.
|
package/README.md
CHANGED
|
@@ -1,75 +1,34 @@
|
|
|
1
1
|
# react-native-voice-bot-sdk
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
- ✅ One wrapper, one floating mic button: no other UI work needed
|
|
8
|
-
- ✅ Or your own button with the `useVoiceBot()` hook
|
|
9
|
-
- ✅ The server can navigate your app (Expo Router, React Navigation, or your own router)
|
|
10
|
-
- ✅ **Actions:** the server can run operations your app registers ("add a medium T-shirt to my
|
|
11
|
-
cart and go to checkout"): validated, run in order, confirmed by the user when needed, real results
|
|
12
|
-
- ✅ Clean audio: noise gate, the mic is muted while the bot speaks (no echo loops), optional barge-in
|
|
13
|
-
- ✅ Keeps listening in the background (Android), reconnects by itself, handles phone calls
|
|
14
|
-
- ✅ Every request and response in the console, TypeScript-first
|
|
15
|
-
|
|
16
|
-
> Actions guide: [docs/ACTIONS.md](https://unpkg.com/react-native-voice-bot-sdk/docs/ACTIONS.md) · Integration guide: [docs/INTEGRATION.md](https://unpkg.com/react-native-voice-bot-sdk/docs/INTEGRATION.md) · Wire protocol for the server team:
|
|
17
|
-
> [docs/PROTOCOL.md](https://unpkg.com/react-native-voice-bot-sdk/docs/PROTOCOL.md) · Release notes: [CHANGELOG.md](https://unpkg.com/react-native-voice-bot-sdk/CHANGELOG.md)
|
|
3
|
+
A voice assistant for React Native and Expo apps. Users tap a mic and talk; the SDK streams their
|
|
4
|
+
voice to your voice server, plays the spoken answer, and lets the server open screens and run
|
|
5
|
+
actions in your app.
|
|
18
6
|
|
|
19
7
|
## Requirements
|
|
20
8
|
|
|
21
|
-
- Expo SDK 52
|
|
22
|
-
|
|
23
|
-
-
|
|
24
|
-
- Android 7+ (tested). iOS 16.4+ (first version, not tested on a device yet).
|
|
9
|
+
- Expo SDK 52+ with a development build (not Expo Go), or bare React Native with Expo modules.
|
|
10
|
+
- Android 7+, iOS 16.4+.
|
|
11
|
+
- A voice server URL and your domain id.
|
|
25
12
|
|
|
26
|
-
##
|
|
13
|
+
## Install
|
|
27
14
|
|
|
28
15
|
```bash
|
|
29
16
|
npx expo install react-native-voice-bot-sdk
|
|
30
17
|
```
|
|
31
18
|
|
|
32
|
-
Add the
|
|
19
|
+
Add the plugin to `app.json` (it adds the microphone permission):
|
|
33
20
|
|
|
34
21
|
```json
|
|
35
22
|
{
|
|
36
23
|
"expo": {
|
|
37
24
|
"plugins": [
|
|
38
|
-
["react-native-voice-bot-sdk", {
|
|
39
|
-
"microphonePermission": "Allow $(PRODUCT_NAME) to use the microphone for the voice assistant",
|
|
40
|
-
"allowCleartextTraffic": true
|
|
41
|
-
}]
|
|
25
|
+
["react-native-voice-bot-sdk", { "microphonePermission": "Allow $(PRODUCT_NAME) to use the microphone for the voice assistant" }]
|
|
42
26
|
]
|
|
43
27
|
}
|
|
44
28
|
}
|
|
45
29
|
```
|
|
46
30
|
|
|
47
|
-
|
|
48
|
-
release builds.
|
|
49
|
-
|
|
50
|
-
### Self-signed `wss://` server (Android dev builds)
|
|
51
|
-
|
|
52
|
-
Android only trusts certificates from public authorities. If your test server uses a self-signed
|
|
53
|
-
certificate, connecting fails with `Trust anchor for certification path not found`. Save the
|
|
54
|
-
server's certificate in your project and list it in the plugin:
|
|
55
|
-
|
|
56
|
-
```bash
|
|
57
|
-
mkdir -p certs
|
|
58
|
-
openssl s_client -connect your-test-server:8091 </dev/null 2>/dev/null | openssl x509 -outform PEM > certs/server.pem
|
|
59
|
-
```
|
|
60
|
-
|
|
61
|
-
```json
|
|
62
|
-
["react-native-voice-bot-sdk", { "trustedCertificates": ["./certs/server.pem"] }]
|
|
63
|
-
```
|
|
64
|
-
|
|
65
|
-
Then run `npx expo prebuild --clean` and rebuild. The plugin adds an Android network security
|
|
66
|
-
config that trusts these certificates **in debuggable (dev) builds only**; release builds keep the
|
|
67
|
-
normal system trust. The certificate's Subject Alternative Name must contain the host you connect
|
|
68
|
-
to (IP or DNS name). For production, use a certificate from a public CA (e.g. Let's Encrypt) and
|
|
69
|
-
leave this option out. If your app already has its own `networkSecurityConfig`, add the certificate
|
|
70
|
-
there instead. iOS is not covered by this option.
|
|
71
|
-
|
|
72
|
-
Then rebuild the native app:
|
|
31
|
+
Then rebuild the app:
|
|
73
32
|
|
|
74
33
|
```bash
|
|
75
34
|
npx expo prebuild --clean
|
|
@@ -79,15 +38,9 @@ npx expo prebuild --clean
|
|
|
79
38
|
npx expo run:android
|
|
80
39
|
```
|
|
81
40
|
|
|
82
|
-
|
|
83
|
-
the app. The library's own Android manifest adds `RECORD_AUDIO`; on iOS add
|
|
84
|
-
`NSMicrophoneUsageDescription` to `Info.plist` and run `pod install`.
|
|
41
|
+
## Set up
|
|
85
42
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
### Step 1: wrap your app once with `VoiceBotProvider`
|
|
89
|
-
|
|
90
|
-
**Expo Router** (`app/_layout.tsx`):
|
|
43
|
+
Wrap your app once. This example uses Expo Router (`app/_layout.tsx`):
|
|
91
44
|
|
|
92
45
|
```tsx
|
|
93
46
|
import { Stack } from 'expo-router';
|
|
@@ -95,415 +48,75 @@ import { VoiceBotProvider } from 'react-native-voice-bot-sdk';
|
|
|
95
48
|
import { useExpoRouterNavigation } from 'react-native-voice-bot-sdk/expo-router';
|
|
96
49
|
|
|
97
50
|
export default function RootLayout() {
|
|
98
|
-
const navigation = useExpoRouterNavigation();
|
|
99
|
-
|
|
51
|
+
const navigation = useExpoRouterNavigation();
|
|
100
52
|
return (
|
|
101
|
-
<VoiceBotProvider
|
|
53
|
+
<VoiceBotProvider
|
|
54
|
+
url="wss://your-voice-server/demo"
|
|
55
|
+
domainId="YOUR_DOMAIN_ID"
|
|
56
|
+
userId={currentUser?.email}
|
|
57
|
+
navigation={navigation}
|
|
58
|
+
>
|
|
102
59
|
<Stack />
|
|
103
60
|
</VoiceBotProvider>
|
|
104
61
|
);
|
|
105
62
|
}
|
|
106
63
|
```
|
|
107
64
|
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
```tsx
|
|
111
|
-
import { VoiceBotProvider } from 'react-native-voice-bot-sdk';
|
|
112
|
-
|
|
113
|
-
export default function App() {
|
|
114
|
-
return (
|
|
115
|
-
<VoiceBotProvider url="wss://voice.example.com/demo" domainId="YOUR_DOMAIN_ID">
|
|
116
|
-
<AppNavigator />
|
|
117
|
-
</VoiceBotProvider>
|
|
118
|
-
);
|
|
119
|
-
}
|
|
120
|
-
```
|
|
121
|
-
|
|
122
|
-
That's the whole setup for the **widget-only** integration: the provider connects to your server
|
|
123
|
-
and shows the floating mic (bottom-right). The user taps it to talk and taps again to stop.
|
|
124
|
-
|
|
125
|
-
### Step 2 (optional): use it from any screen with `useVoiceBot`
|
|
126
|
-
|
|
127
|
-
```tsx
|
|
128
|
-
import { Button } from 'react-native';
|
|
129
|
-
import { useVoiceBot } from 'react-native-voice-bot-sdk';
|
|
130
|
-
|
|
131
|
-
function TalkButton() {
|
|
132
|
-
const { isListening, start, stop, lastQuestion, lastPrompt } = useVoiceBot();
|
|
133
|
-
return <Button title={isListening ? 'Stop' : 'Talk to us'} onPress={isListening ? stop : start} />;
|
|
134
|
-
}
|
|
135
|
-
```
|
|
136
|
-
|
|
137
|
-
Right after connecting, the SDK sends one connect message with your screen names, then streams
|
|
138
|
-
the mic:
|
|
139
|
-
|
|
140
|
-
```json
|
|
141
|
-
{
|
|
142
|
-
"sessionId": "c0a8f6e2-…",
|
|
143
|
-
"domain_id": "YOUR_DOMAIN_ID",
|
|
144
|
-
"cookie_id": "9b2e4c1a-…",
|
|
145
|
-
"type": "Buffer",
|
|
146
|
-
"deviceId": 1,
|
|
147
|
-
"sampleRate": 16000,
|
|
148
|
-
"screens": ["cart", "index", "products", "profile", "product/[id]"]
|
|
149
|
-
}
|
|
150
|
-
```
|
|
151
|
-
|
|
152
|
-
## Widget on or off
|
|
153
|
-
|
|
154
|
-
```tsx
|
|
155
|
-
<VoiceBotProvider url={URL}> {/* default floating mic */}
|
|
156
|
-
<VoiceBotProvider url={URL} widget={{ size: 56, right: 16, bottom: 90, colors: { idle: '#7048E8' } }}>
|
|
157
|
-
<VoiceBotProvider url={URL} widget={false}> {/* no widget: use your own button */}
|
|
158
|
-
```
|
|
65
|
+
That's all: a floating mic button appears. Tap to talk, tap again to stop.
|
|
159
66
|
|
|
160
|
-
|
|
161
|
-
|
|
67
|
+
| Prop | Required | What it is |
|
|
68
|
+
|------|----------|------------|
|
|
69
|
+
| `url` | Yes | Your voice server's WebSocket URL. |
|
|
70
|
+
| `domainId` | Yes | Your domain id. |
|
|
71
|
+
| `userId` | No | The signed-in user: email, phone number or your own id. Leave it out for guests. |
|
|
72
|
+
| `navigation` | No | Lets the assistant open your screens. Expo Router: `useExpoRouterNavigation()`. React Navigation: `createReactNavigationAdapter(navigationRef)`. |
|
|
73
|
+
| `connectOn` | No | `"mount"` (default): stay connected while the app runs. `"mic"`: connect only while the mic is on. |
|
|
74
|
+
| `widget` | No | `true` (default) shows the floating mic. `false` to use your own button. |
|
|
162
75
|
|
|
163
76
|
## Your own button
|
|
164
77
|
|
|
165
78
|
```tsx
|
|
166
|
-
import { useVoiceBot } from 'react-native-voice-bot-sdk';
|
|
79
|
+
import { VoiceBotProvider, useVoiceBot } from 'react-native-voice-bot-sdk';
|
|
80
|
+
|
|
81
|
+
<VoiceBotProvider url={URL} domainId={DOMAIN_ID} widget={false}>
|
|
167
82
|
|
|
168
83
|
function TalkButton() {
|
|
169
84
|
const bot = useVoiceBot();
|
|
170
|
-
return
|
|
171
|
-
<Button
|
|
172
|
-
title={bot.isListening ? 'Stop' : 'Talk'}
|
|
173
|
-
onPress={() => (bot.isListening ? bot.stop() : bot.start())}
|
|
174
|
-
/>
|
|
175
|
-
);
|
|
85
|
+
return <Button title={bot.isListening ? 'Stop' : 'Talk'} onPress={bot.toggle} />;
|
|
176
86
|
}
|
|
177
87
|
```
|
|
178
88
|
|
|
179
|
-
|
|
180
|
-
`
|
|
181
|
-
|
|
182
|
-
`start()` asks for the microphone permission the first time. If the socket isn't open it reconnects
|
|
183
|
-
with the options from the last `connect()` call and then starts the mic.
|
|
184
|
-
|
|
185
|
-
## API
|
|
186
|
-
|
|
187
|
-
### `VoiceBot.connect(options)`
|
|
188
|
-
|
|
189
|
-
| Option | Type | Description |
|
|
190
|
-
|--------|------|-------------|
|
|
191
|
-
| `url` | `string` | **Required.** WebSocket URL of the voice server. |
|
|
192
|
-
| `domainId` | `string` | Sent as `domain_id` in the connect message. Default `""`. |
|
|
193
|
-
| `cookieId` | `string` | Sent as `cookie_id`. Default: a random id the SDK saves on the device, so it stays the same across app launches. Pass your own id (e.g. your user's visitor id) to use that instead. |
|
|
194
|
-
| `onSuccess` | `({ sessionId }) => void` | Connected; the connect message (with the screen names) was sent. |
|
|
195
|
-
| `onFailure` | `(error) => void` | Couldn't connect. `error.code`: `connect_failed`, `connect_timeout`, `native_missing`, ... |
|
|
196
|
-
| `onClose` | `({ code, reason }) => void` | The socket closed after a successful connect. |
|
|
197
|
-
| `onReply` | `(reply) => void` | Every reply from the server (`question`, `output`, `buffer`). |
|
|
198
|
-
| `autoStart` | `boolean` | Start the mic right after connecting. Default `false`. |
|
|
199
|
-
| `uplinkEncoding` | `'binary' \| 'base64'` | Default `binary` (what the server expects today). `base64` needs server support, see the protocol doc. |
|
|
200
|
-
| `deviceId` | `number` | `deviceId` in the connect message. Default `1`. |
|
|
201
|
-
| `connectTimeoutMs` | `number` | Default `10000`. |
|
|
202
|
-
| `autoReconnect` | `boolean \| { maxAttempts?, maxDelayMs? }` | Reconnect by itself when the socket drops. Default `true` (backoff 1 s, 2 s, 4 s … 30 s, 20 attempts). See [Reconnecting](#reconnecting). |
|
|
203
|
-
| `onReconnecting` | `({ attempt, delayMs }) => void` | Called before each reconnect attempt. |
|
|
204
|
-
| `backgroundListening` | `boolean \| { title?, text? }` | Android: keep listening in the background, with a notification while the mic is on. Default `true`. See [Background listening](#background-listening). |
|
|
205
|
-
| `interruptOnNewReply` | `boolean` | Default `true`: a reply to a new question stops the old reply's audio and plays right away. Parts of the same reply still play in order. `false` queues every reply. |
|
|
206
|
-
| `noiseGate` | `boolean \| { thresholdDb?, minLevelDb?, hangoverMs?, preRollMs? }` | Default `true`: send silence instead of room noise between sentences. See [Noise gate and barge-in](#noise-gate-and-barge-in). |
|
|
207
|
-
| `whileSpeaking` | `'mute' \| 'guard' \| 'listen'` | What the mic does while the bot speaks. Default `'mute'`. |
|
|
208
|
-
| `bargeIn` | `boolean` | Default `false`. `true`: talking over the bot stops its reply (use with headsets and `whileSpeaking: 'guard'`). |
|
|
209
|
-
| `echoTailMs` | `number` | Default `600`: the mic stays muted this long after the reply has finished playing. |
|
|
210
|
-
| `pauseOnCall` | `boolean` | Default `true`: during a phone call, stop the bot's audio and send silence. |
|
|
211
|
-
| `keepSessionOnReconnect` | `boolean` | Default `false`. `true` keeps the same `sessionId` after an automatic reconnect. |
|
|
212
|
-
| `localNavigation` | `boolean` | Default `true`: when the server doesn't navigate, open the screen the user clearly asked for ("open my cart"). See [Local voice navigation](#local-voice-navigation). |
|
|
213
|
-
| `voiceShortcuts` | `Record<screen, string[]>` | Extra words for local navigation, e.g. `{ '(tabs)/cart': ['bag', 'basket'] }`. |
|
|
214
|
-
| `logLevel` | `'trace' \| 'debug' \| 'info' \| 'warn' \| 'error' \| 'none'` | Console logging, see [Logs](#logs). |
|
|
215
|
-
|
|
216
|
-
### `useVoiceBot()`
|
|
217
|
-
|
|
218
|
-
```tsx
|
|
219
|
-
const { status, isReady, isListening, speaking, lastQuestion, lastPrompt, lastMessage, error,
|
|
220
|
-
start, stop, toggle, connect, disconnect, addMessageListener } = useVoiceBot();
|
|
221
|
-
```
|
|
222
|
-
|
|
223
|
-
| Returns | Description |
|
|
224
|
-
|---------|-------------|
|
|
225
|
-
| `status` | `'idle' \| 'connecting' \| 'connected' \| 'listening'` |
|
|
226
|
-
| `isReady` / `isConnected` | Connected to the server, ready to listen. |
|
|
227
|
-
| `isListening` | The mic is on. |
|
|
228
|
-
| `speaking` | The bot's reply is playing. |
|
|
229
|
-
| `sessionId` | Current session id, or `null`. |
|
|
230
|
-
| `lastQuestion`, `lastPrompt` | What the user said (`question`) and the bot's answer text (`output.prompt`). |
|
|
231
|
-
| `lastMessage` | The most recent JSON message from the server. |
|
|
232
|
-
| `error` / `lastError` | Last error (`{ code, message }`), or `null`. |
|
|
233
|
-
| `start`, `stop`, `toggle` | Mic on / off. `start()` asks for the mic permission the first time and reconnects if needed. |
|
|
234
|
-
| `connect`, `disconnect` | Same as `VoiceBot.connect()` / `disconnect()`. |
|
|
235
|
-
| `registerAction(name, def)` | Register an action; returns an unregister function. |
|
|
236
|
-
| `setScreenContext(params)` | Small context about the visible screen, sent with `screen_changed`. |
|
|
237
|
-
| `addMessageListener(fn)` | Every JSON message from the server. Returns an unsubscribe function. |
|
|
238
|
-
|
|
239
|
-
### `<VoiceBotProvider>`
|
|
240
|
-
|
|
241
|
-
| Prop | Description |
|
|
242
|
-
|------|-------------|
|
|
243
|
-
| `url` | Voice server WebSocket URL. When set, the provider connects by itself. |
|
|
244
|
-
| `domainId` | Sent as `domain_id`. |
|
|
245
|
-
| `autoConnect` | Default `true` (when `url` is set). |
|
|
246
|
-
| `widget` | Default `true`: the floating mic. Widget props to style it, `false` to use your own button. |
|
|
247
|
-
| `navigation` | A navigation adapter, so the server can open screens (see below). |
|
|
248
|
-
| `onConnect`, `onError`, `onClose` | Connection callbacks. |
|
|
249
|
-
| `onReply`, `onMessage` | Every reply / every JSON message from the server. |
|
|
250
|
-
| `actions` | Actions the server may run (see [Actions](#actions-020)). |
|
|
251
|
-
| `onConfirmAction` | Your confirmation UI for actions with `confirm`. Default: a native alert. |
|
|
252
|
-
| `options` | Any other `VoiceBot.connect()` option (`noiseGate`, `bargeIn`, `autoReconnect`, `logLevel` …). |
|
|
253
|
-
| `disconnectOnUnmount` | Default `true`. |
|
|
89
|
+
`useVoiceBot()` also gives `status`, `speaking`, `lastQuestion` (what the user said) and
|
|
90
|
+
`lastPrompt` (the assistant's answer).
|
|
254
91
|
|
|
255
|
-
|
|
92
|
+
## Actions (optional)
|
|
256
93
|
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
Let the AI server run operations of your app. Register them on the provider; the SDK validates
|
|
260
|
-
params, asks for confirmation where you require it, runs them in order with timeouts, and tells the
|
|
261
|
-
server the real result. The SDK has no business logic of its own.
|
|
94
|
+
Let the assistant do things in your app, such as adding to a cart. You write the code; the SDK
|
|
95
|
+
checks the parameters, asks the user to confirm where you require it, and reports the result.
|
|
262
96
|
|
|
263
97
|
```tsx
|
|
264
98
|
<VoiceBotProvider
|
|
265
99
|
url={URL}
|
|
266
|
-
|
|
100
|
+
domainId={DOMAIN_ID}
|
|
267
101
|
actions={{
|
|
268
102
|
add_to_cart: {
|
|
269
103
|
description: 'Add a product to the cart',
|
|
270
|
-
params: { product: 'string', size: 'string?'
|
|
271
|
-
run: async ({ product, size,
|
|
272
|
-
const line = await cart.add(product, size, quantity); // your code
|
|
273
|
-
return { ok: true, data: line };
|
|
274
|
-
},
|
|
104
|
+
params: { product: 'string', size: 'string?' },
|
|
105
|
+
run: async ({ product, size }) => ({ ok: true, data: await cart.add(product, size) }),
|
|
275
106
|
},
|
|
276
|
-
place_order: { description: 'Place the order', confirm: true, run: () => api.placeOrder() },
|
|
277
107
|
}}
|
|
278
108
|
>
|
|
279
109
|
```
|
|
280
110
|
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
`useVoiceBotScreenContext()` so the server knows what "this" is, `ActionError` for safe error
|
|
284
|
-
codes, `onConfirmAction` for your own confirmation UI. Full guide:
|
|
285
|
-
[docs/ACTIONS.md](https://unpkg.com/react-native-voice-bot-sdk/docs/ACTIONS.md).
|
|
286
|
-
|
|
287
|
-
## Reconnecting
|
|
288
|
-
|
|
289
|
-
If the connection drops (Wi-Fi change, server restart, close code other than 1000), the SDK
|
|
290
|
-
reconnects by itself: after 1 s, 2 s, 4 s … up to 30 s between tries, 20 tries by default. While it
|
|
291
|
-
reconnects:
|
|
292
|
-
|
|
293
|
-
- `status` is `'connecting'` and the widget shows the spinner;
|
|
294
|
-
- **the mic keeps running**, frames recorded while offline are dropped (not queued), and streaming
|
|
295
|
-
continues as soon as the socket is open again;
|
|
296
|
-
- each reconnect is a **new session**: new `sessionId`, the connect message is sent again, and
|
|
297
|
-
`onSuccess` is called again; `onClose` is called for the dropped socket.
|
|
298
|
-
|
|
299
|
-
Tapping the mic, or coming back to the app, retries right away. `disconnect()` stops reconnecting.
|
|
300
|
-
The server closing with code `1000` is treated as a normal end and is not retried.
|
|
301
|
-
|
|
302
|
-
```ts
|
|
303
|
-
VoiceBot.connect({
|
|
304
|
-
url,
|
|
305
|
-
autoReconnect: { maxAttempts: 10, maxDelayMs: 15000 }, // or false
|
|
306
|
-
onReconnecting: ({ attempt, delayMs }) => console.log('reconnect', attempt, delayMs),
|
|
307
|
-
});
|
|
308
|
-
```
|
|
309
|
-
|
|
310
|
-
## Noise gate and barge-in
|
|
311
|
-
|
|
312
|
-
**Noise gate.** In a real room the pauses between sentences are full of noise, so the server can't
|
|
313
|
-
tell where a sentence ends. The SDK checks every 20 ms frame against the room's noise level and,
|
|
314
|
-
while nobody is speaking near the phone, sends silence instead. The stream keeps its shape (one
|
|
315
|
-
640-byte frame every 20 ms). The 300 ms before speech starts is kept, so the first syllable isn't
|
|
316
|
-
cut, which delays the stream by 300 ms; 700 ms after the last word is kept too. It's an energy gate:
|
|
317
|
-
it removes steady noise and makes pauses clean, but people talking near the phone at the same
|
|
318
|
-
volume as the user still get through.
|
|
319
|
-
|
|
320
|
-
```ts
|
|
321
|
-
VoiceBot.connect({ url, noiseGate: { thresholdDb: 8 } }); // more sensitive (default 10)
|
|
322
|
-
VoiceBot.connect({ url, noiseGate: false }); // send the mic unchanged
|
|
323
|
-
```
|
|
324
|
-
|
|
325
|
-
**While the bot speaks** (`whileSpeaking`): `'mute'` (default) sends silence while the reply plays
|
|
326
|
-
and for `echoTailMs` (600 ms) after the speaker has really finished. On a phone's loudspeaker the
|
|
327
|
-
bot's own voice comes back into the mic about as loud as a person (echo cancellation often doesn't
|
|
328
|
-
remove it); without the mute the server hears the bot, answers itself, and replies cut each other
|
|
329
|
-
off. `'guard'` only counts clearly louder speech (for headsets). `'listen'` treats it like any other
|
|
330
|
-
time.
|
|
331
|
-
|
|
332
|
-
**Barge-in** (`bargeIn`, default off): with `whileSpeaking: 'guard'`, when the user talks over the
|
|
333
|
-
bot for about 300 ms clearly louder than the reply's echo, the reply stops and the rest of it isn't
|
|
334
|
-
played. Turn it on only where echo is low (headsets); on a loudspeaker the echo can trigger it.
|
|
335
|
-
|
|
336
|
-
**End of playback:** the native module reports when the speaker has really played the last of the
|
|
337
|
-
reply (`onPlaybackIdle`), so "speaking" and the mute end at the right time, not on an estimate.
|
|
338
|
-
|
|
339
|
-
**Other apps and calls.** While the bot speaks it takes the audio focus, so music from other apps
|
|
340
|
-
gets quieter. If another app takes the audio (or a call comes in), the bot's reply stops. During a
|
|
341
|
-
phone call the mic sends silence, and normal audio resumes when the call ends (`pauseOnCall`).
|
|
342
|
-
|
|
343
|
-
## Background listening
|
|
344
|
-
|
|
345
|
-
On Android, apps lose the microphone in the background unless they run a *foreground service* of
|
|
346
|
-
type microphone, which must show a notification. While the mic is on, the SDK runs one, so the voice
|
|
347
|
-
bot keeps listening when the user switches apps or locks the screen. The notification goes away
|
|
348
|
-
when the mic stops. On Android 13+ the SDK asks for the notification permission the first time; if
|
|
349
|
-
it's denied, background listening still works but the notification is hidden.
|
|
350
|
-
|
|
351
|
-
```ts
|
|
352
|
-
VoiceBot.connect({ url, backgroundListening: { title: 'My Shop assistant', text: 'Listening…' } });
|
|
353
|
-
VoiceBot.connect({ url, backgroundListening: false }); // mic only while the app is on screen
|
|
354
|
-
```
|
|
355
|
-
|
|
356
|
-
The library's manifest adds `FOREGROUND_SERVICE`, `FOREGROUND_SERVICE_MICROPHONE` and
|
|
357
|
-
`POST_NOTIFICATIONS`, and the service. Apps on Google Play must declare the microphone foreground
|
|
358
|
-
service use in the Play Console. iOS: not supported yet.
|
|
359
|
-
|
|
360
|
-
## Navigation ("agentic")
|
|
361
|
-
|
|
362
|
-
The server can send `{"type":"navigate","screen":"cart"}` or `{"type":"navigate","action":"back"}`.
|
|
363
|
-
The SDK only opens screens it sent to the server, and follows the usual back stack rules:
|
|
364
|
-
|
|
365
|
-
- a screen that isn't in the stack is **pushed**;
|
|
366
|
-
- a screen that's already in the stack is **popped back to** (the screens above it are removed);
|
|
367
|
-
- the visible screen: nothing happens (`already_on_screen`);
|
|
368
|
-
- `back` works like the Back button.
|
|
369
|
-
|
|
370
|
-
The result goes back to the server as `navigate_result`, and every screen change (voice, tap or
|
|
371
|
-
Back) is sent as `screen_changed` with the back stack. Pick the adapter for your app:
|
|
372
|
-
|
|
373
|
-
### Local voice navigation
|
|
374
|
-
|
|
375
|
-
If the server's reply doesn't navigate (`type: "none"`) but the user clearly asked for a screen,
|
|
376
|
-
the SDK opens it itself:
|
|
377
|
-
|
|
378
|
-
| User says | Opens |
|
|
379
|
-
|-----------|-------|
|
|
380
|
-
| "Open my cart", "go to my cart" | `(tabs)/cart` |
|
|
381
|
-
| "Show my orders" | `orders/index` |
|
|
382
|
-
| "Take me to my notifications please" | `account/notifications` |
|
|
383
|
-
| "Take me home" | the screen at `/` |
|
|
384
|
-
| "Go back" | back one screen |
|
|
385
|
-
| "Add this to my cart", "search for shoes", "my cart" | nothing (not an "open" request) |
|
|
386
|
-
|
|
387
|
-
It needs an "open"-style word (open, show, go to, take me to, view …) and a word that names a
|
|
388
|
-
screen. The words come from your route names (`account/addresses` → "addresses", "address");
|
|
389
|
-
dynamic routes like `product/[slug]` are left to the server. Add your own words:
|
|
390
|
-
|
|
391
|
-
```tsx
|
|
392
|
-
<VoiceBotProvider url={URL} options={{ voiceShortcuts: { '(tabs)/cart': ['bag', 'basket'], 'orders/index': ['order history'] } }}>
|
|
393
|
-
```
|
|
394
|
-
|
|
395
|
-
The server's own navigation always wins, and the server still gets `navigate_result` (with
|
|
396
|
-
`requestId: "local"`) and `screen_changed`. Turn it off with `options={{ localNavigation: false }}`.
|
|
397
|
-
|
|
398
|
-
### Expo Router
|
|
399
|
-
|
|
400
|
-
```tsx
|
|
401
|
-
import { useExpoRouterNavigation } from 'react-native-voice-bot-sdk/expo-router';
|
|
402
|
-
|
|
403
|
-
const navigation = useExpoRouterNavigation({ exclude: ['modal'] });
|
|
404
|
-
```
|
|
405
|
-
|
|
406
|
-
Call it in the root `_layout.tsx`. Screen names are the file routes: `index`, `products`,
|
|
407
|
-
`(tabs)/index`, `product/[id]`. The server can pass `params` for dynamic routes.
|
|
408
|
-
|
|
409
|
-
### React Navigation
|
|
410
|
-
|
|
411
|
-
```tsx
|
|
412
|
-
import { NavigationContainer, createNavigationContainerRef } from '@react-navigation/native';
|
|
413
|
-
import { VoiceBotProvider, createReactNavigationAdapter } from 'react-native-voice-bot-sdk';
|
|
414
|
-
|
|
415
|
-
const navigationRef = createNavigationContainerRef();
|
|
416
|
-
const navigation = createReactNavigationAdapter(navigationRef, {
|
|
417
|
-
// Optional. Defaults to the screens of the navigators that are mounted.
|
|
418
|
-
screens: ['Home', 'Products', { name: 'Cart', parents: ['Shop'] }],
|
|
419
|
-
});
|
|
420
|
-
|
|
421
|
-
export default function App() {
|
|
422
|
-
return (
|
|
423
|
-
<VoiceBotProvider url={URL} navigation={navigation}>
|
|
424
|
-
<NavigationContainer ref={navigationRef}>{/* navigators */}</NavigationContainer>
|
|
425
|
-
</VoiceBotProvider>
|
|
426
|
-
);
|
|
427
|
-
}
|
|
428
|
-
```
|
|
429
|
-
|
|
430
|
-
Written for React Navigation 7 (`popTo`).
|
|
431
|
-
|
|
432
|
-
### Your own navigation (callbacks)
|
|
433
|
-
|
|
434
|
-
```tsx
|
|
435
|
-
import { createCallbackNavigation } from 'react-native-voice-bot-sdk';
|
|
436
|
-
|
|
437
|
-
const navigation = createCallbackNavigation({
|
|
438
|
-
screens: ['Home', 'Products', 'Cart'],
|
|
439
|
-
initialScreen: 'Home',
|
|
440
|
-
onNavigate: (screen, { action, params }) => myRouter.open(screen.name, params), // action: 'push' | 'popTo'
|
|
441
|
-
onBack: () => myRouter.back(),
|
|
442
|
-
});
|
|
443
|
-
|
|
444
|
-
// When the user moves by hand, tell the SDK:
|
|
445
|
-
navigation.setCurrentScreen('Cart');
|
|
446
|
-
```
|
|
447
|
-
|
|
448
|
-
## Logs
|
|
449
|
-
|
|
450
|
-
The SDK logs to the console with a `[VoiceBot]` prefix, the time and a level. You see these in
|
|
451
|
-
Metro or in `adb logcat` (tag `ReactNativeJS`):
|
|
452
|
-
|
|
453
|
-
```
|
|
454
|
-
[VoiceBot] 14:41:41.205 INFO connecting to ws://localhost:8091/demo
|
|
455
|
-
[VoiceBot] 14:41:41.512 INFO connected in 307 ms, session=81185a05-ccbf-43be-8ffc-20eae1c65a64
|
|
456
|
-
[VoiceBot] 14:41:41.514 INFO → connect message: domain_id=your-domain cookie_id=a527edd9… deviceId=1 sampleRate=16000 screens(5)=["cart","index","product/[id]","products","profile"]
|
|
457
|
-
[VoiceBot] 14:41:41.520 INFO → screen_changed: "index" backStack=["index"]
|
|
458
|
-
[VoiceBot] 14:41:43.101 INFO mic started: PCM s16le 16000 Hz mono, 640-byte frames (20 ms), uplink=BINARY
|
|
459
|
-
[VoiceBot] 14:41:43.140 INFO → first audio frame sent
|
|
460
|
-
[VoiceBot] 14:41:48.120 INFO → audio streaming: 250 frames (5.00 s)
|
|
461
|
-
[VoiceBot] 14:41:49.002 INFO ← you said: "open my cart"
|
|
462
|
-
[VoiceBot] 14:41:49.003 INFO ← bot: "Opening your cart"
|
|
463
|
-
[VoiceBot] 14:41:49.004 INFO 🔊 bot speaking (reply audio playing)
|
|
464
|
-
[VoiceBot] 14:41:49.010 INFO ← navigate: screen="cart" requestId=1
|
|
465
|
-
[VoiceBot] 14:41:49.030 INFO → navigate_result: opened "cart"
|
|
466
|
-
[VoiceBot] 14:41:49.031 INFO → screen_changed: "cart" backStack=["index","cart"]
|
|
467
|
-
[VoiceBot] 14:41:50.300 INFO 🔇 bot finished speaking (1.20 s of audio)
|
|
468
|
-
[VoiceBot] 14:41:58.400 INFO mic stopped after 15.3 s: sent 765 frames (15.30 s of audio, 489600 bytes)
|
|
469
|
-
[VoiceBot] 14:42:00.000 INFO → closing socket: code=1000 reason="User exited"
|
|
470
|
-
```
|
|
471
|
-
|
|
472
|
-
| Level | What is logged |
|
|
473
|
-
|-------|----------------|
|
|
474
|
-
| `trace` | Everything below, plus **every audio frame** sent (`→ SEND audio frame #123`), 50 lines a second. |
|
|
475
|
-
| `debug` | **Every request and response in full:** each JSON message sent (`→ SEND {...}`) and received (`← RECV {...}`). Base64 audio is replaced by its size (`<base64 42668 chars = 32000 bytes>`); everything else is printed as is. Plus each reply audio chunk. **Default in development.** |
|
|
476
|
-
| `info` | Readable summary: connect, connect message, screens, mic start/stop with frame counts, audio progress every 5 s, what you said, bot reply, speaking start/end, navigate and its result, screen changes, socket close. |
|
|
477
|
-
| `warn` | Problems that don't stop the session: permission denied, dropped frames, unknown screen, abnormal close codes, slow network. **Default in release.** |
|
|
478
|
-
| `error` | Connect failed, mic failed, playback failed, navigation threw. |
|
|
479
|
-
| `none` | Nothing. |
|
|
480
|
-
|
|
481
|
-
```ts
|
|
482
|
-
import { setLogLevel, setLogHandler } from 'react-native-voice-bot-sdk';
|
|
483
|
-
|
|
484
|
-
setLogLevel('debug'); // or VoiceBot.connect({ url, logLevel: 'debug' })
|
|
485
|
-
setLogHandler((level, message) => myCrashReporter.log(`[VoiceBot] ${level} ${message}`));
|
|
486
|
-
```
|
|
487
|
-
|
|
488
|
-
`→` is app to server, `←` is server to app. On Android the native audio module also logs to logcat
|
|
489
|
-
with the tag `VoiceBotAudio` (audio source, echo cancel / gain / noise effects, start and stop):
|
|
490
|
-
|
|
491
|
-
```bash
|
|
492
|
-
adb logcat -s ReactNativeJS VoiceBotAudio
|
|
493
|
-
```
|
|
494
|
-
|
|
495
|
-
## Removing the SDK
|
|
496
|
-
|
|
497
|
-
Remove `<VoiceBotProvider>` (or `<VoiceBotWidget>`) and any `VoiceBot.*` calls, delete the plugin
|
|
498
|
-
entry from `app.json`, `npm uninstall react-native-voice-bot-sdk`, and rebuild the native app.
|
|
111
|
+
Payments should stay on your checkout screen: the assistant can open checkout, and the user pays
|
|
112
|
+
there.
|
|
499
113
|
|
|
500
|
-
##
|
|
114
|
+
## More
|
|
501
115
|
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
with echo cancellation, gain control and noise suppression. Details: [docs/PROTOCOL.md](https://unpkg.com/react-native-voice-bot-sdk/docs/PROTOCOL.md).
|
|
116
|
+
- [Integration guide](https://unpkg.com/react-native-voice-bot-sdk/docs/INTEGRATION.md): all options, testing, troubleshooting
|
|
117
|
+
- [Actions guide](https://unpkg.com/react-native-voice-bot-sdk/docs/ACTIONS.md)
|
|
118
|
+
- [Server protocol](https://unpkg.com/react-native-voice-bot-sdk/docs/PROTOCOL.md), for your voice server team
|
|
119
|
+
- [Changelog](https://unpkg.com/react-native-voice-bot-sdk/CHANGELOG.md)
|
|
507
120
|
|
|
508
121
|
## License
|
|
509
122
|
|
|
@@ -41,10 +41,24 @@ export interface ConnectOptions {
|
|
|
41
41
|
onReply?(reply: BotReply): void;
|
|
42
42
|
/** Start streaming the mic right after connecting. Default `false`. */
|
|
43
43
|
autoStart?: boolean;
|
|
44
|
+
/**
|
|
45
|
+
* Close the socket whenever the mic stops (`stop()`, `toggle()`, a phone call, a mic error), so
|
|
46
|
+
* a voice session lasts exactly from mic on to mic off. Use with `configure()` and `start()`:
|
|
47
|
+
* the mic button connects and starts, and pressing it again stops and disconnects. Default
|
|
48
|
+
* `false` (the socket stays open between turns). `<VoiceBotProvider connectOn="mic">` sets it.
|
|
49
|
+
*/
|
|
50
|
+
disconnectOnStop?: boolean;
|
|
44
51
|
/** Uplink audio format. `binary` (default) = 640-byte BINARY frames. `base64` = `{type:"audio"}` TEXT frames. */
|
|
45
52
|
uplinkEncoding?: 'binary' | 'base64';
|
|
46
53
|
/** `domain_id` in the connect message: your domain / tenant id. Default `""`. */
|
|
47
54
|
domainId?: string;
|
|
55
|
+
/**
|
|
56
|
+
* `user_id` in the connect message: your app's id for the signed-in user, in any format you choose
|
|
57
|
+
* (an email, a phone number, an internal or random id). Sent as is. Default `""` (no user, e.g. a
|
|
58
|
+
* guest). It is never written to the SDK's logs. When it changes (sign in / sign out), connect again so the server gets the new one;
|
|
59
|
+
* `<VoiceBotProvider userId>` does that for you.
|
|
60
|
+
*/
|
|
61
|
+
userId?: string;
|
|
48
62
|
/**
|
|
49
63
|
* `cookie_id` in the connect message: the visitor id. Default: a random id that the SDK saves on
|
|
50
64
|
* the device, so it stays the same across app launches (until the app is uninstalled or its data
|
|
@@ -204,6 +218,12 @@ export declare class VoiceBotClient {
|
|
|
204
218
|
get isListening(): boolean;
|
|
205
219
|
/** Opens the socket, sends the connect message (session info + screens), then calls `onSuccess`. */
|
|
206
220
|
connect: (options: ConnectOptions) => void;
|
|
221
|
+
/**
|
|
222
|
+
* Saves the connection options without connecting. `start()` then connects and starts the mic
|
|
223
|
+
* in one step. With `disconnectOnStop`, this is the mic-button flow: tap = connect + listen,
|
|
224
|
+
* tap again = stop + disconnect.
|
|
225
|
+
*/
|
|
226
|
+
configure: (options: ConnectOptions) => void;
|
|
207
227
|
private open;
|
|
208
228
|
private reconnectEnabled;
|
|
209
229
|
/** Waits (1 s, 2 s, 4 s ... max 30 s) and opens the socket again, keeping the mic running. */
|
|
@@ -228,10 +248,19 @@ export declare class VoiceBotClient {
|
|
|
228
248
|
* `connect()` options first. Resolves to true when the mic is streaming.
|
|
229
249
|
*/
|
|
230
250
|
start: () => Promise<boolean>;
|
|
231
|
-
/**
|
|
251
|
+
/**
|
|
252
|
+
* Stops streaming the mic. The socket stays open, unless `disconnectOnStop` is set: then it also
|
|
253
|
+
* stops the bot's reply and closes the socket.
|
|
254
|
+
*/
|
|
232
255
|
stop: () => void;
|
|
233
|
-
/**
|
|
256
|
+
/**
|
|
257
|
+
* start() when idle, stop() when listening. With `disconnectOnStop`, a press while connecting
|
|
258
|
+
* cancels (disconnects) instead of waiting.
|
|
259
|
+
*/
|
|
234
260
|
toggle: () => Promise<void>;
|
|
261
|
+
/** Mic-button session over: mic, reply audio and socket all stop. */
|
|
262
|
+
private endSession;
|
|
263
|
+
private endSessionIfMicOnly;
|
|
235
264
|
private startBackground;
|
|
236
265
|
private stopRecording;
|
|
237
266
|
/** Every 20 ms mic frame from the native module. */
|
|
@@ -252,6 +281,13 @@ export declare class VoiceBotClient {
|
|
|
252
281
|
private navigateFromReply;
|
|
253
282
|
/** Queues a reply's audio: stops an older reply first, skips a reply the user talked over. */
|
|
254
283
|
private playReplyAudio;
|
|
284
|
+
/**
|
|
285
|
+
* `{type:"tts", data, sample_rate}`: the next piece of the reply that is playing. The server sends
|
|
286
|
+
* the reply message (text and the first audio) first, then the rest of the speech in these
|
|
287
|
+
* chunks; they carry no question, so they belong to the current reply. Dropped when the user
|
|
288
|
+
* talked over that reply.
|
|
289
|
+
*/
|
|
290
|
+
private playStreamedSpeech;
|
|
255
291
|
/** Stops the audio of the previous reply so the reply to a new question plays right away. */
|
|
256
292
|
private interruptPlayback;
|
|
257
293
|
/** The server's reply didn't navigate: open a screen if the user clearly asked for one. */
|
package/build/VoiceBotClient.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AppState as e}from"react-native";import*as t from"./NativeAudio";import{ActionEngine as s}from"./actions/engine";import{ActionRegistry as n}from"./actions/registry";import{NoiseGate as i}from"./audio/noiseGate";import{base64ByteLength as o,base64ToBytes as a,bytesToBase64 as r}from"./base64";import{logger as c,preview as h,setLogLevel as l}from"./logger";import{findLocalIntent as d}from"./navigation/localIntent";import{decideMove as p,dynamicParams as u,matchScreen as g}from"./navigation/match";import{BYTES_PER_SECOND as m,SAMPLE_RATE as f}from"./protocol";function y(){const e=new Uint8Array(16),t=globalThis.crypto;if(t?.getRandomValues)t.getRandomValues(e);else for(let t=0;t<16;t++)e[t]=Math.floor(256*Math.random());e[6]=15&e[6]|64,e[8]=63&e[8]|128;const s=Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}const S=new Uint8Array(640),k=e=>(e/m).toFixed(2),b={1e3:"normal",1001:"going away",1002:"protocol error",1003:"unsupported data",1006:"connection lost (no close frame)",1008:"policy violation",1009:"message too big",1011:"server error"};export class VoiceBotClient{constructor(){this.ws=null,this.options=null,this.state={status:"idle",speaking:!1,sessionId:null,lastQuestion:null,lastPrompt:null,lastError:null,lastMessage:null},this.listeners=new Set,this.messageListeners=new Set,this.navigation=null,this.navUnsubscribe=null,this.lastSentScreen=null,this.screens=[],this.runCookieId=y(),this.wantConnected=!1,this.reconnectAttempt=0,this.reconnectTimer=null,this.reconnectDueAt=0,this.connectDeadline=0,this.onConnectDeadline=null,this.backgroundServiceOn=!1,this.stopMic=null,this.seq=0,this.speakingUntil=0,this.speakingTimer=null,this.connectTimer=null,this.connectStartedAt=0,this.micStartedAt=0,this.framesSent=0,this.framesDropped=0,this.replyCount=0,this.replyAudioSeconds=0,this.lastReplyRate=f,this.lastReplyNavKey=null,this.playingQuestion=null,this.speakingEndedAt=0,this.realPlaybackEnd=t.hasPlaybackIdleEvents(),this.bargedQuestion=null,this.gate=null,this.inCall=!1,this.lastSessionId=null,this.actions=new n,this.lastActionsKey="",this.screenContext=null,this.lastReplyNavAt=0,this.getState=()=>this.state,this.subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)}),this.addMessageListener=e=>(this.messageListeners.add(e),()=>{this.messageListeners.delete(e)}),this.connect=e=>{this.options=e,e.logLevel&&l(e.logLevel),this.wantConnected=!0,this.reconnectAttempt=0,this.clearReconnectTimer(),this.open()},this.disconnect=()=>{this.engine.cancelQueued("The app disconnected before this request started"),this.wantConnected=!1,this.reconnectAttempt=0,this.clearReconnectTimer(),this.stopRecording(),t.stopPlayback(),this.playingQuestion=null,this.closeSocket(1e3,"User exited"),this.setState({status:"idle",sessionId:null,speaking:!1})},this.start=async()=>{if(this.isListening)return!0;if(!this.isConnected)return this.reconnectTimer?(this.reconnectNow(),!1):this.options?("connecting"!==this.state.status?this.connect({...this.options,autoStart:!0}):this.options={...this.options,autoStart:!0},!1):(this.fail({code:"not_connected",message:"Call VoiceBot.connect({ url }) before start()"}),!1);try{if(!await t.requestMicPermission())return c.warn("microphone permission denied"),this.setState({lastError:{code:"mic_permission",message:"Microphone permission denied"}}),!1;this.seq=0,this.framesSent=0,this.framesDropped=0,this.micStartedAt=Date.now();const e="base64"===this.options?.uplinkEncoding,s=this.options?.noiseGate??!0;return this.gate=new i({..."object"==typeof s?s:{},enabled:!1!==s,whileSpeaking:this.options?.whileSpeaking??"mute"}),this.inCall=!1,this.stopMic=await t.startRecording((t=>this.onMicFrame(t,e)),(e=>{c.error(`mic error: ${e}`),this.setState({lastError:{code:"mic_failed",message:e}})})),this.isConnected?(this.setState({status:"listening",lastError:null}),this.startBackground(),c.info(`mic started: PCM s16le ${f} Hz mono, 640-byte frames (20 ms), uplink=${e?"base64 TEXT":"BINARY"}, noise gate ${!1===s?"off":"on"}, while bot speaks: ${this.options?.whileSpeaking??"mute"}, barge-in `+(!0===this.options?.bargeIn?"on":"off")),!0):(this.stopRecording(),!1)}catch(e){return c.error(`mic failed to start: ${e?.message??String(e)}`),this.setState({lastError:{code:"mic_failed",message:e?.message??String(e)}}),!1}},this.stop=()=>{this.stopRecording(),this.isConnected&&this.setState({status:"connected"})},this.toggle=async()=>{this.isListening?this.stop():await this.start()},this.registerAction=(e,t)=>this.actions.register(e,t),this.unregisterAction=e=>this.actions.unregister(e),this.setActions=e=>this.actions.replaceAll(e),this.getActions=()=>this.actions.metadata(),this.setConfirmHandler=e=>{this.confirmHandler=e??void 0},this.setScreenContext=e=>{this.screenContext=e?{screen:this.navigation?.getCurrentScreen()??null,params:e}:null,this.sendScreenChanged()},this.setNavigation=e=>{e!==this.navigation&&(this.navUnsubscribe?.(),this.navUnsubscribe=null,this.navigation=e,e&&(c.info(`navigation registered: ${e.kind}, ${e.getScreens().length} screens`),this.navUnsubscribe=e.subscribe((()=>this.sendScreenChanged())),this.isConnected&&this.state.sessionId&&(this.sendScreensUpdate(this.state.sessionId),this.lastSentScreen=null,this.sendScreenChanged())))},this.handleNavigate=async(e,t=!0)=>{const s="back"===e.action,n={type:"navigate_result",sessionId:this.state.sessionId??"",screen:e.screen??null,action:s?"back":"open",className:null,status:"failed",message:"",requestId:e.requestId??null},i=(e,s="",i=n.className)=>{n.status=e,n.message=s,n.className=i;const o=`→ navigate_result: ${e} ${"back"===n.action?"back":`"${n.screen}"`}`+(i&&i!==n.screen?` → ${i}`:"")+(s?` (${s})`:"");return"failed"===e?c.error(o):"unknown_screen"===e||"not_supported"===e?c.warn(o):c.info(o),t&&this.sendJson(n),n},o=this.navigation;if(!o)return i("not_supported","The app has no navigation registered with the voice bot");try{if(s){const e=o.getCurrentScreen();return await o.goBack()?i("went_back","",e):i("not_supported","Nothing to go back to",e)}if(!e.screen)return i("unknown_screen","No screen given");const t=this.matchScreen(e.screen);if(!t)return i("unknown_screen",`Not in the screens list: ${e.screen}`,null);const n=t.screen,a={...t.params??{},...e.params??{}},r=Object.keys(a).length?a:void 0,h=u(n.name).filter((e=>void 0===r?.[e]||""===r[e]));if(h.length){const e=n.name.replace(/\[(?:\.\.\.)?([^\]]+)\]/g,((e,t)=>`<${t}>`));return i("failed",`${n.name} needs ${h.join(", ")}: send "screen": "${e.replace(/^\(.*?\)\//,"")}" or "params": { ${h.map((e=>`"${e}": "…"`)).join(", ")} }`,n.name)}const l=o.getCurrentScreen(),d=o.getBackStack(),g=p(n.name,l,d,!!r);if("already_on_screen"===g)return i("already_on_screen","",n.name);"popTo"===g?await o.popTo(n,r):await o.push(n,r),c.debug(`navigate: ${g} ${n.name}${r?` ${JSON.stringify(r)}`:""} (from ${l??"-"})`);let m=await this.waitForScreen(o,n.name,l,!!r);return m!==n.name&&o.navigate&&(c.warn(`navigate: ${g} didn't reach ${n.name} (still on ${m??"-"}), trying navigate`),await o.navigate(n,r),m=await this.waitForScreen(o,n.name,l,!!r)),m!==n.name?i("failed",`Navigation didn't reach ${n.name}; the app is on ${m??"an unknown screen"}`,n.name):i("opened","",n.name)}catch(e){return i("failed",e?.message??String(e))}},this.engine=new s({registry:this.actions,navigate:(e,t)=>this.navigateForStep(e,t),getConfirmHandler:()=>this.confirmHandler,send:e=>this.trySend(e),sessionId:()=>this.state.sessionId??this.lastSessionId??"",log:{debug:e=>c.debug(e),info:e=>c.info(e),warn:e=>c.warn(e),error:e=>c.error(e)}}),this.actions.onChange((()=>this.sendActionsUpdate())),t.onInterruption((e=>this.handleInterruption(e))),t.onPlaybackIdle((()=>this.finishSpeaking("playback ended")));try{e.addEventListener("change",(e=>{"active"===e&&this.reconnectTimer&&(c.info("app is active again: reconnecting now"),this.reconnectNow())}))}catch{}}setState(e){this.state={...this.state,...e},this.listeners.forEach((e=>e()))}get isConnected(){return"connected"===this.state.status||"listening"===this.state.status}get isListening(){return"listening"===this.state.status}open(){const e=this.options;this.ws&&this.closeSocket(1e3,"Reconnecting");const{url:s}=e,n=this.reconnectAttempt>0;if(!t.isNativeAvailable())return void this.fail({code:"native_missing",message:t.NATIVE_MISSING_MESSAGE});this.setState({status:"connecting",lastError:null}),this.connectStartedAt=Date.now(),c.info(`connecting to ${s}`);let i=!1;const o=new WebSocket(s);o.binaryType="arraybuffer",this.ws=o;const a=e.connectTimeoutMs??1e4,r=()=>{i||this.ws!==o||(this.closeSocket(1e3,"Connect timeout"),n?this.scheduleReconnect(`timed out connecting to ${s}`):this.fail({code:"connect_timeout",message:`Timed out connecting to ${s}`}))};this.connectTimer=setTimeout(r,a),this.connectDeadline=Date.now()+a,this.onConnectDeadline=r,o.onopen=()=>{if(this.ws!==o)return;i=!0,this.clearConnectTimer();const t=n&&e.keepSessionOnReconnect&&this.lastSessionId?this.lastSessionId:y();this.lastSessionId=t,this.replyCount=0,this.lastReplyNavKey=null;const s=null!=this.stopMic;this.setState({status:s?"listening":"connected",sessionId:t,lastError:null}),c.info((n?`reconnected (attempt ${this.reconnectAttempt})`:"connected")+" in "+`${Date.now()-this.connectStartedAt} ms, session=${t}`+(n&&s?`, mic kept running (${this.framesDropped} frames dropped while offline)`:"")),this.reconnectAttempt=0,this.sendConnectMessage(t),this.lastSentScreen=null,this.sendScreenChanged(),this.engine.flush(),e.onSuccess?.({sessionId:t}),e.autoStart&&this.start()},o.onmessage=e=>{this.ws===o&&("string"==typeof e.data?this.handleText(e.data):c.debug(`← RECV binary message ignored (${e.data?.byteLength??"?"} bytes)`))},o.onerror=e=>{this.ws===o&&(e?.message&&c.warn(`socket error: ${e.message}`),i||setTimeout((()=>{if(this.ws!==o)return;this.clearConnectTimer(),this.ws=null;const t=e?.message||`Could not connect to ${s}`;n?this.scheduleReconnect(t):this.fail({code:"connect_failed",message:t})}),500))},o.onclose=t=>{if(this.ws!==o)return;if(this.ws=null,this.clearConnectTimer(),!i){const e=t.reason||`Could not connect to ${s}`;let i="";return/trust anchor|certificate|CertPath|SSL|handshake/i.test(e)?i=" (TLS: the server certificate is not trusted by the phone, e.g. self-signed. Use a certificate from a public CA, or ws:// for testing)":/refused/i.test(e)?i=" (nothing listening on that host/port)":/timeout|timed out|unreachable|no route/i.test(e)?i=" (host not reachable from the phone)":/cleartext/i.test(e)&&(i=" (ws:// is blocked: set allowCleartextTraffic in the config plugin)"),n?void this.scheduleReconnect(e+i):(this.stopRecording(),void this.fail({code:"connect_failed",message:e+i}))}const a=t.code??1006,r=`socket closed: code=${a} (${b[a]??"unknown"})${t.reason?` reason="${t.reason}"`:""}`;if(1e3===a?c.info(r):c.warn(r),e.onClose?.({code:a,reason:t.reason??""}),1e3!==a&&this.wantConnected&&this.reconnectEnabled())return this.setState({sessionId:null}),void this.scheduleReconnect(r);this.stopRecording(),this.setState({status:"idle",sessionId:null})}}reconnectEnabled(){return!1!==this.options?.autoReconnect}scheduleReconnect(e){const t="object"==typeof this.options?.autoReconnect?this.options.autoReconnect:{},s=t.maxAttempts??20,n=t.maxDelayMs??3e4;if(!this.wantConnected)return;if(this.reconnectAttempt>=s)return c.error(`giving up after ${this.reconnectAttempt} reconnect attempts (${e})`),this.reconnectAttempt=0,this.stopRecording(),void this.fail({code:"connect_failed",message:`Reconnect failed: ${e}`});this.reconnectAttempt++;const i=Math.min(n,1e3*2**(this.reconnectAttempt-1));c.warn(`reconnecting in ${(i/1e3).toFixed(0)} s (attempt ${this.reconnectAttempt}/${s}): ${e}`),this.setState({status:"connecting",sessionId:null}),this.options?.onReconnecting?.({attempt:this.reconnectAttempt,delayMs:i}),this.clearReconnectTimer(),this.reconnectDueAt=Date.now()+i,this.reconnectTimer=setTimeout((()=>{this.reconnectTimer=null,this.reconnectDueAt=0,this.wantConnected&&this.open()}),i)}reconnectNow(){this.reconnectTimer&&(this.clearReconnectTimer(),this.wantConnected&&this.open())}clearReconnectTimer(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.reconnectDueAt=0}closeSocket(e,t){const s=this.ws;if(this.ws=null,this.clearConnectTimer(),s){c.info(`→ closing socket: code=${e} reason="${t}"`);try{s.close(e,t)}catch{}}}clearConnectTimer(){this.connectTimer&&clearTimeout(this.connectTimer),this.connectTimer=null,this.connectDeadline=0,this.onConnectDeadline=null}tick(){const e=Date.now();if(this.reconnectDueAt&&e>=this.reconnectDueAt)this.reconnectNow();else if(this.connectDeadline&&e>=this.connectDeadline){const e=this.onConnectDeadline;this.clearConnectTimer(),e?.()}}fail(e){c.error(`${e.code}: ${e.message}`),this.setState({status:"idle",sessionId:null,lastError:e}),this.options?.onFailure?.(e)}sendJson(e){if(this.ws&&this.ws.readyState===WebSocket.OPEN){const t=JSON.stringify(e);c.debug(`→ SEND ${h(t)}`),this.ws.send(t)}else c.warn(`not sent (socket not open): ${h(e,120)}`)}sendConnectMessage(e){this.screens=this.navigation?.getScreens()??[];const t={sessionId:e,domain_id:this.options?.domainId??"",cookie_id:this.options?.cookieId||this.getSavedCookieId()||this.runCookieId,type:"Buffer",deviceId:this.options?.deviceId??1,sampleRate:f,screens:this.screens.map((e=>e.name))},s=this.actions.metadata();var n;s.length&&(t.actions=s),this.lastActionsKey=JSON.stringify(s),c.info(`→ connect message: domain_id=${t.domain_id||'""'} cookie_id=${n=t.cookie_id,n?`${n.slice(0,8)}…`:"-"} deviceId=${t.deviceId} sampleRate=${t.sampleRate} screens(${t.screens.length})=${JSON.stringify(t.screens)}`),s.length&&c.info(`→ actions(${s.length}): ${s.map((e=>e.name+(e.confirm?" (confirm)":""))).join(", ")}`),t.screens.length||c.warn("no screens sent: register navigation on <VoiceBotProvider navigation={...}> to enable voice navigation"),this.sendJson(t)}getSavedCookieId(){return void 0===this.savedCookieId&&(this.savedCookieId=t.getPersistentId("cookie_id")),this.savedCookieId}sendScreensUpdate(e){const t=this.screens.map((e=>e.name)).join("\n");this.screens=this.navigation?.getScreens()??[];const s=this.screens.map((e=>e.name));if(s.join("\n")===t)return;const n={type:"screens",sessionId:e,screens:s};c.info(`→ screens update (${s.length}): ${JSON.stringify(s)}`),this.sendJson(n)}async startBackground(){const e=this.options?.backgroundListening??!0;if(!1===e)return;const s="object"==typeof e&&e.title||"Voice assistant",n="object"==typeof e&&e.text||"Listening…",i=await t.startBackgroundService(s,n);!i||this.stopMic?(this.backgroundServiceOn=i,i&&c.info("background listening on (notification shown while the mic is on)")):t.stopBackgroundService()}stopRecording(){if(this.backgroundServiceOn&&(this.backgroundServiceOn=!1,t.stopBackgroundService()),this.stopMic){const e=this.gate?.flush()??[],s="base64"===this.options?.uplinkEncoding;e.forEach((e=>this.sendFrameBytes(e,s))),this.gate=null,t.stopRecording(),this.stopMic(),this.stopMic=null;const n=Date.now()-this.micStartedAt;c.info(`mic stopped after ${(n/1e3).toFixed(1)} s: sent ${this.framesSent} frames (${k(640*this.framesSent)} s of audio, ${640*this.framesSent} bytes)`+(this.framesDropped?`, dropped ${this.framesDropped} (socket not open)`:""))}}onMicFrame(e,t){this.tick();let s=a(e);if(this.inCall)s=S;else if(this.gate){const e=this.gate.process(s,this.botAudible());void 0!==e.speechEvent&&c.debug(e.speechEvent?`🗣 speech started (level ${this.gate.levelDb.toFixed(0)} dBFS, room ${this.gate.noiseFloorDb.toFixed(0)} dBFS)`:"… speech ended"),e.bargeIn&&!0===this.options?.bargeIn&&this.bargeIn(),s=e.out}s&&this.sendFrameBytes(s,t)}sendFrameBytes(e,t){const s=this.ws;if(!s||s.readyState!==WebSocket.OPEN)return this.framesDropped++,void(1===this.framesDropped&&c.warn("mic frame dropped: socket not open"));if(this.framesSent++,c.isEnabled("trace")&&c.trace(`→ SEND audio frame #${this.framesSent} (640 bytes, ${t?"base64 TEXT":"BINARY"})`),1===this.framesSent)c.info("→ first audio frame sent");else if(this.framesSent%250==0){const e=s.bufferedAmount??0,t=this.gate;c.info(`→ audio streaming: ${this.framesSent} frames (${k(640*this.framesSent)} s)`+(this.framesDropped?`, dropped ${this.framesDropped}`:"")+(t?`, speech ${(100*t.openRatio).toFixed(0)}% / silence ${(100-100*t.openRatio).toFixed(0)}%, room ${t.noiseFloorDb.toFixed(0)} dBFS`:"")+(this.inCall?", in a call (sending silence)":"")+(e>32e3?`, ${e} bytes waiting to send (slow network?)`:""))}t?s.send(JSON.stringify({type:"audio",sessionId:this.state.sessionId,seq:this.seq++,sampleRate:f,data:r(e)})):s.send(function(e){return 0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer}(e))}bargeIn(){this.state.speaking&&(t.stopPlayback(),c.info(`✋ barge-in: you started talking, stopped the reply to "${this.playingQuestion??""}"`),this.bargedQuestion=this.playingQuestion,this.stopSpeakingState())}stopSpeakingState(){this.speakingUntil=Date.now(),this.state.speaking&&(this.speakingEndedAt=Date.now()),this.speakingTimer&&clearTimeout(this.speakingTimer),this.speakingTimer=null,this.playingQuestion=null,t.releaseAudioFocus(),this.state.speaking&&this.setState({speaking:!1})}handleInterruption(e){if("focus_lost"===e)this.state.speaking&&c.info("🔇 another app took the audio: stopped the bot's reply"),this.stopSpeakingState();else if("call_started"===e){if(!1===this.options?.pauseOnCall||!this.stopMic)return;this.inCall=!0,this.stopSpeakingState(),c.info("📞 phone call: bot audio stopped, the mic sends silence until the call ends")}else"call_ended"===e&&this.inCall&&(this.inCall=!1,c.info("📞 call ended: mic audio resumed"))}handleText(e){let t;try{t=JSON.parse(e)}catch{return void c.warn(`← non-JSON text ignored: ${h(e,120)}`)}if(c.debug(`← RECV ${h(e)}`),!t||"object"!=typeof t)return;if(this.messageListeners.forEach((e=>e(t))),this.setState({lastMessage:t}),"actions"===t.type)return void this.engine.handle(t);if("cancel_actions"===t.type)return void(this.engine.cancel(t.requestId)||c.warn(`← cancel_actions ${t.requestId}: nothing running with that id`));if("action_ack"===t.type)return void this.engine.ack(t.requestId);if("navigate"===t.type)return c.info("← navigate: "+("back"===t.action?"back":`screen="${t.screen}"`)+(t.params?` params=${JSON.stringify(t.params)}`:"")+(null!=t.requestId?` requestId=${t.requestId}`:"")),void this.handleNavigate(t);const s=t;if("string"==typeof s.output)try{s.output=JSON.parse(s.output)}catch{}this.replyCount++;const n=this.state.lastQuestion,i=this.state.lastPrompt;"string"==typeof s.buffer&&s.buffer.length>0&&this.playReplyAudio(s,s.buffer);const o={};"string"==typeof s.question&&s.question&&(o.lastQuestion=s.question);const a=s.output?.prompt;"string"==typeof a&&a&&(o.lastPrompt=a),o.lastQuestion&&o.lastQuestion!==n&&c.info(`← you said: "${o.lastQuestion}"`),o.lastPrompt&&o.lastPrompt!==i&&c.info(`← bot: "${o.lastPrompt}"`);const r=s.output?.error;r&&0!==r&&"0"!==r&&c.warn(`← server reported error: ${h(s.output,200)}`),s.buffer||o.lastQuestion||o.lastPrompt||c.info(`← message: ${h(t,200)}`),Object.keys(o).length&&this.setState(o),this.navigateFromReply(s),this.options?.onReply?.(s)}navigateFromReply(e){const t=e.output;if(!t||"object"!=typeof t)return void this.localNavigate(e);const s=e=>"string"==typeof e?e.trim():"",n=s(t.type).toLowerCase(),i=s(t.intent).toLowerCase(),o=s(t.screen)||s(t.class_name)||s(t.target),a="back"===n||/^(back|go_back|goback)$/i.test(o);if(!(a||o&&("navigation"===n||"navigate"===n||"navigate"===i||a||this.matchScreen(o))))return void this.localNavigate(e);const r=`${e.question??""}|${a?"back":o}`,h=Date.now();r===this.lastReplyNavKey&&h-this.lastReplyNavAt<3e3||(this.lastReplyNavKey=r,this.lastReplyNavAt=h,c.info(`← reply asks for ${a?"back":`screen "${o}"`} (type="${s(t.type)}" intent="${s(t.intent)}" screen="${s(t.screen)}" class_name="${s(t.class_name)}" target="${s(t.target)}")`),this.handleNavigate(a?{type:"navigate",action:"back"}:{type:"navigate",screen:o}))}playReplyAudio(e,s){const n="string"==typeof e.question?e.question.trim():"";if(n&&n===this.bargedQuestion)c.debug(`← reply #${this.replyCount}: audio not played (you talked over "${n}")`);else{n&&(this.bargedQuestion=null);try{const i=o(s);n&&n!==this.playingQuestion&&(this.state.speaking&&!1!==this.options?.interruptOnNewReply&&this.interruptPlayback(n),this.playingQuestion=n,this.gate?.newReply()),i%2&&c.warn(`reply audio chunk has an odd byte count (${i}); last byte dropped`);const a=function(e){const t=e.output,s=Number(e.sample_rate??e.sampleRate??t?.sample_rate??t?.sampleRate);return Number.isFinite(s)&&s>=8e3&&s<=48e3?Math.round(s):f}(e);a!==this.lastReplyRate&&(c.info(`reply audio sample rate: ${a} Hz${a===f?" (default)":" (from the server)"}`),this.lastReplyRate=a),t.enqueuePlayback(s,a);const r=i/(2*a);c.debug(`← reply #${this.replyCount}: audio chunk ${i} bytes (${r.toFixed(2)} s at ${a} Hz) queued`),this.markSpeaking(r)}catch(e){c.error(`playback failed: ${e?.message??String(e)}`),this.setState({lastError:{code:"playback_failed",message:e?.message??String(e)}})}}}interruptPlayback(e){const s=Math.max(0,this.speakingUntil-Date.now())/1e3;t.stopPlayback(),c.info(`⏹ stopped old reply audio (${s.toFixed(1)} s left of "${this.playingQuestion??""}") for new reply to "${e}"`),this.speakingUntil=Date.now(),this.replyAudioSeconds=0}localNavigate(e){if(!1===this.options?.localNavigation||!this.navigation)return;const t="string"==typeof e.question?e.question.trim():"";if(!t)return;const s=this.screens.length?this.screens:this.navigation.getScreens(),n=d(t,s,this.options?.voiceShortcuts);if(!n)return;const i="back"===n.action?"back":n.screen,o=`${t}|local|${i}`,a=Date.now();o===this.lastReplyNavKey&&a-this.lastReplyNavAt<3e3||(this.lastReplyNavKey=o,this.lastReplyNavAt=a,c.info(`🧭 local shortcut: "${t}" → ${i} (the server's reply didn't navigate)`),this.handleNavigate("back"===n.action?{type:"navigate",action:"back",requestId:"local"}:{type:"navigate",screen:n.screen,requestId:"local"}))}markSpeaking(e){const t=Date.now();this.speakingUntil=Math.max(this.speakingUntil,t)+1e3*e,this.state.speaking||(this.replyAudioSeconds=0,c.info("🔊 bot speaking (reply audio playing)"),this.setState({speaking:!0})),this.replyAudioSeconds+=e,this.speakingTimer&&clearTimeout(this.speakingTimer);const s=this.realPlaybackEnd?3e3:250;this.speakingTimer=setTimeout((()=>this.finishSpeaking(this.realPlaybackEnd?"fallback timer":"estimated")),this.speakingUntil-t+s)}finishSpeaking(e){this.state.speaking&&(this.speakingTimer&&clearTimeout(this.speakingTimer),this.speakingTimer=null,c.info(`🔇 bot finished speaking (${this.replyAudioSeconds.toFixed(2)} s of audio, ${e})`),this.playingQuestion=null,this.speakingEndedAt=Date.now(),t.releaseAudioFocus(),this.setState({speaking:!1}))}botAudible(){if(this.state.speaking)return!0;const e=this.options?.echoTailMs??600;return Date.now()-this.speakingEndedAt<e}trySend(e){return!(!this.ws||this.ws.readyState!==WebSocket.OPEN||!this.state.sessionId||(this.sendJson(e),0))}sendActionsUpdate(){if(!this.isConnected||!this.state.sessionId)return;const e=this.actions.metadata(),t=JSON.stringify(e);t!==this.lastActionsKey&&(this.lastActionsKey=t,c.info(`→ actions_update (${e.length}): ${e.map((e=>e.name)).join(", ")}`),this.sendJson({type:"actions_update",sessionId:this.state.sessionId,actions:e}))}async navigateForStep(e,t){const s="back"===e?{type:"navigate",action:"back"}:{type:"navigate",screen:e,params:t},n=await this.handleNavigate(s,!1);return{status:n.status,screen:n.className,message:n.message}}currentScreenParams(e){const t={...this.navigation?.getCurrentParams?.()??{}};this.screenContext&&(null===this.screenContext.screen||this.screenContext.screen===e?Object.assign(t,this.screenContext.params):this.screenContext=null);const s={};let n=0;for(const[e,i]of Object.entries(t))if(!(n>=20||e.startsWith("__")||"screen"===e||"params"===e)){if("string"==typeof i&&i.length<=200)s[e]=i;else if("number"==typeof i&&Number.isFinite(i))s[e]=i;else{if("boolean"!=typeof i)continue;s[e]=i}n++}return n?s:void 0}sendScreenChanged(){if(!this.isConnected||!this.navigation||!this.state.sessionId)return;const e=this.navigation.getCurrentScreen();if(!e)return;const t=this.navigation.getBackStack(),s=this.currentScreenParams(e),n=`${e}|${t.join(",")}|${s?JSON.stringify(s):""}`;if(n===this.lastSentScreen)return;this.lastSentScreen=n;const i={type:"screen_changed",sessionId:this.state.sessionId,screen:e,backStack:t};s&&(i.params=s),c.info(`→ screen_changed: "${e}" backStack=${JSON.stringify(t)}${s?` params=${JSON.stringify(s)}`:""}`),this.sendJson(i)}async waitForScreen(t,s,n,i){const o=()=>t.getCurrentScreen();if(e.currentState&&"active"!==e.currentState)return s;for(let e=0;e<30;e++){const e=o();if(e===s&&(e!==n||i))return e;await new Promise((e=>setTimeout((()=>e()),50)))}return o()}matchScreen(e){const t=this.screens.length?this.screens:this.navigation?.getScreens()??[];return g(t,e)}}export const VoiceBot=new VoiceBotClient;
|
|
1
|
+
import{AppState as e}from"react-native";import*as t from"./NativeAudio";import{ActionEngine as s}from"./actions/engine";import{ActionRegistry as n}from"./actions/registry";import{NoiseGate as i}from"./audio/noiseGate";import{base64ByteLength as o,base64ToBytes as a,bytesToBase64 as r}from"./base64";import{logger as c,preview as h,setLogLevel as l}from"./logger";import{findLocalIntent as d}from"./navigation/localIntent";import{decideMove as p,dynamicParams as u,matchScreen as g}from"./navigation/match";import{BYTES_PER_SECOND as m,SAMPLE_RATE as f}from"./protocol";function y(){const e=new Uint8Array(16),t=globalThis.crypto;if(t?.getRandomValues)t.getRandomValues(e);else for(let t=0;t<16;t++)e[t]=Math.floor(256*Math.random());e[6]=15&e[6]|64,e[8]=63&e[8]|128;const s=Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}const S=new Uint8Array(640),k=e=>e.replace(/"user_id":"(?:[^"\\]|\\.)+"/g,'"user_id":"(hidden)"'),b=e=>(e/m).toFixed(2),v={1e3:"normal",1001:"going away",1002:"protocol error",1003:"unsupported data",1006:"connection lost (no close frame)",1008:"policy violation",1009:"message too big",1011:"server error"};export class VoiceBotClient{constructor(){this.ws=null,this.options=null,this.state={status:"idle",speaking:!1,sessionId:null,lastQuestion:null,lastPrompt:null,lastError:null,lastMessage:null},this.listeners=new Set,this.messageListeners=new Set,this.navigation=null,this.navUnsubscribe=null,this.lastSentScreen=null,this.screens=[],this.runCookieId=y(),this.wantConnected=!1,this.reconnectAttempt=0,this.reconnectTimer=null,this.reconnectDueAt=0,this.connectDeadline=0,this.onConnectDeadline=null,this.backgroundServiceOn=!1,this.stopMic=null,this.seq=0,this.speakingUntil=0,this.speakingTimer=null,this.connectTimer=null,this.connectStartedAt=0,this.micStartedAt=0,this.framesSent=0,this.framesDropped=0,this.replyCount=0,this.replyAudioSeconds=0,this.lastReplyRate=f,this.lastReplyNavKey=null,this.playingQuestion=null,this.speakingEndedAt=0,this.realPlaybackEnd=t.hasPlaybackIdleEvents(),this.bargedQuestion=null,this.gate=null,this.inCall=!1,this.lastSessionId=null,this.actions=new n,this.lastActionsKey="",this.screenContext=null,this.lastReplyNavAt=0,this.getState=()=>this.state,this.subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)}),this.addMessageListener=e=>(this.messageListeners.add(e),()=>{this.messageListeners.delete(e)}),this.connect=e=>{this.options=e,e.logLevel&&l(e.logLevel),this.wantConnected=!0,this.reconnectAttempt=0,this.clearReconnectTimer(),this.open()},this.configure=e=>{this.options=e,e.logLevel&&l(e.logLevel)},this.disconnect=()=>{this.engine.cancelQueued("The app disconnected before this request started"),this.wantConnected=!1,this.reconnectAttempt=0,this.clearReconnectTimer(),this.stopRecording(),t.stopPlayback(),this.stopSpeakingState(),this.playingQuestion=null,this.closeSocket(1e3,"User exited"),this.setState({status:"idle",sessionId:null,speaking:!1})},this.start=async()=>{if(this.isListening)return!0;if(!this.isConnected)return this.reconnectTimer?(this.reconnectNow(),!1):this.options?("connecting"!==this.state.status?this.connect({...this.options,autoStart:!0}):this.options={...this.options,autoStart:!0},!1):(this.fail({code:"not_connected",message:"Call VoiceBot.connect({ url }) before start()"}),!1);try{if(!await t.requestMicPermission())return c.warn("microphone permission denied"),this.setState({lastError:{code:"mic_permission",message:"Microphone permission denied"}}),this.endSessionIfMicOnly("no microphone permission"),!1;this.seq=0,this.framesSent=0,this.framesDropped=0,this.micStartedAt=Date.now();const e="base64"===this.options?.uplinkEncoding,s=this.options?.noiseGate??!0;return this.gate=new i({..."object"==typeof s?s:{},enabled:!1!==s,whileSpeaking:this.options?.whileSpeaking??"mute"}),this.inCall=!1,this.stopMic=await t.startRecording((t=>this.onMicFrame(t,e)),(e=>{c.error(`mic error: ${e}`),this.setState({lastError:{code:"mic_failed",message:e}}),this.endSessionIfMicOnly("mic error")})),this.isConnected?this.options?.disconnectOnStop&&!this.wantConnected?(this.stopRecording(),!1):(this.setState({status:"listening",lastError:null}),this.startBackground(),c.info(`mic started: PCM s16le ${f} Hz mono, 640-byte frames (20 ms), uplink=${e?"base64 TEXT":"BINARY"}, noise gate ${!1===s?"off":"on"}, while bot speaks: ${this.options?.whileSpeaking??"mute"}, barge-in `+(!0===this.options?.bargeIn?"on":"off")),!0):(this.stopRecording(),!1)}catch(e){return c.error(`mic failed to start: ${e?.message??String(e)}`),this.setState({lastError:{code:"mic_failed",message:e?.message??String(e)}}),this.endSessionIfMicOnly("the mic failed to start"),!1}},this.stop=()=>{this.options?.disconnectOnStop?this.endSession("mic stopped"):(this.stopRecording(),this.isConnected&&this.setState({status:"connected"}))},this.toggle=async()=>{this.isListening?this.stop():this.options?.disconnectOnStop&&("connecting"===this.state.status||this.reconnectTimer)?this.endSession("cancelled while connecting"):await this.start()},this.registerAction=(e,t)=>this.actions.register(e,t),this.unregisterAction=e=>this.actions.unregister(e),this.setActions=e=>this.actions.replaceAll(e),this.getActions=()=>this.actions.metadata(),this.setConfirmHandler=e=>{this.confirmHandler=e??void 0},this.setScreenContext=e=>{this.screenContext=e?{screen:this.navigation?.getCurrentScreen()??null,params:e}:null,this.sendScreenChanged()},this.setNavigation=e=>{e!==this.navigation&&(this.navUnsubscribe?.(),this.navUnsubscribe=null,this.navigation=e,e&&(c.info(`navigation registered: ${e.kind}, ${e.getScreens().length} screens`),this.navUnsubscribe=e.subscribe((()=>this.sendScreenChanged())),this.isConnected&&this.state.sessionId&&(this.sendScreensUpdate(this.state.sessionId),this.lastSentScreen=null,this.sendScreenChanged())))},this.handleNavigate=async(e,t=!0)=>{const s="back"===e.action,n={type:"navigate_result",sessionId:this.state.sessionId??"",screen:e.screen??null,action:s?"back":"open",className:null,status:"failed",message:"",requestId:e.requestId??null},i=(e,s="",i=n.className)=>{n.status=e,n.message=s,n.className=i;const o=`→ navigate_result: ${e} ${"back"===n.action?"back":`"${n.screen}"`}`+(i&&i!==n.screen?` → ${i}`:"")+(s?` (${s})`:"");return"failed"===e?c.error(o):"unknown_screen"===e||"not_supported"===e?c.warn(o):c.info(o),t&&this.sendJson(n),n},o=this.navigation;if(!o)return i("not_supported","The app has no navigation registered with the voice bot");try{if(s){const e=o.getCurrentScreen();return await o.goBack()?i("went_back","",e):i("not_supported","Nothing to go back to",e)}if(!e.screen)return i("unknown_screen","No screen given");const t=this.matchScreen(e.screen);if(!t)return i("unknown_screen",`Not in the screens list: ${e.screen}`,null);const n=t.screen,a={...t.params??{},...e.params??{}},r=Object.keys(a).length?a:void 0,h=u(n.name).filter((e=>void 0===r?.[e]||""===r[e]));if(h.length){const e=n.name.replace(/\[(?:\.\.\.)?([^\]]+)\]/g,((e,t)=>`<${t}>`));return i("failed",`${n.name} needs ${h.join(", ")}: send "screen": "${e.replace(/^\(.*?\)\//,"")}" or "params": { ${h.map((e=>`"${e}": "…"`)).join(", ")} }`,n.name)}const l=o.getCurrentScreen(),d=o.getBackStack(),g=p(n.name,l,d,!!r);if("already_on_screen"===g)return i("already_on_screen","",n.name);"popTo"===g?await o.popTo(n,r):await o.push(n,r),c.debug(`navigate: ${g} ${n.name}${r?` ${JSON.stringify(r)}`:""} (from ${l??"-"})`);let m=await this.waitForScreen(o,n.name,l,!!r);return m!==n.name&&o.navigate&&(c.warn(`navigate: ${g} didn't reach ${n.name} (still on ${m??"-"}), trying navigate`),await o.navigate(n,r),m=await this.waitForScreen(o,n.name,l,!!r)),m!==n.name?i("failed",`Navigation didn't reach ${n.name}; the app is on ${m??"an unknown screen"}`,n.name):i("opened","",n.name)}catch(e){return i("failed",e?.message??String(e))}},this.engine=new s({registry:this.actions,navigate:(e,t)=>this.navigateForStep(e,t),getConfirmHandler:()=>this.confirmHandler,send:e=>this.trySend(e),sessionId:()=>this.state.sessionId??this.lastSessionId??"",log:{debug:e=>c.debug(e),info:e=>c.info(e),warn:e=>c.warn(e),error:e=>c.error(e)}}),this.actions.onChange((()=>this.sendActionsUpdate())),t.onInterruption((e=>this.handleInterruption(e))),t.onPlaybackIdle((()=>this.finishSpeaking("playback ended")));try{e.addEventListener("change",(e=>{"active"===e&&this.reconnectTimer&&(c.info("app is active again: reconnecting now"),this.reconnectNow())}))}catch{}}setState(e){this.state={...this.state,...e},this.listeners.forEach((e=>e()))}get isConnected(){return"connected"===this.state.status||"listening"===this.state.status}get isListening(){return"listening"===this.state.status}open(){const e=this.options;this.ws&&this.closeSocket(1e3,"Reconnecting");const{url:s}=e,n=this.reconnectAttempt>0;if(!t.isNativeAvailable())return void this.fail({code:"native_missing",message:t.NATIVE_MISSING_MESSAGE});this.setState({status:"connecting",lastError:null}),this.connectStartedAt=Date.now(),c.info(`connecting to ${s}`);let i=!1;const o=new WebSocket(s);o.binaryType="arraybuffer",this.ws=o;const a=e.connectTimeoutMs??1e4,r=()=>{i||this.ws!==o||(this.closeSocket(1e3,"Connect timeout"),n?this.scheduleReconnect(`timed out connecting to ${s}`):this.fail({code:"connect_timeout",message:`Timed out connecting to ${s}`}))};this.connectTimer=setTimeout(r,a),this.connectDeadline=Date.now()+a,this.onConnectDeadline=r,o.onopen=()=>{if(this.ws!==o)return;i=!0,this.clearConnectTimer();const t=n&&e.keepSessionOnReconnect&&this.lastSessionId?this.lastSessionId:y();this.lastSessionId=t,this.replyCount=0,this.lastReplyNavKey=null;const s=null!=this.stopMic;this.setState({status:s?"listening":"connected",sessionId:t,lastError:null}),c.info((n?`reconnected (attempt ${this.reconnectAttempt})`:"connected")+" in "+`${Date.now()-this.connectStartedAt} ms, session=${t}`+(n&&s?`, mic kept running (${this.framesDropped} frames dropped while offline)`:"")),this.reconnectAttempt=0,this.sendConnectMessage(t),this.lastSentScreen=null,this.sendScreenChanged(),this.engine.flush(),e.onSuccess?.({sessionId:t}),e.autoStart&&this.start()},o.onmessage=e=>{this.ws===o&&("string"==typeof e.data?this.handleText(e.data):c.debug(`← RECV binary message ignored (${e.data?.byteLength??"?"} bytes)`))},o.onerror=e=>{this.ws===o&&(e?.message&&c.warn(`socket error: ${e.message}`),i||setTimeout((()=>{if(this.ws!==o)return;this.clearConnectTimer(),this.ws=null;const t=e?.message||`Could not connect to ${s}`;n?this.scheduleReconnect(t):this.fail({code:"connect_failed",message:t})}),500))},o.onclose=t=>{if(this.ws!==o)return;if(this.ws=null,this.clearConnectTimer(),!i){const e=t.reason||`Could not connect to ${s}`;let i="";return/trust anchor|certificate|CertPath|SSL|handshake/i.test(e)?i=" (TLS: the server certificate is not trusted by the phone, e.g. self-signed. Use a certificate from a public CA, or ws:// for testing)":/refused/i.test(e)?i=" (nothing listening on that host/port)":/timeout|timed out|unreachable|no route/i.test(e)?i=" (host not reachable from the phone)":/cleartext/i.test(e)&&(i=" (ws:// is blocked: set allowCleartextTraffic in the config plugin)"),n?void this.scheduleReconnect(e+i):(this.stopRecording(),void this.fail({code:"connect_failed",message:e+i}))}const a=t.code??1006,r=`socket closed: code=${a} (${v[a]??"unknown"})${t.reason?` reason="${t.reason}"`:""}`;if(1e3===a?c.info(r):c.warn(r),e.onClose?.({code:a,reason:t.reason??""}),1e3!==a&&this.wantConnected&&this.reconnectEnabled())return this.setState({sessionId:null}),void this.scheduleReconnect(r);this.stopRecording(),this.setState({status:"idle",sessionId:null})}}reconnectEnabled(){return!1!==this.options?.autoReconnect}scheduleReconnect(e){const t="object"==typeof this.options?.autoReconnect?this.options.autoReconnect:{},s=t.maxAttempts??20,n=t.maxDelayMs??3e4;if(!this.wantConnected)return;if(this.reconnectAttempt>=s)return c.error(`giving up after ${this.reconnectAttempt} reconnect attempts (${e})`),this.reconnectAttempt=0,this.stopRecording(),void this.fail({code:"connect_failed",message:`Reconnect failed: ${e}`});this.reconnectAttempt++;const i=Math.min(n,1e3*2**(this.reconnectAttempt-1));c.warn(`reconnecting in ${(i/1e3).toFixed(0)} s (attempt ${this.reconnectAttempt}/${s}): ${e}`),this.setState({status:"connecting",sessionId:null}),this.options?.onReconnecting?.({attempt:this.reconnectAttempt,delayMs:i}),this.clearReconnectTimer(),this.reconnectDueAt=Date.now()+i,this.reconnectTimer=setTimeout((()=>{this.reconnectTimer=null,this.reconnectDueAt=0,this.wantConnected&&this.open()}),i)}reconnectNow(){this.reconnectTimer&&(this.clearReconnectTimer(),this.wantConnected&&this.open())}clearReconnectTimer(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.reconnectDueAt=0}closeSocket(e,t){const s=this.ws;if(this.ws=null,this.clearConnectTimer(),s){c.info(`→ closing socket: code=${e} reason="${t}"`);try{s.close(e,t)}catch{}}}clearConnectTimer(){this.connectTimer&&clearTimeout(this.connectTimer),this.connectTimer=null,this.connectDeadline=0,this.onConnectDeadline=null}tick(){const e=Date.now();if(this.reconnectDueAt&&e>=this.reconnectDueAt)this.reconnectNow();else if(this.connectDeadline&&e>=this.connectDeadline){const e=this.onConnectDeadline;this.clearConnectTimer(),e?.()}}fail(e){c.error(`${e.code}: ${e.message}`),this.setState({status:"idle",sessionId:null,lastError:e}),this.options?.onFailure?.(e)}sendJson(e){if(this.ws&&this.ws.readyState===WebSocket.OPEN){const t=JSON.stringify(e);c.debug(`→ SEND ${h(k(t))}`),this.ws.send(t)}else c.warn(`not sent (socket not open): ${h(k(JSON.stringify(e)),120)}`)}sendConnectMessage(e){this.screens=this.navigation?.getScreens()??[];const t={sessionId:e,domain_id:this.options?.domainId??"",user_id:this.options?.userId??"",cookie_id:this.options?.cookieId||this.getSavedCookieId()||this.runCookieId,type:"Buffer",deviceId:this.options?.deviceId??1,sampleRate:f,screens:this.screens.map((e=>e.name))},s=this.actions.metadata();var n;s.length&&(t.actions=s),this.lastActionsKey=JSON.stringify(s),c.info(`→ connect message: domain_id=${t.domain_id||'""'} user_id=${t.user_id?"(set, hidden)":'""'} cookie_id=${n=t.cookie_id,n?`${n.slice(0,8)}…`:"-"} deviceId=${t.deviceId} sampleRate=${t.sampleRate} screens(${t.screens.length})=${JSON.stringify(t.screens)}`),s.length&&c.info(`→ actions(${s.length}): ${s.map((e=>e.name+(e.confirm?" (confirm)":""))).join(", ")}`),t.screens.length||c.warn("no screens sent: register navigation on <VoiceBotProvider navigation={...}> to enable voice navigation"),this.sendJson(t)}getSavedCookieId(){return void 0===this.savedCookieId&&(this.savedCookieId=t.getPersistentId("cookie_id")),this.savedCookieId}sendScreensUpdate(e){const t=this.screens.map((e=>e.name)).join("\n");this.screens=this.navigation?.getScreens()??[];const s=this.screens.map((e=>e.name));if(s.join("\n")===t)return;const n={type:"screens",sessionId:e,screens:s};c.info(`→ screens update (${s.length}): ${JSON.stringify(s)}`),this.sendJson(n)}endSession(e){("idle"!==this.state.status||this.ws||this.stopMic)&&(c.info(`⏹ voice session ended (${e}): mic off, reply stopped, socket closed`),this.disconnect())}endSessionIfMicOnly(e){this.options?.disconnectOnStop&&this.endSession(e)}async startBackground(){const e=this.options?.backgroundListening??!0;if(!1===e)return;const s="object"==typeof e&&e.title||"Voice assistant",n="object"==typeof e&&e.text||"Listening…",i=await t.startBackgroundService(s,n);!i||this.stopMic?(this.backgroundServiceOn=i,i&&c.info("background listening on (notification shown while the mic is on)")):t.stopBackgroundService()}stopRecording(){if(this.backgroundServiceOn&&(this.backgroundServiceOn=!1,t.stopBackgroundService()),this.stopMic){const e=this.gate?.flush()??[],s="base64"===this.options?.uplinkEncoding;e.forEach((e=>this.sendFrameBytes(e,s))),this.gate=null,t.stopRecording(),this.stopMic(),this.stopMic=null;const n=Date.now()-this.micStartedAt;c.info(`mic stopped after ${(n/1e3).toFixed(1)} s: sent ${this.framesSent} frames (${b(640*this.framesSent)} s of audio, ${640*this.framesSent} bytes)`+(this.framesDropped?`, dropped ${this.framesDropped} (socket not open)`:""))}}onMicFrame(e,t){this.tick();let s=a(e);if(this.inCall)s=S;else if(this.gate){const e=this.gate.process(s,this.botAudible());void 0!==e.speechEvent&&c.debug(e.speechEvent?`🗣 speech started (level ${this.gate.levelDb.toFixed(0)} dBFS, room ${this.gate.noiseFloorDb.toFixed(0)} dBFS)`:"… speech ended"),e.bargeIn&&!0===this.options?.bargeIn&&this.bargeIn(),s=e.out}s&&this.sendFrameBytes(s,t)}sendFrameBytes(e,t){const s=this.ws;if(!s||s.readyState!==WebSocket.OPEN)return this.framesDropped++,void(1===this.framesDropped&&c.warn("mic frame dropped: socket not open"));if(this.framesSent++,c.isEnabled("trace")&&c.trace(`→ SEND audio frame #${this.framesSent} (640 bytes, ${t?"base64 TEXT":"BINARY"})`),1===this.framesSent)c.info("→ first audio frame sent");else if(this.framesSent%250==0){const e=s.bufferedAmount??0,t=this.gate;c.info(`→ audio streaming: ${this.framesSent} frames (${b(640*this.framesSent)} s)`+(this.framesDropped?`, dropped ${this.framesDropped}`:"")+(t?`, speech ${(100*t.openRatio).toFixed(0)}% / silence ${(100-100*t.openRatio).toFixed(0)}%, room ${t.noiseFloorDb.toFixed(0)} dBFS`:"")+(this.inCall?", in a call (sending silence)":"")+(e>32e3?`, ${e} bytes waiting to send (slow network?)`:""))}t?s.send(JSON.stringify({type:"audio",sessionId:this.state.sessionId,seq:this.seq++,sampleRate:f,data:r(e)})):s.send(function(e){return 0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer}(e))}bargeIn(){this.state.speaking&&(t.stopPlayback(),c.info(`✋ barge-in: you started talking, stopped the reply to "${this.playingQuestion??""}"`),this.bargedQuestion=this.playingQuestion,this.stopSpeakingState())}stopSpeakingState(){this.speakingUntil=Date.now(),this.state.speaking&&(this.speakingEndedAt=Date.now()),this.speakingTimer&&clearTimeout(this.speakingTimer),this.speakingTimer=null,this.playingQuestion=null,t.releaseAudioFocus(),this.state.speaking&&this.setState({speaking:!1})}handleInterruption(e){if("focus_lost"===e)this.state.speaking&&c.info("🔇 another app took the audio: stopped the bot's reply"),this.stopSpeakingState();else if("call_started"===e){if(!1===this.options?.pauseOnCall||!this.stopMic)return;if(this.options?.disconnectOnStop)return void this.endSession("phone call");this.inCall=!0,this.stopSpeakingState(),c.info("📞 phone call: bot audio stopped, the mic sends silence until the call ends")}else"call_ended"===e&&this.inCall&&(this.inCall=!1,c.info("📞 call ended: mic audio resumed"))}handleText(e){let t;try{t=JSON.parse(e)}catch{return void c.warn(`← non-JSON text ignored: ${h(e,120)}`)}if(!t||"object"!=typeof t)return;if("tts"===t.type)return this.messageListeners.forEach((e=>e(t))),void this.playStreamedSpeech(t);if(c.debug(`← RECV ${h(k(e))}`),this.messageListeners.forEach((e=>e(t))),this.setState({lastMessage:t}),"actions"===t.type)return void this.engine.handle(t);if("cancel_actions"===t.type)return void(this.engine.cancel(t.requestId)||c.warn(`← cancel_actions ${t.requestId}: nothing running with that id`));if("action_ack"===t.type)return void this.engine.ack(t.requestId);if("navigate"===t.type)return c.info("← navigate: "+("back"===t.action?"back":`screen="${t.screen}"`)+(t.params?` params=${JSON.stringify(t.params)}`:"")+(null!=t.requestId?` requestId=${t.requestId}`:"")),void this.handleNavigate(t);const s=t;if("string"==typeof s.output)try{s.output=JSON.parse(s.output)}catch{}this.replyCount++;const n=this.state.lastQuestion,i=this.state.lastPrompt;"string"==typeof s.buffer&&s.buffer.length>0&&this.playReplyAudio(s,s.buffer);const o={};"string"==typeof s.question&&s.question&&(o.lastQuestion=s.question);const a=s.output?.prompt;"string"==typeof a&&a&&(o.lastPrompt=a),o.lastQuestion&&o.lastQuestion!==n&&c.info(`← you said: "${o.lastQuestion}"`),o.lastPrompt&&o.lastPrompt!==i&&c.info(`← bot: "${o.lastPrompt}"`);const r=s.output?.error;r&&0!==r&&"0"!==r&&c.warn(`← server reported error: ${h(s.output,200)}`),s.buffer||o.lastQuestion||o.lastPrompt||c.info(`← message: ${h(t,200)}`),Object.keys(o).length&&this.setState(o),this.navigateFromReply(s),this.options?.onReply?.(s)}navigateFromReply(e){const t=e.output;if(!t||"object"!=typeof t)return void this.localNavigate(e);const s=e=>"string"==typeof e?e.trim():"",n=s(t.type).toLowerCase(),i=s(t.intent).toLowerCase(),o=s(t.screen)||s(t.class_name)||s(t.target),a="back"===n||/^(back|go_back|goback)$/i.test(o);if(!(a||o&&("navigation"===n||"navigate"===n||"navigate"===i||a||this.matchScreen(o))))return void this.localNavigate(e);const r=`${e.question??""}|${a?"back":o}`,h=Date.now();r===this.lastReplyNavKey&&h-this.lastReplyNavAt<3e3||(this.lastReplyNavKey=r,this.lastReplyNavAt=h,c.info(`← reply asks for ${a?"back":`screen "${o}"`} (type="${s(t.type)}" intent="${s(t.intent)}" screen="${s(t.screen)}" class_name="${s(t.class_name)}" target="${s(t.target)}")`),this.handleNavigate(a?{type:"navigate",action:"back"}:{type:"navigate",screen:o}))}playReplyAudio(e,s){const n="string"==typeof e.question?e.question.trim():"";if(n&&n===this.bargedQuestion)c.debug(`← reply #${this.replyCount}: audio not played (you talked over "${n}")`);else{n&&(this.bargedQuestion=null);try{const i=o(s);n&&n!==this.playingQuestion&&(this.state.speaking&&!1!==this.options?.interruptOnNewReply&&this.interruptPlayback(n),this.playingQuestion=n,this.gate?.newReply()),i%2&&c.warn(`reply audio chunk has an odd byte count (${i}); last byte dropped`);const a=function(e){const t=e.output,s=Number(e.sample_rate??e.sampleRate??t?.sample_rate??t?.sampleRate);return Number.isFinite(s)&&s>=8e3&&s<=48e3?Math.round(s):f}(e);a!==this.lastReplyRate&&(c.info(`reply audio sample rate: ${a} Hz${a===f?" (default)":" (from the server)"}`),this.lastReplyRate=a),t.enqueuePlayback(s,a);const r=i/(2*a);c.debug(`← reply #${this.replyCount}: audio chunk ${i} bytes (${r.toFixed(2)} s at ${a} Hz) queued`),this.markSpeaking(r)}catch(e){c.error(`playback failed: ${e?.message??String(e)}`),this.setState({lastError:{code:"playback_failed",message:e?.message??String(e)}})}}}playStreamedSpeech(e){"string"==typeof e.data&&e.data&&(this.playingQuestion&&this.playingQuestion===this.bargedQuestion?c.trace("← tts chunk not played (you talked over this reply)"):this.playReplyAudio({sample_rate:e.sample_rate},e.data))}interruptPlayback(e){const s=Math.max(0,this.speakingUntil-Date.now())/1e3;t.stopPlayback(),c.info(`⏹ stopped old reply audio (${s.toFixed(1)} s left of "${this.playingQuestion??""}") for new reply to "${e}"`),this.speakingUntil=Date.now(),this.replyAudioSeconds=0}localNavigate(e){if(!1===this.options?.localNavigation||!this.navigation)return;const t="string"==typeof e.question?e.question.trim():"";if(!t)return;const s=this.screens.length?this.screens:this.navigation.getScreens(),n=d(t,s,this.options?.voiceShortcuts);if(!n)return;const i="back"===n.action?"back":n.screen,o=`${t}|local|${i}`,a=Date.now();o===this.lastReplyNavKey&&a-this.lastReplyNavAt<3e3||(this.lastReplyNavKey=o,this.lastReplyNavAt=a,c.info(`🧭 local shortcut: "${t}" → ${i} (the server's reply didn't navigate)`),this.handleNavigate("back"===n.action?{type:"navigate",action:"back",requestId:"local"}:{type:"navigate",screen:n.screen,requestId:"local"}))}markSpeaking(e){const t=Date.now();this.speakingUntil=Math.max(this.speakingUntil,t)+1e3*e,this.state.speaking||(this.replyAudioSeconds=0,c.info("🔊 bot speaking (reply audio playing)"),this.setState({speaking:!0})),this.replyAudioSeconds+=e,this.speakingTimer&&clearTimeout(this.speakingTimer);const s=this.realPlaybackEnd?3e3:250;this.speakingTimer=setTimeout((()=>this.finishSpeaking(this.realPlaybackEnd?"fallback timer":"estimated")),this.speakingUntil-t+s)}finishSpeaking(e){this.state.speaking&&(this.speakingTimer&&clearTimeout(this.speakingTimer),this.speakingTimer=null,c.info(`🔇 bot finished speaking (${this.replyAudioSeconds.toFixed(2)} s of audio, ${e})`),this.playingQuestion=null,this.speakingEndedAt=Date.now(),t.releaseAudioFocus(),this.setState({speaking:!1}))}botAudible(){if(this.state.speaking)return!0;const e=this.options?.echoTailMs??600;return Date.now()-this.speakingEndedAt<e}trySend(e){return!(!this.ws||this.ws.readyState!==WebSocket.OPEN||!this.state.sessionId||(this.sendJson(e),0))}sendActionsUpdate(){if(!this.isConnected||!this.state.sessionId)return;const e=this.actions.metadata(),t=JSON.stringify(e);t!==this.lastActionsKey&&(this.lastActionsKey=t,c.info(`→ actions_update (${e.length}): ${e.map((e=>e.name)).join(", ")}`),this.sendJson({type:"actions_update",sessionId:this.state.sessionId,actions:e}))}async navigateForStep(e,t){const s="back"===e?{type:"navigate",action:"back"}:{type:"navigate",screen:e,params:t},n=await this.handleNavigate(s,!1);return{status:n.status,screen:n.className,message:n.message}}currentScreenParams(e){const t={...this.navigation?.getCurrentParams?.()??{}};this.screenContext&&(null===this.screenContext.screen||this.screenContext.screen===e?Object.assign(t,this.screenContext.params):this.screenContext=null);const s={};let n=0;for(const[e,i]of Object.entries(t))if(!(n>=20||e.startsWith("__")||"screen"===e||"params"===e)){if("string"==typeof i&&i.length<=200)s[e]=i;else if("number"==typeof i&&Number.isFinite(i))s[e]=i;else{if("boolean"!=typeof i)continue;s[e]=i}n++}return n?s:void 0}sendScreenChanged(){if(!this.isConnected||!this.navigation||!this.state.sessionId)return;const e=this.navigation.getCurrentScreen();if(!e)return;const t=this.navigation.getBackStack(),s=this.currentScreenParams(e),n=`${e}|${t.join(",")}|${s?JSON.stringify(s):""}`;if(n===this.lastSentScreen)return;this.lastSentScreen=n;const i={type:"screen_changed",sessionId:this.state.sessionId,screen:e,backStack:t};s&&(i.params=s),c.info(`→ screen_changed: "${e}" backStack=${JSON.stringify(t)}${s?` params=${JSON.stringify(s)}`:""}`),this.sendJson(i)}async waitForScreen(t,s,n,i){const o=()=>t.getCurrentScreen();if(e.currentState&&"active"!==e.currentState)return s;for(let e=0;e<30;e++){const e=o();if(e===s&&(e!==n||i))return e;await new Promise((e=>setTimeout((()=>e()),50)))}return o()}matchScreen(e){const t=this.screens.length?this.screens:this.navigation?.getScreens()??[];return g(t,e)}}export const VoiceBot=new VoiceBotClient;
|
package/build/protocol.d.ts
CHANGED
|
@@ -16,6 +16,8 @@ export interface ConnectMessage {
|
|
|
16
16
|
sessionId: string;
|
|
17
17
|
/** Host app's domain / tenant id (from `connect({ domainId })`). */
|
|
18
18
|
domain_id: string;
|
|
19
|
+
/** The app's user id (from `connect({ userId })`): any string the app chooses (email, phone, id); `""` for guests. */
|
|
20
|
+
user_id: string;
|
|
19
21
|
/** Visitor id (from `connect({ cookieId })`, or a random id kept for the app run). */
|
|
20
22
|
cookie_id: string;
|
|
21
23
|
type: 'Buffer';
|
|
@@ -82,6 +84,17 @@ export interface BotReply {
|
|
|
82
84
|
sample_rate?: number;
|
|
83
85
|
[key: string]: unknown;
|
|
84
86
|
}
|
|
87
|
+
/**
|
|
88
|
+
* Server → app: the next piece of the current reply's speech. Servers that stream their speech
|
|
89
|
+
* send the reply message (text and the first audio) first, then the rest in these chunks.
|
|
90
|
+
*/
|
|
91
|
+
export interface TtsChunk {
|
|
92
|
+
type: 'tts';
|
|
93
|
+
/** Base64 PCM s16le mono. */
|
|
94
|
+
data: string;
|
|
95
|
+
/** Sample rate of `data` in Hz (8000-48000). Missing = 16000. */
|
|
96
|
+
sample_rate?: number;
|
|
97
|
+
}
|
|
85
98
|
/** Server → app: open a screen, or go back. */
|
|
86
99
|
export interface NavigateCommand {
|
|
87
100
|
type: 'navigate';
|
|
@@ -14,8 +14,21 @@ export interface VoiceBotProviderProps {
|
|
|
14
14
|
url?: string;
|
|
15
15
|
/** Your domain / tenant id, sent as `domain_id`. */
|
|
16
16
|
domainId?: string;
|
|
17
|
+
/**
|
|
18
|
+
* Your app's id for the signed-in user, sent as `user_id`: an email, a phone number or any id of
|
|
19
|
+
* yours (sent as is, never logged). Leave it out (or `""`) for guests.
|
|
20
|
+
* When it changes (sign in / sign out) the provider reconnects, so the server gets the new user.
|
|
21
|
+
*/
|
|
22
|
+
userId?: string;
|
|
17
23
|
/** Connect as soon as the provider mounts (when `url` is set). Default `true`. */
|
|
18
24
|
autoConnect?: boolean;
|
|
25
|
+
/**
|
|
26
|
+
* When the socket opens. `"mount"` (default): when the provider mounts, and it stays open
|
|
27
|
+
* between turns. `"mic"`: only while the mic is on. Pressing the mic connects and starts
|
|
28
|
+
* listening; pressing it again stops listening, stops the bot's reply and disconnects (a phone
|
|
29
|
+
* call or mic error also ends the session). Each mic press is a new server session.
|
|
30
|
+
*/
|
|
31
|
+
connectOn?: 'mount' | 'mic';
|
|
19
32
|
/**
|
|
20
33
|
* The floating mic button. Default `true` (drop-in voice widget, bottom-right). Pass an object to
|
|
21
34
|
* style it, or `false` to use your own button with `useVoiceBot().start()` / `stop()`.
|
|
@@ -39,7 +52,7 @@ export interface VoiceBotProviderProps {
|
|
|
39
52
|
/** Every JSON message from the server (replies, navigate commands, custom messages). */
|
|
40
53
|
onMessage?(message: Record<string, unknown>): void;
|
|
41
54
|
/** Advanced options, the same as `VoiceBot.connect()` (noise gate, barge-in, reconnect, logs ...). */
|
|
42
|
-
options?: Omit<ConnectOptions, 'url' | 'domainId' | 'onSuccess' | 'onFailure' | 'onClose' | 'onReply'>;
|
|
55
|
+
options?: Omit<ConnectOptions, 'url' | 'domainId' | 'userId' | 'onSuccess' | 'onFailure' | 'onClose' | 'onReply'>;
|
|
43
56
|
/**
|
|
44
57
|
* Actions of your app the AI server may run, by name. Each has a description, a params schema
|
|
45
58
|
* and a `run` function that uses your app's own APIs. See docs/ACTIONS.md. Optional: without it
|
|
@@ -59,8 +72,8 @@ export declare const alertConfirm: ConfirmHandler;
|
|
|
59
72
|
/**
|
|
60
73
|
* Wrap your app once. With `url` it connects to your voice server and shows the floating mic:
|
|
61
74
|
*
|
|
62
|
-
* <VoiceBotProvider url="wss://voice.example.com/demo" domainId="your-domain-id" navigation={navigation}>
|
|
75
|
+
* <VoiceBotProvider url="wss://voice.example.com/demo" domainId="your-domain-id" userId={user?.id} navigation={navigation}>
|
|
63
76
|
* <App />
|
|
64
77
|
* </VoiceBotProvider>
|
|
65
78
|
*/
|
|
66
|
-
export declare function VoiceBotProvider({ children, url, domainId, autoConnect, widget, navigation, onConnect, onError, onClose, onReply, onMessage, options, actions, onConfirmAction, disconnectOnUnmount, }: VoiceBotProviderProps): React.JSX.Element;
|
|
79
|
+
export declare function VoiceBotProvider({ children, url, domainId, userId, autoConnect, connectOn, widget, navigation, onConnect, onError, onClose, onReply, onMessage, options, actions, onConfirmAction, disconnectOnUnmount, }: VoiceBotProviderProps): React.JSX.Element;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as n,jsxs as e}from"react/jsx-runtime";import{useEffect as o,useRef as t}from"react";import{Alert as r,StyleSheet as s,View as
|
|
1
|
+
import{jsx as n,jsxs as e}from"react/jsx-runtime";import{useEffect as o,useRef as t}from"react";import{Alert as r,StyleSheet as s,View as c}from"react-native";import{VoiceBot as i}from"../VoiceBotClient";import{VoiceBotWidget as l}from"./VoiceBotWidget";export const alertConfirm=n=>new Promise((e=>{let o=!1;const t=n=>{o||(o=!0,e(n))};n.signal.addEventListener?.("abort",(()=>t("cancelled"))),r.alert(n.title,n.message||void 0,[{text:n.cancelLabel,style:"cancel",onPress:()=>t("rejected")},{text:n.confirmLabel,onPress:()=>t("approved")}],{cancelable:!0,onDismiss:()=>t("cancelled")})}));export function VoiceBotProvider({children:r,url:s,domainId:u,userId:d,autoConnect:m=!0,connectOn:p="mount",widget:f=!0,navigation:C=null,onConnect:g,onError:v,onClose:x,onReply:y,onMessage:b,options:j,actions:E,onConfirmAction:M,disconnectOnUnmount:R=!0}){const I=t({onConnect:g,onError:v,onClose:x,onReply:y,onMessage:b,options:j});return I.current={onConnect:g,onError:v,onClose:x,onReply:y,onMessage:b,options:j},o((()=>{i.setNavigation(C)}),[C]),o((()=>i.addMessageListener((n=>I.current.onMessage?.(n)))),[]),o((()=>{if(E)return i.setActions(E),()=>i.setActions({})}),[E]),o((()=>{i.setConfirmHandler(M??alertConfirm)}),[M]),o((()=>{if(!s||!m)return;const n={...I.current.options,url:s,domainId:u,userId:d,onSuccess:n=>I.current.onConnect?.(n),onFailure:n=>I.current.onError?.(n),onClose:n=>I.current.onClose?.(n),onReply:n=>I.current.onReply?.(n)};return"mic"===p?i.configure({...n,disconnectOnStop:!0}):i.connect(n),()=>i.disconnect()}),[s,u,d,m,p]),o((()=>()=>{i.setNavigation(null),R&&i.disconnect()}),[R]),e(c,{style:a.fill,children:[r,f?n(l,{..."object"==typeof f?f:{}}):null]})}const a=s.create({fill:{flex:1}});
|
package/docs/ACTIONS.md
CHANGED
|
@@ -44,7 +44,7 @@ const actions: Record<string, ActionDefinition> = {
|
|
|
44
44
|
},
|
|
45
45
|
};
|
|
46
46
|
|
|
47
|
-
<VoiceBotProvider url={URL} domainId="…" navigation={navigation} actions={actions}>
|
|
47
|
+
<VoiceBotProvider url={URL} domainId="…" userId={currentUserId} navigation={navigation} actions={actions}>
|
|
48
48
|
```
|
|
49
49
|
|
|
50
50
|
Without React, or for actions added later:
|
package/docs/INTEGRATION.md
CHANGED
|
@@ -71,7 +71,7 @@ import { useExpoRouterNavigation } from 'react-native-voice-bot-sdk/expo-router'
|
|
|
71
71
|
export default function RootLayout() {
|
|
72
72
|
const navigation = useExpoRouterNavigation();
|
|
73
73
|
return (
|
|
74
|
-
<VoiceBotProvider url="wss://voice.example.com/demo" domainId="YOUR_DOMAIN_ID" navigation={navigation}>
|
|
74
|
+
<VoiceBotProvider url="wss://voice.example.com/demo" domainId="YOUR_DOMAIN_ID" userId={currentUserId} navigation={navigation}>
|
|
75
75
|
<Stack />
|
|
76
76
|
</VoiceBotProvider>
|
|
77
77
|
);
|
|
@@ -89,13 +89,19 @@ const navigation = createReactNavigationAdapter(navigationRef);
|
|
|
89
89
|
|
|
90
90
|
export default function App() {
|
|
91
91
|
return (
|
|
92
|
-
<VoiceBotProvider url="wss://voice.example.com/demo" domainId="YOUR_DOMAIN_ID" navigation={navigation}>
|
|
92
|
+
<VoiceBotProvider url="wss://voice.example.com/demo" domainId="YOUR_DOMAIN_ID" userId={currentUserId} navigation={navigation}>
|
|
93
93
|
<NavigationContainer ref={navigationRef}>{/* your navigators */}</NavigationContainer>
|
|
94
94
|
</VoiceBotProvider>
|
|
95
95
|
);
|
|
96
96
|
}
|
|
97
97
|
```
|
|
98
98
|
|
|
99
|
+
`userId` is your app's id for the signed-in user, sent to the server as `user_id`. Use whatever
|
|
100
|
+
identifies your users: an email, a phone number or your own id. The SDK sends it as is and never
|
|
101
|
+
writes it to its logs. Leave it out (or
|
|
102
|
+
pass `""`) for guests. When it changes (sign in / sign out) the provider reconnects, so the server
|
|
103
|
+
always knows who is talking.
|
|
104
|
+
|
|
99
105
|
**No navigation by voice:** leave out `navigation`. The bot still listens and answers.
|
|
100
106
|
|
|
101
107
|
### What is sent to the server
|
|
@@ -104,12 +110,24 @@ Only the **names of your screens** (route names such as `cart`, `products`, `pro
|
|
|
104
110
|
code, data or component names. Leave screens out with
|
|
105
111
|
`useExpoRouterNavigation({ exclude: ['settings/billing'] })`.
|
|
106
112
|
|
|
113
|
+
### Connect only while the mic is on (optional)
|
|
114
|
+
|
|
115
|
+
By default the provider connects when the app starts and stays connected. To open the connection
|
|
116
|
+
only for a voice session, use `connectOn="mic"`:
|
|
117
|
+
|
|
118
|
+
```tsx
|
|
119
|
+
<VoiceBotProvider url={URL} domainId={DOMAIN_ID} userId={currentUserId} connectOn="mic" navigation={navigation}>
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
Mic press: connect and start listening. Press again: stop listening, stop the bot's reply and
|
|
123
|
+
disconnect. Each press starts a new server session.
|
|
124
|
+
|
|
107
125
|
## 5. Your own button (optional)
|
|
108
126
|
|
|
109
127
|
Hide the widget and use the hook:
|
|
110
128
|
|
|
111
129
|
```tsx
|
|
112
|
-
<VoiceBotProvider url={URL} domainId={DOMAIN_ID} widget={false}>
|
|
130
|
+
<VoiceBotProvider url={URL} domainId={DOMAIN_ID} userId={currentUserId} widget={false}>
|
|
113
131
|
```
|
|
114
132
|
|
|
115
133
|
```tsx
|
|
@@ -129,6 +147,7 @@ function TalkButton() {
|
|
|
129
147
|
<VoiceBotProvider
|
|
130
148
|
url={URL}
|
|
131
149
|
domainId={DOMAIN_ID}
|
|
150
|
+
userId={currentUserId}
|
|
132
151
|
onConnect={({ sessionId }) => analytics.track('voice_connected', { sessionId })}
|
|
133
152
|
onError={(e) => console.warn('voice bot', e.code, e.message)}
|
|
134
153
|
onReply={(reply) => console.log('user said', reply.question, 'bot said', reply.output?.prompt)}
|
|
@@ -182,6 +201,81 @@ packages needed) that checks the connect message and the audio frames.
|
|
|
182
201
|
- [ ] Test on the oldest Android and iOS versions you support.
|
|
183
202
|
- [ ] Set `logLevel: 'warn'` (the default in release builds) so requests aren't logged.
|
|
184
203
|
|
|
204
|
+
## 10. Reference
|
|
205
|
+
|
|
206
|
+
### `VoiceBot.connect(options)`
|
|
207
|
+
|
|
208
|
+
| Option | Type | Description |
|
|
209
|
+
|--------|------|-------------|
|
|
210
|
+
| `url` | `string` | **Required.** WebSocket URL of the voice server. |
|
|
211
|
+
| `domainId` | `string` | Sent as `domain_id` in the connect message. Default `""`. |
|
|
212
|
+
| `userId` | `string` | Sent as `user_id`: your app's id for the signed-in user, in any format (email, phone number, your own id). Never logged by the SDK. Default `""` (guest). Connect again when it changes. |
|
|
213
|
+
| `cookieId` | `string` | Sent as `cookie_id`. Default: a random id the SDK saves on the device, so it stays the same across app launches. Pass your own id (e.g. your user's visitor id) to use that instead. |
|
|
214
|
+
| `onSuccess` | `({ sessionId }) => void` | Connected; the connect message (with the screen names) was sent. |
|
|
215
|
+
| `onFailure` | `(error) => void` | Couldn't connect. `error.code`: `connect_failed`, `connect_timeout`, `native_missing`, ... |
|
|
216
|
+
| `onClose` | `({ code, reason }) => void` | The socket closed after a successful connect. |
|
|
217
|
+
| `onReply` | `(reply) => void` | Every reply from the server (`question`, `output`, `buffer`). |
|
|
218
|
+
| `autoStart` | `boolean` | Start the mic right after connecting. Default `false`. |
|
|
219
|
+
| `uplinkEncoding` | `'binary' \| 'base64'` | Default `binary` (what the server expects today). `base64` needs server support, see the protocol doc. |
|
|
220
|
+
| `deviceId` | `number` | `deviceId` in the connect message. Default `1`. |
|
|
221
|
+
| `connectTimeoutMs` | `number` | Default `10000`. |
|
|
222
|
+
| `autoReconnect` | `boolean \| { maxAttempts?, maxDelayMs? }` | Reconnect by itself when the socket drops. Default `true` (backoff 1 s, 2 s, 4 s … 30 s, 20 attempts). |
|
|
223
|
+
| `onReconnecting` | `({ attempt, delayMs }) => void` | Called before each reconnect attempt. |
|
|
224
|
+
| `backgroundListening` | `boolean \| { title?, text? }` | Android: keep listening in the background, with a notification while the mic is on. Default `true`. |
|
|
225
|
+
| `interruptOnNewReply` | `boolean` | Default `true`: a reply to a new question stops the old reply's audio and plays right away. Parts of the same reply still play in order. `false` queues every reply. |
|
|
226
|
+
| `noiseGate` | `boolean \| { thresholdDb?, minLevelDb?, hangoverMs?, preRollMs? }` | Default `true`: send silence instead of room noise between sentences. |
|
|
227
|
+
| `whileSpeaking` | `'mute' \| 'guard' \| 'listen'` | What the mic does while the bot speaks. Default `'mute'`. |
|
|
228
|
+
| `bargeIn` | `boolean` | Default `false`. `true`: talking over the bot stops its reply (use with headsets and `whileSpeaking: 'guard'`). |
|
|
229
|
+
| `echoTailMs` | `number` | Default `600`: the mic stays muted this long after the reply has finished playing. |
|
|
230
|
+
| `pauseOnCall` | `boolean` | Default `true`: during a phone call, stop the bot's audio and send silence. |
|
|
231
|
+
| `keepSessionOnReconnect` | `boolean` | Default `false`. `true` keeps the same `sessionId` after an automatic reconnect. |
|
|
232
|
+
| `localNavigation` | `boolean` | Default `true`: when the server doesn't navigate, open the screen the user clearly asked for ("open my cart"). |
|
|
233
|
+
| `voiceShortcuts` | `Record<screen, string[]>` | Extra words for local navigation, e.g. `{ '(tabs)/cart': ['bag', 'basket'] }`. |
|
|
234
|
+
| `logLevel` | `'trace' \| 'debug' \| 'info' \| 'warn' \| 'error' \| 'none'` | Console logging. Default `debug` in development, `warn` in release. `none` turns it off. |
|
|
235
|
+
|
|
236
|
+
### `useVoiceBot()`
|
|
237
|
+
|
|
238
|
+
```tsx
|
|
239
|
+
const { status, isReady, isListening, speaking, lastQuestion, lastPrompt, lastMessage, error,
|
|
240
|
+
start, stop, toggle, connect, disconnect, addMessageListener } = useVoiceBot();
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
| Returns | Description |
|
|
244
|
+
|---------|-------------|
|
|
245
|
+
| `status` | `'idle' \| 'connecting' \| 'connected' \| 'listening'` |
|
|
246
|
+
| `isReady` / `isConnected` | Connected to the server, ready to listen. |
|
|
247
|
+
| `isListening` | The mic is on. |
|
|
248
|
+
| `speaking` | The bot's reply is playing. |
|
|
249
|
+
| `sessionId` | Current session id, or `null`. |
|
|
250
|
+
| `lastQuestion`, `lastPrompt` | What the user said (`question`) and the bot's answer text (`output.prompt`). |
|
|
251
|
+
| `lastMessage` | The most recent JSON message from the server. |
|
|
252
|
+
| `error` / `lastError` | Last error (`{ code, message }`), or `null`. |
|
|
253
|
+
| `start`, `stop`, `toggle` | Mic on / off. `start()` asks for the mic permission the first time and reconnects if needed. |
|
|
254
|
+
| `connect`, `disconnect` | Same as `VoiceBot.connect()` / `disconnect()`. |
|
|
255
|
+
| `registerAction(name, def)` | Register an action; returns an unregister function. |
|
|
256
|
+
| `setScreenContext(params)` | Small context about the visible screen, sent with `screen_changed`. |
|
|
257
|
+
| `addMessageListener(fn)` | Every JSON message from the server. Returns an unsubscribe function. |
|
|
258
|
+
|
|
259
|
+
### `<VoiceBotProvider>`
|
|
260
|
+
|
|
261
|
+
| Prop | Description |
|
|
262
|
+
|------|-------------|
|
|
263
|
+
| `url` | Voice server WebSocket URL. When set, the provider connects by itself. |
|
|
264
|
+
| `domainId` | Sent as `domain_id`. |
|
|
265
|
+
| `userId` | Sent as `user_id` (the signed-in user's id; leave out for guests). Changing it reconnects. |
|
|
266
|
+
| `autoConnect` | Default `true` (when `url` is set). |
|
|
267
|
+
| `connectOn` | `"mount"` (default): connect when the provider mounts and stay connected. `"mic"`: connect only while the mic is on. Mic press = connect + listen; press again = stop listening, stop the reply, disconnect. |
|
|
268
|
+
| `widget` | Default `true`: the floating mic. Widget props to style it, `false` to use your own button. |
|
|
269
|
+
| `navigation` | A navigation adapter, so the server can open screens (section 4). |
|
|
270
|
+
| `onConnect`, `onError`, `onClose` | Connection callbacks. |
|
|
271
|
+
| `onReply`, `onMessage` | Every reply / every JSON message from the server. |
|
|
272
|
+
| `actions` | Actions the server may run (see [ACTIONS.md](https://unpkg.com/react-native-voice-bot-sdk/docs/ACTIONS.md)). |
|
|
273
|
+
| `onConfirmAction` | Your confirmation UI for actions with `confirm`. Default: a native alert. |
|
|
274
|
+
| `options` | Any other `VoiceBot.connect()` option (`noiseGate`, `bargeIn`, `autoReconnect`, `logLevel` …). |
|
|
275
|
+
| `disconnectOnUnmount` | Default `true`. |
|
|
276
|
+
|
|
277
|
+
Without `url`, call `VoiceBot.connect({ url, … })` yourself (for example after login).
|
|
278
|
+
|
|
185
279
|
## Troubleshooting
|
|
186
280
|
|
|
187
281
|
| Problem | Cause and fix |
|
package/docs/PROTOCOL.md
CHANGED
|
@@ -11,10 +11,11 @@ Transport: one WebSocket connection per session, e.g. `ws://<host>:8091/demo`.
|
|
|
11
11
|
|
|
12
12
|
| # | Direction | Frame | Content |
|
|
13
13
|
|---|-----------|-------|---------|
|
|
14
|
-
| 1 | App → Server | TEXT, once, first | Connect `{sessionId, domain_id, cookie_id, type:"Buffer", deviceId, sampleRate:16000, screens[]}` |
|
|
14
|
+
| 1 | App → Server | TEXT, once, first | Connect `{sessionId, domain_id, user_id, cookie_id, type:"Buffer", deviceId, sampleRate:16000, screens[]}` |
|
|
15
15
|
| 3 | App → Server | TEXT, right after 1 and on every screen change | `{type:"screen_changed", sessionId, screen, backStack[]}` |
|
|
16
16
|
| 4 | App → Server | BINARY stream | 640-byte frames of PCM s16le / 16 kHz / mono, in order, no gaps |
|
|
17
17
|
| 5 | Server → App | TEXT stream | Reply `{session_id, question, output{...}, buffer}`; `buffer` = base64 PCM s16le 16 kHz mono |
|
|
18
|
+
| 5a | Server → App | TEXT stream, after 5 | **0.2.2** Streamed speech `{type:"tts", data, sample_rate}`: the rest of the reply's audio |
|
|
18
19
|
| 6 | Server → App | TEXT, any time | `{type:"navigate", screen, params?, requestId?}` or `{type:"navigate", action:"back"}` |
|
|
19
20
|
| 7 | App → Server | TEXT, answer to 6 | `{type:"navigate_result", sessionId, screen, action, className, status, message, requestId}` |
|
|
20
21
|
| 8 | Server → App | TEXT, any time | **0.2.0** `{type:"actions", requestId, steps[]}`: run registered actions and navigation, in order |
|
|
@@ -30,6 +31,7 @@ names of the app's UI screens in one JSON object:
|
|
|
30
31
|
{
|
|
31
32
|
"sessionId": "c0a8f6e2-5b1d-4f0e-9d7a-2b6c1e3f4a5b",
|
|
32
33
|
"domain_id": "demo-domain",
|
|
34
|
+
"user_id": "u_10293",
|
|
33
35
|
"cookie_id": "9b2e4c1a-7f3d-4e8b-a1c6-5d0f2e9b7a34",
|
|
34
36
|
"type": "Buffer",
|
|
35
37
|
"deviceId": 1,
|
|
@@ -42,6 +44,7 @@ names of the app's UI screens in one JSON object:
|
|
|
42
44
|
|-------|---------|
|
|
43
45
|
| `sessionId` | Random UUID v4, new for every connection. |
|
|
44
46
|
| `domain_id` | The host app's domain / tenant id, from `connect({ domainId })`. `""` if not set. |
|
|
47
|
+
| `user_id` | The host app's id for the signed-in user, from `connect({ userId })`. **Any string format the app chooses:** an email, a phone number, or an internal or random id; don't assume one format. `""` for guests (no user signed in). When the user signs in or out, the app reconnects with the new value (new `sessionId`). Since 0.2.1. |
|
|
45
48
|
| `cookie_id` | Visitor id, from `connect({ cookieId })`. If the app doesn't pass one, a random UUID saved on the device: the same across app launches until the app is uninstalled or its data is cleared. |
|
|
46
49
|
| `type` | Always `"Buffer"`. |
|
|
47
50
|
| `deviceId` | Default `1`; the app may override it. |
|
|
@@ -153,6 +156,19 @@ Same as Android:
|
|
|
153
156
|
app stops the old audio and plays the new reply right away. So keep `question` the same in every
|
|
154
157
|
chunk of one reply.
|
|
155
158
|
- `output` may be an object or a JSON-encoded string.
|
|
159
|
+
- **Streamed speech (0.2.2):** the server may send the reply message with only the first piece of
|
|
160
|
+
audio in `buffer`, then the rest of the speech as separate messages:
|
|
161
|
+
|
|
162
|
+
```json
|
|
163
|
+
{ "type": "tts", "data": "<base64 PCM s16le mono>", "sample_rate": 24000 }
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
The app plays each `data` right after the audio already queued, as part of the **current**
|
|
167
|
+
reply (these messages have no `question`). So send the reply message first, then its `tts`
|
|
168
|
+
chunks, in order; a reply with a new `question` starts the next reply. Chunks arrive faster
|
|
169
|
+
than they play today (about 200 ms of audio each, 20–50 ms apart), so playback is continuous.
|
|
170
|
+
SDK versions before 0.2.2 ignore `tts` messages and play only the first `buffer`, which cuts the
|
|
171
|
+
reply off after about 200 ms.
|
|
156
172
|
- The SDK is more lenient than the Android app: a message with missing keys is **not** dropped. It
|
|
157
173
|
plays `buffer` if present and passes the whole message to the app.
|
|
158
174
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-native-voice-bot-sdk",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"description": "Drop-in voice assistant widget for React Native and Expo apps: talks to your voice server over a WebSocket, plays the spoken reply, and lets the server open screens in your app.",
|
|
5
5
|
"main": "build/index.js",
|
|
6
6
|
"types": "build/index.d.ts",
|