react-native-voice-bot-sdk 0.2.1 → 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 CHANGED
@@ -1,5 +1,19 @@
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
+
3
17
  ## 0.2.1
4
18
 
5
19
  - **`userId`:** new option on `VoiceBotProvider` and `VoiceBot.connect()`, sent as `user_id` in the
package/README.md CHANGED
@@ -1,75 +1,34 @@
1
1
  # react-native-voice-bot-sdk
2
2
 
3
- Drop-in **voice assistant widget** for React Native and Expo apps. Your users tap a floating mic and
4
- talk; the SDK streams their voice to your voice server, plays the spoken answer, and lets the server
5
- **open screens in your app** ("open my cart", "go back").
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 or newer with a **development build** (`npx expo run:android` / EAS). It doesn't run in
22
- **Expo Go**, because it has its own native audio module.
23
- - Or a bare React Native app with Expo modules installed (`npx install-expo-modules@latest`).
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
- ## Installation
13
+ ## Install
27
14
 
28
15
  ```bash
29
16
  npx expo install react-native-voice-bot-sdk
30
17
  ```
31
18
 
32
- Add the config plugin to `app.json` (adds the microphone permission on Android and iOS):
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
- Set `allowCleartextTraffic` only if your server URL is `ws://` (not `wss://`) and you need it in
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
- **Bare React Native:** after `npx install-expo-modules@latest` and installing this package, rebuild
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
- ## Quick start (2 steps)
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,422 +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(); // lets the server open your screens
99
-
51
+ const navigation = useExpoRouterNavigation();
100
52
  return (
101
- <VoiceBotProvider url="wss://voice.example.com/demo" domainId="YOUR_DOMAIN_ID" userId={currentUserId} navigation={navigation}>
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
- **React Native without Expo Router** (`App.tsx`):
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" userId={currentUserId}>
116
- <AppNavigator />
117
- </VoiceBotProvider>
118
- );
119
- }
120
- ```
121
-
122
- `url`, `domainId` and `userId` come from your app: the voice server address, your domain id, and
123
- the id of the signed-in user in any format you choose: an email, a phone number or your own id (leave `userId` out, or pass `""`, for guests; when it changes the
124
- provider reconnects so the server gets the new user).
125
-
126
- That's the whole setup for the **widget-only** integration: the provider connects to your server
127
- and shows the floating mic (bottom-right). The user taps it to talk and taps again to stop.
128
-
129
- ### Step 2 (optional): use it from any screen with `useVoiceBot`
130
-
131
- ```tsx
132
- import { Button } from 'react-native';
133
- import { useVoiceBot } from 'react-native-voice-bot-sdk';
134
-
135
- function TalkButton() {
136
- const { isListening, start, stop, lastQuestion, lastPrompt } = useVoiceBot();
137
- return <Button title={isListening ? 'Stop' : 'Talk to us'} onPress={isListening ? stop : start} />;
138
- }
139
- ```
140
-
141
- Right after connecting, the SDK sends one connect message with your screen names, then streams
142
- the mic:
143
-
144
- ```json
145
- {
146
- "sessionId": "c0a8f6e2-…",
147
- "domain_id": "YOUR_DOMAIN_ID",
148
- "user_id": "YOUR_USER_ID",
149
- "cookie_id": "9b2e4c1a-…",
150
- "type": "Buffer",
151
- "deviceId": 1,
152
- "sampleRate": 16000,
153
- "screens": ["cart", "index", "products", "profile", "product/[id]"]
154
- }
155
- ```
156
-
157
- ## Widget on or off
65
+ That's all: a floating mic button appears. Tap to talk, tap again to stop.
158
66
 
159
- ```tsx
160
- <VoiceBotProvider url={URL}> {/* default floating mic */}
161
- <VoiceBotProvider url={URL} widget={{ size: 56, right: 16, bottom: 90, colors: { idle: '#7048E8' } }}>
162
- <VoiceBotProvider url={URL} widget={false}> {/* no widget: use your own button */}
163
- ```
164
-
165
- Apps with a bottom tab bar: move the mic above it, e.g. `widget={{ bottom: 90 }}`. You can also place `<VoiceBotWidget />` yourself anywhere. The widget shows a spinner while
166
- connecting, a pulsing red ring while listening, and green while the bot is speaking.
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. |
167
75
 
168
76
  ## Your own button
169
77
 
170
78
  ```tsx
171
- 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}>
172
82
 
173
83
  function TalkButton() {
174
84
  const bot = useVoiceBot();
175
- return (
176
- <Button
177
- title={bot.isListening ? 'Stop' : 'Talk'}
178
- onPress={() => (bot.isListening ? bot.stop() : bot.start())}
179
- />
180
- );
85
+ return <Button title={bot.isListening ? 'Stop' : 'Talk'} onPress={bot.toggle} />;
181
86
  }
182
87
  ```
183
88
 
184
- Without React, use the `VoiceBot` object: `VoiceBot.start()`, `VoiceBot.stop()`, `VoiceBot.toggle()`,
185
- `VoiceBot.disconnect()`, `VoiceBot.getState()`, `VoiceBot.subscribe(fn)`.
186
-
187
- `start()` asks for the microphone permission the first time. If the socket isn't open it reconnects
188
- with the options from the last `connect()` call and then starts the mic.
189
-
190
- ## API
191
-
192
- ### `VoiceBot.connect(options)`
193
-
194
- | Option | Type | Description |
195
- |--------|------|-------------|
196
- | `url` | `string` | **Required.** WebSocket URL of the voice server. |
197
- | `domainId` | `string` | Sent as `domain_id` in the connect message. Default `""`. |
198
- | `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. |
199
- | `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. |
200
- | `onSuccess` | `({ sessionId }) => void` | Connected; the connect message (with the screen names) was sent. |
201
- | `onFailure` | `(error) => void` | Couldn't connect. `error.code`: `connect_failed`, `connect_timeout`, `native_missing`, ... |
202
- | `onClose` | `({ code, reason }) => void` | The socket closed after a successful connect. |
203
- | `onReply` | `(reply) => void` | Every reply from the server (`question`, `output`, `buffer`). |
204
- | `autoStart` | `boolean` | Start the mic right after connecting. Default `false`. |
205
- | `uplinkEncoding` | `'binary' \| 'base64'` | Default `binary` (what the server expects today). `base64` needs server support, see the protocol doc. |
206
- | `deviceId` | `number` | `deviceId` in the connect message. Default `1`. |
207
- | `connectTimeoutMs` | `number` | Default `10000`. |
208
- | `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). |
209
- | `onReconnecting` | `({ attempt, delayMs }) => void` | Called before each reconnect attempt. |
210
- | `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). |
211
- | `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. |
212
- | `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). |
213
- | `whileSpeaking` | `'mute' \| 'guard' \| 'listen'` | What the mic does while the bot speaks. Default `'mute'`. |
214
- | `bargeIn` | `boolean` | Default `false`. `true`: talking over the bot stops its reply (use with headsets and `whileSpeaking: 'guard'`). |
215
- | `echoTailMs` | `number` | Default `600`: the mic stays muted this long after the reply has finished playing. |
216
- | `pauseOnCall` | `boolean` | Default `true`: during a phone call, stop the bot's audio and send silence. |
217
- | `keepSessionOnReconnect` | `boolean` | Default `false`. `true` keeps the same `sessionId` after an automatic reconnect. |
218
- | `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). |
219
- | `voiceShortcuts` | `Record<screen, string[]>` | Extra words for local navigation, e.g. `{ '(tabs)/cart': ['bag', 'basket'] }`. |
220
- | `logLevel` | `'trace' \| 'debug' \| 'info' \| 'warn' \| 'error' \| 'none'` | Console logging, see [Logs](#logs). |
221
-
222
- ### `useVoiceBot()`
223
-
224
- ```tsx
225
- const { status, isReady, isListening, speaking, lastQuestion, lastPrompt, lastMessage, error,
226
- start, stop, toggle, connect, disconnect, addMessageListener } = useVoiceBot();
227
- ```
228
-
229
- | Returns | Description |
230
- |---------|-------------|
231
- | `status` | `'idle' \| 'connecting' \| 'connected' \| 'listening'` |
232
- | `isReady` / `isConnected` | Connected to the server, ready to listen. |
233
- | `isListening` | The mic is on. |
234
- | `speaking` | The bot's reply is playing. |
235
- | `sessionId` | Current session id, or `null`. |
236
- | `lastQuestion`, `lastPrompt` | What the user said (`question`) and the bot's answer text (`output.prompt`). |
237
- | `lastMessage` | The most recent JSON message from the server. |
238
- | `error` / `lastError` | Last error (`{ code, message }`), or `null`. |
239
- | `start`, `stop`, `toggle` | Mic on / off. `start()` asks for the mic permission the first time and reconnects if needed. |
240
- | `connect`, `disconnect` | Same as `VoiceBot.connect()` / `disconnect()`. |
241
- | `registerAction(name, def)` | Register an action; returns an unregister function. |
242
- | `setScreenContext(params)` | Small context about the visible screen, sent with `screen_changed`. |
243
- | `addMessageListener(fn)` | Every JSON message from the server. Returns an unsubscribe function. |
244
-
245
- ### `<VoiceBotProvider>`
89
+ `useVoiceBot()` also gives `status`, `speaking`, `lastQuestion` (what the user said) and
90
+ `lastPrompt` (the assistant's answer).
246
91
 
247
- | Prop | Description |
248
- |------|-------------|
249
- | `url` | Voice server WebSocket URL. When set, the provider connects by itself. |
250
- | `domainId` | Sent as `domain_id`. |
251
- | `userId` | Sent as `user_id` (the signed-in user's id; leave out for guests). Changing it reconnects. |
252
- | `autoConnect` | Default `true` (when `url` is set). |
253
- | `widget` | Default `true`: the floating mic. Widget props to style it, `false` to use your own button. |
254
- | `navigation` | A navigation adapter, so the server can open screens (see below). |
255
- | `onConnect`, `onError`, `onClose` | Connection callbacks. |
256
- | `onReply`, `onMessage` | Every reply / every JSON message from the server. |
257
- | `actions` | Actions the server may run (see [Actions](#actions-020)). |
258
- | `onConfirmAction` | Your confirmation UI for actions with `confirm`. Default: a native alert. |
259
- | `options` | Any other `VoiceBot.connect()` option (`noiseGate`, `bargeIn`, `autoReconnect`, `logLevel` …). |
260
- | `disconnectOnUnmount` | Default `true`. |
92
+ ## Actions (optional)
261
93
 
262
- Without `url`, call `VoiceBot.connect({ url, … })` yourself (for example after login).
263
-
264
- ## Actions (0.2.0)
265
-
266
- Let the AI server run operations of your app. Register them on the provider; the SDK validates
267
- params, asks for confirmation where you require it, runs them in order with timeouts, and tells the
268
- 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.
269
96
 
270
97
  ```tsx
271
98
  <VoiceBotProvider
272
99
  url={URL}
273
- navigation={navigation}
100
+ domainId={DOMAIN_ID}
274
101
  actions={{
275
102
  add_to_cart: {
276
103
  description: 'Add a product to the cart',
277
- params: { product: 'string', size: 'string?', quantity: 'integer?' },
278
- run: async ({ product, size, quantity = 1 }) => {
279
- const line = await cart.add(product, size, quantity); // your code
280
- return { ok: true, data: line };
281
- },
104
+ params: { product: 'string', size: 'string?' },
105
+ run: async ({ product, size }) => ({ ok: true, data: await cart.add(product, size) }),
282
106
  },
283
- place_order: { description: 'Place the order', confirm: true, run: () => api.placeOrder() },
284
107
  }}
285
108
  >
286
109
  ```
287
110
 
288
- The server sends `{"type":"actions","requestId":"req_001","steps":[{"action":"add_to_cart",…},{"navigate":"checkout"}]}`
289
- and gets one `action_result`. Also: `useVoiceBotAction()` for screen-only actions,
290
- `useVoiceBotScreenContext()` so the server knows what "this" is, `ActionError` for safe error
291
- codes, `onConfirmAction` for your own confirmation UI. Full guide:
292
- [docs/ACTIONS.md](https://unpkg.com/react-native-voice-bot-sdk/docs/ACTIONS.md).
293
-
294
- ## Reconnecting
295
-
296
- If the connection drops (Wi-Fi change, server restart, close code other than 1000), the SDK
297
- reconnects by itself: after 1 s, 2 s, 4 s … up to 30 s between tries, 20 tries by default. While it
298
- reconnects:
299
-
300
- - `status` is `'connecting'` and the widget shows the spinner;
301
- - **the mic keeps running**, frames recorded while offline are dropped (not queued), and streaming
302
- continues as soon as the socket is open again;
303
- - each reconnect is a **new session**: new `sessionId`, the connect message is sent again, and
304
- `onSuccess` is called again; `onClose` is called for the dropped socket.
305
-
306
- Tapping the mic, or coming back to the app, retries right away. `disconnect()` stops reconnecting.
307
- The server closing with code `1000` is treated as a normal end and is not retried.
308
-
309
- ```ts
310
- VoiceBot.connect({
311
- url,
312
- autoReconnect: { maxAttempts: 10, maxDelayMs: 15000 }, // or false
313
- onReconnecting: ({ attempt, delayMs }) => console.log('reconnect', attempt, delayMs),
314
- });
315
- ```
316
-
317
- ## Noise gate and barge-in
318
-
319
- **Noise gate.** In a real room the pauses between sentences are full of noise, so the server can't
320
- tell where a sentence ends. The SDK checks every 20 ms frame against the room's noise level and,
321
- while nobody is speaking near the phone, sends silence instead. The stream keeps its shape (one
322
- 640-byte frame every 20 ms). The 300 ms before speech starts is kept, so the first syllable isn't
323
- cut, which delays the stream by 300 ms; 700 ms after the last word is kept too. It's an energy gate:
324
- it removes steady noise and makes pauses clean, but people talking near the phone at the same
325
- volume as the user still get through.
326
-
327
- ```ts
328
- VoiceBot.connect({ url, noiseGate: { thresholdDb: 8 } }); // more sensitive (default 10)
329
- VoiceBot.connect({ url, noiseGate: false }); // send the mic unchanged
330
- ```
331
-
332
- **While the bot speaks** (`whileSpeaking`): `'mute'` (default) sends silence while the reply plays
333
- and for `echoTailMs` (600 ms) after the speaker has really finished. On a phone's loudspeaker the
334
- bot's own voice comes back into the mic about as loud as a person (echo cancellation often doesn't
335
- remove it); without the mute the server hears the bot, answers itself, and replies cut each other
336
- off. `'guard'` only counts clearly louder speech (for headsets). `'listen'` treats it like any other
337
- time.
338
-
339
- **Barge-in** (`bargeIn`, default off): with `whileSpeaking: 'guard'`, when the user talks over the
340
- bot for about 300 ms clearly louder than the reply's echo, the reply stops and the rest of it isn't
341
- played. Turn it on only where echo is low (headsets); on a loudspeaker the echo can trigger it.
342
-
343
- **End of playback:** the native module reports when the speaker has really played the last of the
344
- reply (`onPlaybackIdle`), so "speaking" and the mute end at the right time, not on an estimate.
345
-
346
- **Other apps and calls.** While the bot speaks it takes the audio focus, so music from other apps
347
- gets quieter. If another app takes the audio (or a call comes in), the bot's reply stops. During a
348
- phone call the mic sends silence, and normal audio resumes when the call ends (`pauseOnCall`).
349
-
350
- ## Background listening
351
-
352
- On Android, apps lose the microphone in the background unless they run a *foreground service* of
353
- type microphone, which must show a notification. While the mic is on, the SDK runs one, so the voice
354
- bot keeps listening when the user switches apps or locks the screen. The notification goes away
355
- when the mic stops. On Android 13+ the SDK asks for the notification permission the first time; if
356
- it's denied, background listening still works but the notification is hidden.
357
-
358
- ```ts
359
- VoiceBot.connect({ url, backgroundListening: { title: 'My Shop assistant', text: 'Listening…' } });
360
- VoiceBot.connect({ url, backgroundListening: false }); // mic only while the app is on screen
361
- ```
362
-
363
- The library's manifest adds `FOREGROUND_SERVICE`, `FOREGROUND_SERVICE_MICROPHONE` and
364
- `POST_NOTIFICATIONS`, and the service. Apps on Google Play must declare the microphone foreground
365
- service use in the Play Console. iOS: not supported yet.
366
-
367
- ## Navigation ("agentic")
368
-
369
- The server can send `{"type":"navigate","screen":"cart"}` or `{"type":"navigate","action":"back"}`.
370
- The SDK only opens screens it sent to the server, and follows the usual back stack rules:
371
-
372
- - a screen that isn't in the stack is **pushed**;
373
- - a screen that's already in the stack is **popped back to** (the screens above it are removed);
374
- - the visible screen: nothing happens (`already_on_screen`);
375
- - `back` works like the Back button.
376
-
377
- The result goes back to the server as `navigate_result`, and every screen change (voice, tap or
378
- Back) is sent as `screen_changed` with the back stack. Pick the adapter for your app:
379
-
380
- ### Local voice navigation
381
-
382
- If the server's reply doesn't navigate (`type: "none"`) but the user clearly asked for a screen,
383
- the SDK opens it itself:
384
-
385
- | User says | Opens |
386
- |-----------|-------|
387
- | "Open my cart", "go to my cart" | `(tabs)/cart` |
388
- | "Show my orders" | `orders/index` |
389
- | "Take me to my notifications please" | `account/notifications` |
390
- | "Take me home" | the screen at `/` |
391
- | "Go back" | back one screen |
392
- | "Add this to my cart", "search for shoes", "my cart" | nothing (not an "open" request) |
393
-
394
- It needs an "open"-style word (open, show, go to, take me to, view …) and a word that names a
395
- screen. The words come from your route names (`account/addresses` → "addresses", "address");
396
- dynamic routes like `product/[slug]` are left to the server. Add your own words:
397
-
398
- ```tsx
399
- <VoiceBotProvider url={URL} options={{ voiceShortcuts: { '(tabs)/cart': ['bag', 'basket'], 'orders/index': ['order history'] } }}>
400
- ```
401
-
402
- The server's own navigation always wins, and the server still gets `navigate_result` (with
403
- `requestId: "local"`) and `screen_changed`. Turn it off with `options={{ localNavigation: false }}`.
404
-
405
- ### Expo Router
406
-
407
- ```tsx
408
- import { useExpoRouterNavigation } from 'react-native-voice-bot-sdk/expo-router';
409
-
410
- const navigation = useExpoRouterNavigation({ exclude: ['modal'] });
411
- ```
412
-
413
- Call it in the root `_layout.tsx`. Screen names are the file routes: `index`, `products`,
414
- `(tabs)/index`, `product/[id]`. The server can pass `params` for dynamic routes.
415
-
416
- ### React Navigation
417
-
418
- ```tsx
419
- import { NavigationContainer, createNavigationContainerRef } from '@react-navigation/native';
420
- import { VoiceBotProvider, createReactNavigationAdapter } from 'react-native-voice-bot-sdk';
421
-
422
- const navigationRef = createNavigationContainerRef();
423
- const navigation = createReactNavigationAdapter(navigationRef, {
424
- // Optional. Defaults to the screens of the navigators that are mounted.
425
- screens: ['Home', 'Products', { name: 'Cart', parents: ['Shop'] }],
426
- });
427
-
428
- export default function App() {
429
- return (
430
- <VoiceBotProvider url={URL} navigation={navigation}>
431
- <NavigationContainer ref={navigationRef}>{/* navigators */}</NavigationContainer>
432
- </VoiceBotProvider>
433
- );
434
- }
435
- ```
436
-
437
- Written for React Navigation 7 (`popTo`).
438
-
439
- ### Your own navigation (callbacks)
440
-
441
- ```tsx
442
- import { createCallbackNavigation } from 'react-native-voice-bot-sdk';
443
-
444
- const navigation = createCallbackNavigation({
445
- screens: ['Home', 'Products', 'Cart'],
446
- initialScreen: 'Home',
447
- onNavigate: (screen, { action, params }) => myRouter.open(screen.name, params), // action: 'push' | 'popTo'
448
- onBack: () => myRouter.back(),
449
- });
450
-
451
- // When the user moves by hand, tell the SDK:
452
- navigation.setCurrentScreen('Cart');
453
- ```
454
-
455
- ## Logs
456
-
457
- The SDK logs to the console with a `[VoiceBot]` prefix, the time and a level. You see these in
458
- Metro or in `adb logcat` (tag `ReactNativeJS`):
459
-
460
- ```
461
- [VoiceBot] 14:41:41.205 INFO connecting to ws://localhost:8091/demo
462
- [VoiceBot] 14:41:41.512 INFO connected in 307 ms, session=81185a05-ccbf-43be-8ffc-20eae1c65a64
463
- [VoiceBot] 14:41:41.514 INFO → connect message: domain_id=your-domain user_id=(set, hidden) cookie_id=a527edd9… deviceId=1 sampleRate=16000 screens(5)=["cart","index","product/[id]","products","profile"]
464
- [VoiceBot] 14:41:41.520 INFO → screen_changed: "index" backStack=["index"]
465
- [VoiceBot] 14:41:43.101 INFO mic started: PCM s16le 16000 Hz mono, 640-byte frames (20 ms), uplink=BINARY
466
- [VoiceBot] 14:41:43.140 INFO → first audio frame sent
467
- [VoiceBot] 14:41:48.120 INFO → audio streaming: 250 frames (5.00 s)
468
- [VoiceBot] 14:41:49.002 INFO ← you said: "open my cart"
469
- [VoiceBot] 14:41:49.003 INFO ← bot: "Opening your cart"
470
- [VoiceBot] 14:41:49.004 INFO 🔊 bot speaking (reply audio playing)
471
- [VoiceBot] 14:41:49.010 INFO ← navigate: screen="cart" requestId=1
472
- [VoiceBot] 14:41:49.030 INFO → navigate_result: opened "cart"
473
- [VoiceBot] 14:41:49.031 INFO → screen_changed: "cart" backStack=["index","cart"]
474
- [VoiceBot] 14:41:50.300 INFO 🔇 bot finished speaking (1.20 s of audio)
475
- [VoiceBot] 14:41:58.400 INFO mic stopped after 15.3 s: sent 765 frames (15.30 s of audio, 489600 bytes)
476
- [VoiceBot] 14:42:00.000 INFO → closing socket: code=1000 reason="User exited"
477
- ```
478
-
479
- | Level | What is logged |
480
- |-------|----------------|
481
- | `trace` | Everything below, plus **every audio frame** sent (`→ SEND audio frame #123`), 50 lines a second. |
482
- | `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.** |
483
- | `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. |
484
- | `warn` | Problems that don't stop the session: permission denied, dropped frames, unknown screen, abnormal close codes, slow network. **Default in release.** |
485
- | `error` | Connect failed, mic failed, playback failed, navigation threw. |
486
- | `none` | Nothing. |
487
-
488
- ```ts
489
- import { setLogLevel, setLogHandler } from 'react-native-voice-bot-sdk';
490
-
491
- setLogLevel('debug'); // or VoiceBot.connect({ url, logLevel: 'debug' })
492
- setLogHandler((level, message) => myCrashReporter.log(`[VoiceBot] ${level} ${message}`));
493
- ```
494
-
495
- `→` is app to server, `←` is server to app. On Android the native audio module also logs to logcat
496
- with the tag `VoiceBotAudio` (audio source, echo cancel / gain / noise effects, start and stop):
497
-
498
- ```bash
499
- adb logcat -s ReactNativeJS VoiceBotAudio
500
- ```
501
-
502
- ## Removing the SDK
503
-
504
- Remove `<VoiceBotProvider>` (or `<VoiceBotWidget>`) and any `VoiceBot.*` calls, delete the plugin
505
- 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.
506
113
 
507
- ## Audio format
114
+ ## More
508
115
 
509
- Both directions use raw PCM, signed 16-bit little-endian, mono, no header. The mic is always 16 kHz.
510
- Reply audio is played at the reply's `sample_rate` (e.g. `24000`), or 16 kHz if the server doesn't
511
- send one. The mic is sent as
512
- 640-byte (20 ms) binary frames, in order, with no gaps. Android records from `VOICE_COMMUNICATION`
513
- 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)
514
120
 
515
121
  ## License
516
122
 
@@ -41,6 +41,13 @@ 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 `""`. */
@@ -211,6 +218,12 @@ export declare class VoiceBotClient {
211
218
  get isListening(): boolean;
212
219
  /** Opens the socket, sends the connect message (session info + screens), then calls `onSuccess`. */
213
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;
214
227
  private open;
215
228
  private reconnectEnabled;
216
229
  /** Waits (1 s, 2 s, 4 s ... max 30 s) and opens the socket again, keeping the mic running. */
@@ -235,10 +248,19 @@ export declare class VoiceBotClient {
235
248
  * `connect()` options first. Resolves to true when the mic is streaming.
236
249
  */
237
250
  start: () => Promise<boolean>;
238
- /** Stops streaming the mic. The socket stays open. */
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
+ */
239
255
  stop: () => void;
240
- /** start() when idle, stop() when listening. */
256
+ /**
257
+ * start() when idle, stop() when listening. With `disconnectOnStop`, a press while connecting
258
+ * cancels (disconnects) instead of waiting.
259
+ */
241
260
  toggle: () => Promise<void>;
261
+ /** Mic-button session over: mic, reply audio and socket all stop. */
262
+ private endSession;
263
+ private endSessionIfMicOnly;
242
264
  private startBackground;
243
265
  private stopRecording;
244
266
  /** Every 20 ms mic frame from the native module. */
@@ -259,6 +281,13 @@ export declare class VoiceBotClient {
259
281
  private navigateFromReply;
260
282
  /** Queues a reply's audio: stops an older reply first, skips a reply the user talked over. */
261
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;
262
291
  /** Stops the audio of the previous reply so the reply to a new question plays right away. */
263
292
  private interruptPlayback;
264
293
  /** The server's reply didn't navigate: open a screen if the user clearly asked for one. */
@@ -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.replace(/"user_id":"(?:[^"\\]|\\.)+"/g,'"user_id":"(hidden)"'),b=e=>(e/m).toFixed(2),$={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} (${$[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)}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;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(k(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;
@@ -84,6 +84,17 @@ export interface BotReply {
84
84
  sample_rate?: number;
85
85
  [key: string]: unknown;
86
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
+ }
87
98
  /** Server → app: open a screen, or go back. */
88
99
  export interface NavigateCommand {
89
100
  type: 'navigate';
@@ -22,6 +22,13 @@ export interface VoiceBotProviderProps {
22
22
  userId?: string;
23
23
  /** Connect as soon as the provider mounts (when `url` is set). Default `true`. */
24
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';
25
32
  /**
26
33
  * The floating mic button. Default `true` (drop-in voice widget, bottom-right). Pass an object to
27
34
  * style it, or `false` to use your own button with `useVoiceBot().start()` / `stop()`.
@@ -69,4 +76,4 @@ export declare const alertConfirm: ConfirmHandler;
69
76
  * <App />
70
77
  * </VoiceBotProvider>
71
78
  */
72
- export declare function VoiceBotProvider({ children, url, domainId, userId, 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 e,jsxs as n}from"react/jsx-runtime";import{useEffect as o,useRef as t}from"react";import{Alert as r,StyleSheet as s,View as i}from"react-native";import{VoiceBot as c}from"../VoiceBotClient";import{VoiceBotWidget as l}from"./VoiceBotWidget";export const alertConfirm=e=>new Promise((n=>{let o=!1;const t=e=>{o||(o=!0,n(e))};e.signal.addEventListener?.("abort",(()=>t("cancelled"))),r.alert(e.title,e.message||void 0,[{text:e.cancelLabel,style:"cancel",onPress:()=>t("rejected")},{text:e.confirmLabel,onPress:()=>t("approved")}],{cancelable:!0,onDismiss:()=>t("cancelled")})}));export function VoiceBotProvider({children:r,url:s,domainId:d,userId:u,autoConnect:m=!0,widget:p=!0,navigation:f=null,onConnect:C,onError:g,onClose:v,onReply:x,onMessage:y,options:b,actions:j,onConfirmAction:E,disconnectOnUnmount:M=!0}){const R=t({onConnect:C,onError:g,onClose:v,onReply:x,onMessage:y,options:b});return R.current={onConnect:C,onError:g,onClose:v,onReply:x,onMessage:y,options:b},o((()=>{c.setNavigation(f)}),[f]),o((()=>c.addMessageListener((e=>R.current.onMessage?.(e)))),[]),o((()=>{if(j)return c.setActions(j),()=>c.setActions({})}),[j]),o((()=>{c.setConfirmHandler(E??alertConfirm)}),[E]),o((()=>{if(s&&m)return c.connect({...R.current.options,url:s,domainId:d,userId:u,onSuccess:e=>R.current.onConnect?.(e),onFailure:e=>R.current.onError?.(e),onClose:e=>R.current.onClose?.(e),onReply:e=>R.current.onReply?.(e)}),()=>c.disconnect()}),[s,d,u,m]),o((()=>()=>{c.setNavigation(null),M&&c.disconnect()}),[M]),n(i,{style:a.fill,children:[r,p?e(l,{..."object"==typeof p?p:{}}):null]})}const a=s.create({fill:{flex: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 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}});
@@ -110,6 +110,18 @@ Only the **names of your screens** (route names such as `cart`, `products`, `pro
110
110
  code, data or component names. Leave screens out with
111
111
  `useExpoRouterNavigation({ exclude: ['settings/billing'] })`.
112
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
+
113
125
  ## 5. Your own button (optional)
114
126
 
115
127
  Hide the widget and use the hook:
@@ -189,6 +201,81 @@ packages needed) that checks the connect message and the audio frames.
189
201
  - [ ] Test on the oldest Android and iOS versions you support.
190
202
  - [ ] Set `logLevel: 'warn'` (the default in release builds) so requests aren't logged.
191
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
+
192
279
  ## Troubleshooting
193
280
 
194
281
  | Problem | Cause and fix |
package/docs/PROTOCOL.md CHANGED
@@ -15,6 +15,7 @@ Transport: one WebSocket connection per session, e.g. `ws://<host>:8091/demo`.
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 |
@@ -155,6 +156,19 @@ Same as Android:
155
156
  app stops the old audio and plays the new reply right away. So keep `question` the same in every
156
157
  chunk of one reply.
157
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.
158
172
  - The SDK is more lenient than the Android app: a message with missing keys is **not** dropped. It
159
173
  plays `buffer` if present and passes the whole message to the app.
160
174
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-voice-bot-sdk",
3
- "version": "0.2.1",
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",