react-native-voice-bot-sdk 0.1.2 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,63 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.1
4
+
5
+ - **`userId`:** new option on `VoiceBotProvider` and `VoiceBot.connect()`, sent as `user_id` in the
6
+ connect message (next to `domain_id`). Your app's id for the signed-in user in any format (email, phone number, your own id); `""` for
7
+ guests. Never written to the SDK's logs.
8
+ When the provider's `userId` changes (sign in / sign out) it reconnects, so the server gets the
9
+ new user. Backwards compatible: without it `user_id` is `""`.
10
+
11
+ ## 0.2.0
12
+
13
+ **Actions:** the AI server can now run operations that the app registers, not only open screens.
14
+ Fully optional and backwards compatible: apps without actions send exactly the same messages.
15
+
16
+ - **Action registry:** `actions` prop on `VoiceBotProvider`, `VoiceBot.registerAction()`,
17
+ `useVoiceBotAction()`. Each action has a description, a params schema (short forms like
18
+ `'string?'`, `'S|M|L'`, or full specs with min/max/enum), a `run` handler, `timeoutMs`, `confirm`
19
+ and `idempotent`. The SDK contains no business actions.
20
+ - **Protocol:** `actions` metadata in the connect message (and `actions_update`); new messages
21
+ `actions` (server → app), `action_result` (one per request), `action_status` (repeats),
22
+ `cancel_actions`, `action_ack`. See docs/PROTOCOL.md section 11.
23
+ - **Execution engine:** steps run in order (actions and navigation), requests one at a time;
24
+ allowlist and param validation; per-action timeouts with an abort signal; a failed step stops the
25
+ request; repeated requestIds are never run twice; results that finish while offline are sent after
26
+ reconnecting; finished requests are forgotten after 10 minutes. Thrown errors are reported with
27
+ safe messages (`ActionError` for your own codes).
28
+ - **Confirmation:** actions marked `confirm` run only after the user approves; default native alert,
29
+ or your own UI with `onConfirmAction`. The server can't skip it.
30
+ - **Screen context:** `screen_changed` includes small `params` (route params plus
31
+ `useVoiceBotScreenContext()` / `VoiceBot.setScreenContext()`).
32
+ - **Echo (breaking voice, cut-off sentences, repeated replies):** on a phone loudspeaker the bot's
33
+ own voice reached the mic at speech level, so barge-in cut replies off and the server answered the
34
+ bot's own words. Now the mic is **muted while the bot speaks** by default (`whileSpeaking: 'mute'`,
35
+ plus `echoTailMs`, default 600 ms, after playback), and **barge-in is off** by default
36
+ (`bargeIn: true` to enable, with `whileSpeaking: 'guard'`, for headsets).
37
+ - **Real end of playback:** the native module sends `onPlaybackIdle` when the speaker has played the
38
+ last frame of the reply (Android: AudioTrack playback position; iOS: buffers played back), so
39
+ "speaking" and the mute end on time instead of on an estimate. Needs a native rebuild; older
40
+ native code falls back to the estimate.
41
+ - **Logs:** SDK warnings and errors no longer use `console.warn` / `console.error`, so they don't
42
+ pop up React Native's LogBox in the host app (the level is still in each line).
43
+ - Example app: a demo shop with a real cart and example actions (search, add/remove/update cart,
44
+ coupon, cart summary, place order with confirmation).
45
+
46
+ ## 0.1.3
47
+
48
+ Navigation fixes found in a real app (Expo Router, tabs, a start route left out of the screens).
49
+
50
+ - **Switching to a tab you visited before** ("open my account" from the Cart tab) now always
51
+ switches tabs. Before, some tab setups were treated like a back stack, the SDK tried to "go back"
52
+ to the tab (`dismissTo`), nothing happened, and it still reported `opened`.
53
+ - **Home with an excluded start route:** when the app has a root `index` (e.g. one that redirects
54
+ to a welcome screen) next to `(tabs)/index`, opening Home now goes to `(tabs)/index` instead of
55
+ the start route. The SDK checks every route the app has, not only the ones it sends.
56
+ - **No more false "opened":** after navigating, the SDK checks that the visible screen really
57
+ changed. If not, it tries once more with `router.navigate`, and otherwise reports `failed` with
58
+ the screen the app is on.
59
+ - Tip for tab apps: move the floating mic above your tab bar with `widget={{ bottom: 90 }}`.
60
+
3
61
  ## 0.1.2
4
62
 
5
63
  Navigation fixes for Expo Router apps with tabs, nested folders and dynamic routes, and local
@@ -49,8 +107,8 @@ React Native and Expo apps.
49
107
  Navigation, or your own router (callbacks).
50
108
  - **Cleaner audio for the server.** A noise gate sends silence instead of room noise between
51
109
  sentences, so the server can tell where a sentence ends.
52
- - **Barge-in.** Talking over the bot stops its reply. The bot's own voice coming back into the mic
53
- is ignored (`whileSpeaking: 'guard'`).
110
+ - **Barge-in (optional).** With `bargeIn: true` and `whileSpeaking: 'guard'`, talking over the bot
111
+ stops its reply. Off by default (see 0.2.0).
54
112
  - **New replies replace old ones.** A reply to a new question stops the previous reply's audio.
55
113
  - **Background listening (Android).** The mic keeps working when the app is in the background,
56
114
  with a notification while it's on.
package/README.md CHANGED
@@ -7,11 +7,13 @@ talk; the SDK streams their voice to your voice server, plays the spoken answer,
7
7
  - ✅ One wrapper, one floating mic button: no other UI work needed
8
8
  - ✅ Or your own button with the `useVoiceBot()` hook
9
9
  - ✅ The server can navigate your app (Expo Router, React Navigation, or your own router)
10
- - ✅ Clean audio: noise gate, barge-in (talk over the bot), echo guard
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
11
13
  - ✅ Keeps listening in the background (Android), reconnects by itself, handles phone calls
12
14
  - ✅ Every request and response in the console, TypeScript-first
13
15
 
14
- > Integration guide: [docs/INTEGRATION.md](https://unpkg.com/react-native-voice-bot-sdk/docs/INTEGRATION.md) · Wire protocol for the server team:
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:
15
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)
16
18
 
17
19
  ## Requirements
@@ -96,7 +98,7 @@ export default function RootLayout() {
96
98
  const navigation = useExpoRouterNavigation(); // lets the server open your screens
97
99
 
98
100
  return (
99
- <VoiceBotProvider url="wss://voice.example.com/demo" domainId="YOUR_DOMAIN_ID" navigation={navigation}>
101
+ <VoiceBotProvider url="wss://voice.example.com/demo" domainId="YOUR_DOMAIN_ID" userId={currentUserId} navigation={navigation}>
100
102
  <Stack />
101
103
  </VoiceBotProvider>
102
104
  );
@@ -110,13 +112,17 @@ import { VoiceBotProvider } from 'react-native-voice-bot-sdk';
110
112
 
111
113
  export default function App() {
112
114
  return (
113
- <VoiceBotProvider url="wss://voice.example.com/demo" domainId="YOUR_DOMAIN_ID">
115
+ <VoiceBotProvider url="wss://voice.example.com/demo" domainId="YOUR_DOMAIN_ID" userId={currentUserId}>
114
116
  <AppNavigator />
115
117
  </VoiceBotProvider>
116
118
  );
117
119
  }
118
120
  ```
119
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
+
120
126
  That's the whole setup for the **widget-only** integration: the provider connects to your server
121
127
  and shows the floating mic (bottom-right). The user taps it to talk and taps again to stop.
122
128
 
@@ -139,6 +145,7 @@ the mic:
139
145
  {
140
146
  "sessionId": "c0a8f6e2-…",
141
147
  "domain_id": "YOUR_DOMAIN_ID",
148
+ "user_id": "YOUR_USER_ID",
142
149
  "cookie_id": "9b2e4c1a-…",
143
150
  "type": "Buffer",
144
151
  "deviceId": 1,
@@ -155,7 +162,7 @@ the mic:
155
162
  <VoiceBotProvider url={URL} widget={false}> {/* no widget: use your own button */}
156
163
  ```
157
164
 
158
- You can also place `<VoiceBotWidget />` yourself anywhere. The widget shows a spinner while
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
159
166
  connecting, a pulsing red ring while listening, and green while the bot is speaking.
160
167
 
161
168
  ## Your own button
@@ -188,6 +195,7 @@ with the options from the last `connect()` call and then starts the mic.
188
195
  |--------|------|-------------|
189
196
  | `url` | `string` | **Required.** WebSocket URL of the voice server. |
190
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. |
191
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. |
192
200
  | `onSuccess` | `({ sessionId }) => void` | Connected; the connect message (with the screen names) was sent. |
193
201
  | `onFailure` | `(error) => void` | Couldn't connect. `error.code`: `connect_failed`, `connect_timeout`, `native_missing`, ... |
@@ -202,8 +210,9 @@ with the options from the last `connect()` call and then starts the mic.
202
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). |
203
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. |
204
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). |
205
- | `whileSpeaking` | `'guard' \| 'mute' \| 'listen'` | What the mic does while the bot speaks. Default `'guard'`. |
206
- | `bargeIn` | `boolean` | Default `true`: talking over the bot stops its reply. |
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. |
207
216
  | `pauseOnCall` | `boolean` | Default `true`: during a phone call, stop the bot's audio and send silence. |
208
217
  | `keepSessionOnReconnect` | `boolean` | Default `false`. `true` keeps the same `sessionId` after an automatic reconnect. |
209
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). |
@@ -229,6 +238,8 @@ const { status, isReady, isListening, speaking, lastQuestion, lastPrompt, lastMe
229
238
  | `error` / `lastError` | Last error (`{ code, message }`), or `null`. |
230
239
  | `start`, `stop`, `toggle` | Mic on / off. `start()` asks for the mic permission the first time and reconnects if needed. |
231
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`. |
232
243
  | `addMessageListener(fn)` | Every JSON message from the server. Returns an unsubscribe function. |
233
244
 
234
245
  ### `<VoiceBotProvider>`
@@ -237,16 +248,49 @@ const { status, isReady, isListening, speaking, lastQuestion, lastPrompt, lastMe
237
248
  |------|-------------|
238
249
  | `url` | Voice server WebSocket URL. When set, the provider connects by itself. |
239
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. |
240
252
  | `autoConnect` | Default `true` (when `url` is set). |
241
253
  | `widget` | Default `true`: the floating mic. Widget props to style it, `false` to use your own button. |
242
254
  | `navigation` | A navigation adapter, so the server can open screens (see below). |
243
255
  | `onConnect`, `onError`, `onClose` | Connection callbacks. |
244
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. |
245
259
  | `options` | Any other `VoiceBot.connect()` option (`noiseGate`, `bargeIn`, `autoReconnect`, `logLevel` …). |
246
260
  | `disconnectOnUnmount` | Default `true`. |
247
261
 
248
262
  Without `url`, call `VoiceBot.connect({ url, … })` yourself (for example after login).
249
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.
269
+
270
+ ```tsx
271
+ <VoiceBotProvider
272
+ url={URL}
273
+ navigation={navigation}
274
+ actions={{
275
+ add_to_cart: {
276
+ 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
+ },
282
+ },
283
+ place_order: { description: 'Place the order', confirm: true, run: () => api.placeOrder() },
284
+ }}
285
+ >
286
+ ```
287
+
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
+
250
294
  ## Reconnecting
251
295
 
252
296
  If the connection drops (Wi-Fi change, server restart, close code other than 1000), the SDK
@@ -285,12 +329,19 @@ VoiceBot.connect({ url, noiseGate: { thresholdDb: 8 } }); // more sensitive (def
285
329
  VoiceBot.connect({ url, noiseGate: false }); // send the mic unchanged
286
330
  ```
287
331
 
288
- **While the bot speaks** (`whileSpeaking`): `'guard'` (default) needs 8 dB louder speech, so the
289
- bot's own voice coming back into the mic isn't taken as the user. `'mute'` sends silence while the
290
- bot speaks. `'listen'` treats it like any other time.
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.
291
342
 
292
- **Barge-in** (`bargeIn`, default on): when the user talks over the bot for about 200 ms, the bot's
293
- reply stops right away, and the rest of that reply is not played.
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.
294
345
 
295
346
  **Other apps and calls.** While the bot speaks it takes the audio focus, so music from other apps
296
347
  gets quieter. If another app takes the audio (or a call comes in), the bot's reply stops. During a
@@ -409,7 +460,7 @@ Metro or in `adb logcat` (tag `ReactNativeJS`):
409
460
  ```
410
461
  [VoiceBot] 14:41:41.205 INFO connecting to ws://localhost:8091/demo
411
462
  [VoiceBot] 14:41:41.512 INFO connected in 307 ms, session=81185a05-ccbf-43be-8ffc-20eae1c65a64
412
- [VoiceBot] 14:41:41.514 INFO → connect message: domain_id=your-domain cookie_id=a527edd9… deviceId=1 sampleRate=16000 screens(5)=["cart","index","product/[id]","products","profile"]
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"]
413
464
  [VoiceBot] 14:41:41.520 INFO → screen_changed: "index" backStack=["index"]
414
465
  [VoiceBot] 14:41:43.101 INFO mic started: PCM s16le 16000 Hz mono, 640-byte frames (20 ms), uplink=BINARY
415
466
  [VoiceBot] 14:41:43.140 INFO → first audio frame sent
@@ -54,15 +54,21 @@ class VoiceBotAudioModule : Module() {
54
54
  private var playbackExecutor: ExecutorService? = null
55
55
  /** Bumped by stopPlayback(); queued or running writes from before a stop are dropped. */
56
56
  @Volatile private var playbackGeneration = 0
57
+ /** Chunks queued but not written yet (current generation only). */
58
+ private val pendingChunks = java.util.concurrent.atomic.AtomicInteger(0)
59
+ /** Frames written to the current AudioTrack (to know when the speaker has played everything). */
60
+ @Volatile private var framesWritten = 0L
57
61
 
58
62
  override fun definition() = ModuleDefinition {
59
63
  Name("VoiceBotAudio")
60
64
 
61
- Events("onAudioFrame", "onAudioError", "onAudioInterruption")
65
+ Events("onAudioFrame", "onAudioError", "onAudioInterruption", "onPlaybackIdle")
62
66
 
63
67
  Constants(
64
68
  "sampleRate" to SAMPLE_RATE,
65
- "frameBytes" to FRAME_BYTES
69
+ "frameBytes" to FRAME_BYTES,
70
+ // JS waits for onPlaybackIdle (the real end of playback) when this is true.
71
+ "playbackIdleEvents" to true
66
72
  )
67
73
 
68
74
  Function("getAppInfo") {
@@ -267,6 +273,7 @@ class VoiceBotAudioModule : Module() {
267
273
  .build()
268
274
  track.play()
269
275
  audioTrack = track
276
+ framesWritten = 0L
270
277
  requestFocus()
271
278
  return track
272
279
  }
@@ -281,8 +288,10 @@ class VoiceBotAudioModule : Module() {
281
288
  val (executor, gen) = synchronized(lock) {
282
289
  (playbackExecutor ?: Executors.newSingleThreadExecutor().also { playbackExecutor = it }) to playbackGeneration
283
290
  }
291
+ pendingChunks.incrementAndGet()
284
292
  executor.execute {
285
293
  if (gen != playbackGeneration) return@execute
294
+ var written = 0
286
295
  try {
287
296
  val track = synchronized(lock) { if (gen == playbackGeneration) ensureTrack(rate) else null } ?: return@execute
288
297
  // Odd byte counts would shift every following sample; drop a trailing odd byte.
@@ -294,17 +303,53 @@ class VoiceBotAudioModule : Module() {
294
303
  if (w <= 0) break
295
304
  off += w
296
305
  }
306
+ written = off
297
307
  } catch (e: Exception) {
298
308
  if (gen != playbackGeneration) return@execute // stopped while writing
299
309
  Log.e(TAG, "Playback failed: ${e.message}")
300
310
  sendEvent("onAudioError", mapOf("message" to "Playback failed: ${e.message}"))
311
+ } finally {
312
+ if (gen == playbackGeneration) {
313
+ framesWritten += written / 2
314
+ if (pendingChunks.decrementAndGet() <= 0) {
315
+ pendingChunks.set(0)
316
+ watchForIdle(gen)
317
+ }
318
+ }
319
+ }
320
+ }
321
+ }
322
+
323
+ /**
324
+ * After the last queued chunk is written, waits until the speaker has really played every frame
325
+ * (the AudioTrack's playback position reaches the frames written), then tells JS. Cancelled by a
326
+ * new chunk or a stop.
327
+ */
328
+ private fun watchForIdle(gen: Int) {
329
+ val started = System.currentTimeMillis()
330
+ val check = object : Runnable {
331
+ override fun run() {
332
+ if (gen != playbackGeneration || pendingChunks.get() > 0) return
333
+ val track = audioTrack
334
+ val head = try { track?.playbackHeadPosition?.toLong()?.and(0xffffffffL) ?: Long.MAX_VALUE } catch (_: Exception) { Long.MAX_VALUE }
335
+ val rate = track?.sampleRate ?: SAMPLE_RATE
336
+ val maxWait = (framesWritten * 1000L / rate) + 3000L
337
+ if (head >= framesWritten || System.currentTimeMillis() - started > maxWait) {
338
+ Log.i(TAG, "Playback finished ($framesWritten frames at $rate Hz)")
339
+ sendEvent("onPlaybackIdle", mapOf("frames" to framesWritten, "sampleRate" to rate))
340
+ } else {
341
+ mainHandler.postDelayed(this, 40)
342
+ }
301
343
  }
302
344
  }
345
+ mainHandler.post(check)
303
346
  }
304
347
 
305
348
  private fun stopPlayback() {
306
349
  val (executor, track) = synchronized(lock) {
307
350
  playbackGeneration++
351
+ pendingChunks.set(0)
352
+ framesWritten = 0L
308
353
  val e = playbackExecutor
309
354
  val t = audioTrack
310
355
  playbackExecutor = null
@@ -22,3 +22,7 @@ export declare function stopBackgroundService(): void;
22
22
  export declare function releaseAudioFocus(): void;
23
23
  /** Calls, other apps taking the audio. Returns an unsubscribe function. */
24
24
  export declare function onInterruption(listener: (reason: InterruptionReason) => void): () => void;
25
+ /** True if the native module reports the real end of reply playback (`onPlaybackIdle`). */
26
+ export declare function hasPlaybackIdleEvents(): boolean;
27
+ /** Called when all queued reply audio has really been played. Returns an unsubscribe function. */
28
+ export declare function onPlaybackIdle(listener: () => void): () => void;
@@ -1 +1 @@
1
- import{requireOptionalNativeModule as e}from"expo-modules-core";import{PermissionsAndroid as t,Platform as r}from"react-native";const o=e("VoiceBotAudio");export const NATIVE_MISSING_MESSAGE="The VoiceBotAudio native module is not available. Expo Go cannot load it: use a development build (`npx expo run:android`) or rebuild your bare app after installing the package.";export function isNativeAvailable(){return null!=o}function n(){if(!o)throw new Error(NATIVE_MISSING_MESSAGE);return o}export function getPackageName(){try{return o?.getAppInfo().packageName??""}catch{return""}}export async function requestMicPermission(){const e=n();return!!e.hasPermission()||("android"===r.OS?await t.request(t.PERMISSIONS.RECORD_AUDIO)===t.RESULTS.GRANTED:!!e.requestPermission&&e.requestPermission())}export function startRecording(e,t){const r=n(),o=[r.addListener("onAudioFrame",(t=>e(t.data))),r.addListener("onAudioError",(e=>t(e.message)))],a=()=>o.forEach((e=>e.remove()));return r.startRecording().then((()=>a),(e=>{throw a(),e}))}export function stopRecording(){o?.stopRecording()}export function enqueuePlayback(e,t=16e3){n().enqueuePlayback(e,t)}export function stopPlayback(){o?.stopPlayback()}export function getPersistentId(e){try{return o?.getPersistentId?.(e)??null}catch{return null}}let a=!1;export async function startBackgroundService(e,n){if("android"!==r.OS||!o?.startBackgroundService)return!1;const i=t.PERMISSIONS.POST_NOTIFICATIONS;if(!a&&i&&Number(r.Version)>=33){a=!0;try{await t.check(i)||await t.request(i)}catch{}}try{return o.startBackgroundService(e,n)}catch{return!1}}export function stopBackgroundService(){try{o?.stopBackgroundService?.()}catch{}}export function releaseAudioFocus(){try{o?.releaseAudioFocus?.()}catch{}}export function onInterruption(e){if(!o)return()=>{};try{const t=o.addListener("onAudioInterruption",(t=>e(t.reason)));return()=>t.remove()}catch{return()=>{}}}
1
+ import{requireOptionalNativeModule as e}from"expo-modules-core";import{PermissionsAndroid as t,Platform as r}from"react-native";const n=e("VoiceBotAudio");export const NATIVE_MISSING_MESSAGE="The VoiceBotAudio native module is not available. Expo Go cannot load it: use a development build (`npx expo run:android`) or rebuild your bare app after installing the package.";export function isNativeAvailable(){return null!=n}function o(){if(!n)throw new Error(NATIVE_MISSING_MESSAGE);return n}export function getPackageName(){try{return n?.getAppInfo().packageName??""}catch{return""}}export async function requestMicPermission(){const e=o();return!!e.hasPermission()||("android"===r.OS?await t.request(t.PERMISSIONS.RECORD_AUDIO)===t.RESULTS.GRANTED:!!e.requestPermission&&e.requestPermission())}export function startRecording(e,t){const r=o(),n=[r.addListener("onAudioFrame",(t=>e(t.data))),r.addListener("onAudioError",(e=>t(e.message)))],a=()=>n.forEach((e=>e.remove()));return r.startRecording().then((()=>a),(e=>{throw a(),e}))}export function stopRecording(){n?.stopRecording()}export function enqueuePlayback(e,t=16e3){o().enqueuePlayback(e,t)}export function stopPlayback(){n?.stopPlayback()}export function getPersistentId(e){try{return n?.getPersistentId?.(e)??null}catch{return null}}let a=!1;export async function startBackgroundService(e,o){if("android"!==r.OS||!n?.startBackgroundService)return!1;const c=t.PERMISSIONS.POST_NOTIFICATIONS;if(!a&&c&&Number(r.Version)>=33){a=!0;try{await t.check(c)||await t.request(c)}catch{}}try{return n.startBackgroundService(e,o)}catch{return!1}}export function stopBackgroundService(){try{n?.stopBackgroundService?.()}catch{}}export function releaseAudioFocus(){try{n?.releaseAudioFocus?.()}catch{}}export function onInterruption(e){if(!n)return()=>{};try{const t=n.addListener("onAudioInterruption",(t=>e(t.reason)));return()=>t.remove()}catch{return()=>{}}}export function hasPlaybackIdleEvents(){try{return!0===n?.playbackIdleEvents}catch{return!1}}export function onPlaybackIdle(e){if(!n)return()=>{};try{const t=n.addListener("onPlaybackIdle",(()=>e()));return()=>t.remove()}catch{return()=>{}}}
@@ -1,3 +1,5 @@
1
+ import { ActionRegistry } from './actions/registry';
2
+ import type { ActionDefinition, ActionMetadata, ConfirmHandler } from './actions/types';
1
3
  import { type NoiseGateOptions, type WhileSpeaking } from './audio/noiseGate';
2
4
  import { type LogLevel } from './logger';
3
5
  import { type VoiceShortcuts } from './navigation/localIntent';
@@ -43,6 +45,13 @@ export interface ConnectOptions {
43
45
  uplinkEncoding?: 'binary' | 'base64';
44
46
  /** `domain_id` in the connect message: your domain / tenant id. Default `""`. */
45
47
  domainId?: string;
48
+ /**
49
+ * `user_id` in the connect message: your app's id for the signed-in user, in any format you choose
50
+ * (an email, a phone number, an internal or random id). Sent as is. Default `""` (no user, e.g. a
51
+ * guest). It is never written to the SDK's logs. When it changes (sign in / sign out), connect again so the server gets the new one;
52
+ * `<VoiceBotProvider userId>` does that for you.
53
+ */
54
+ userId?: string;
46
55
  /**
47
56
  * `cookie_id` in the connect message: the visitor id. Default: a random id that the SDK saves on
48
57
  * the device, so it stays the same across app launches (until the app is uninstalled or its data
@@ -97,13 +106,23 @@ export interface ConnectOptions {
97
106
  */
98
107
  noiseGate?: boolean | Omit<NoiseGateOptions, 'enabled' | 'whileSpeaking'>;
99
108
  /**
100
- * What the mic does while the bot is speaking. `'guard'` (default): only louder speech counts, so
101
- * the bot's own voice coming back through the mic is ignored. `'mute'`: send silence (no
102
- * barge-in). `'listen'`: same as any other time.
109
+ * What the mic does while the bot is speaking. `'mute'` (default): send silence, so the bot's own
110
+ * voice coming out of the speaker can't reach the server (on a phone speaker, echo cancellation
111
+ * often doesn't remove it). `'guard'`: only louder speech counts (use with headsets, together with
112
+ * `bargeIn`). `'listen'`: same as any other time.
103
113
  */
104
114
  whileSpeaking?: WhileSpeaking;
105
- /** Stop the bot's reply when the user starts talking over it (about 200 ms of speech). Default `true`. */
115
+ /**
116
+ * Stop the bot's reply when the user starts talking over it. Default `false`: on a phone speaker
117
+ * the bot's own echo can be mistaken for the user and cut the reply off. Needs
118
+ * `whileSpeaking: 'guard'` (or 'listen').
119
+ */
106
120
  bargeIn?: boolean;
121
+ /**
122
+ * After the bot's reply has finished playing, keep the mic muted this long (ms), so the end of
123
+ * the reply and room echo don't reach the server. Default 600. Only with `whileSpeaking: 'mute'`.
124
+ */
125
+ echoTailMs?: number;
107
126
  /** During a phone call, stop the bot's audio and send silence until the call ends. Default `true`. */
108
127
  pauseOnCall?: boolean;
109
128
  /**
@@ -164,11 +183,23 @@ export declare class VoiceBotClient {
164
183
  private lastReplyNavKey;
165
184
  /** `question` of the reply whose audio is playing (to tell new replies from more chunks). */
166
185
  private playingQuestion;
186
+ /** When the bot last stopped speaking (for the echo tail). */
187
+ private speakingEndedAt;
188
+ private readonly realPlaybackEnd;
167
189
  /** Reply the user talked over: its remaining chunks are not played. */
168
190
  private bargedQuestion;
169
191
  private gate;
170
192
  private inCall;
171
193
  private lastSessionId;
194
+ /**
195
+ * Actions the host app lets the AI server run. Register with `VoiceBot.registerAction()` or the
196
+ * provider's `actions` prop. Empty by default: then the SDK behaves exactly as without actions.
197
+ */
198
+ readonly actions: ActionRegistry;
199
+ private readonly engine;
200
+ private confirmHandler;
201
+ private lastActionsKey;
202
+ private screenContext;
172
203
  private lastReplyNavAt;
173
204
  getState: () => VoiceBotState;
174
205
  /** Subscribe to state changes. Returns an unsubscribe function. */
@@ -232,14 +263,56 @@ export declare class VoiceBotClient {
232
263
  private interruptPlayback;
233
264
  /** The server's reply didn't navigate: open a screen if the user clearly asked for one. */
234
265
  private localNavigate;
266
+ /**
267
+ * The bot's reply is (still) playing. With native playback-end events the reply ends when the
268
+ * speaker has really played everything (`onPlaybackIdle`); the timer is only a fallback.
269
+ * Otherwise the end is estimated from the audio length.
270
+ */
235
271
  private markSpeaking;
272
+ private finishSpeaking;
273
+ /** True while the bot's voice may still be coming out of the speaker (reply + echo tail). */
274
+ private botAudible;
275
+ /**
276
+ * Lets the AI server run an action of your app. Returns a function that removes it again.
277
+ * The server learns about it in the connect message (or an `actions_update` if already connected).
278
+ */
279
+ registerAction: (name: string, definition: ActionDefinition) => (() => void);
280
+ unregisterAction: (name: string) => void;
281
+ /** Replaces all registered actions (what the provider's `actions` prop does). */
282
+ setActions: (actions: Record<string, ActionDefinition>) => void;
283
+ /** What the server is told about the registered actions. */
284
+ getActions: () => ActionMetadata[];
285
+ /**
286
+ * The UI that asks the user before an action marked `confirm` runs. The provider sets a default
287
+ * (a native alert); pass your own to show your own sheet, or `null` to remove it (such actions
288
+ * then fail with CONFIRMATION_UNAVAILABLE).
289
+ */
290
+ setConfirmHandler: (handler: ConfirmHandler | null) => void;
291
+ /**
292
+ * Small context about what the user is looking at, sent with `screen_changed` (e.g.
293
+ * `{ itemId: 'A12', selectedColor: 'red' }`), so the server understands "this one". It's cleared
294
+ * when the user moves to another screen. Only short strings, numbers and booleans are sent; don't
295
+ * put personal data here.
296
+ */
297
+ setScreenContext: (params: Record<string, unknown> | null) => void;
298
+ private trySend;
299
+ private sendActionsUpdate;
300
+ /** A navigate step of an actions request: the normal navigation rules, reported in action_result. */
301
+ private navigateForStep;
302
+ /** Route params of the visible screen plus the app's context: short, flat values only. */
303
+ private currentScreenParams;
236
304
  /** Registers (or clears with `null`) the host app's navigation. */
237
305
  setNavigation: (adapter: NavigationAdapter | null) => void;
238
306
  private sendScreenChanged;
307
+ /**
308
+ * Waits (up to about 1.5 s) for the visible screen to become `target`. Returns the visible screen.
309
+ * Skipped in the background, where JS timers are paused.
310
+ */
311
+ private waitForScreen;
239
312
  /** Finds the screen the server asked for (see `matchScreen` for the rules). */
240
313
  private matchScreen;
241
314
  /** Runs a navigate command (also usable by the host for testing). */
242
- handleNavigate: (cmd: NavigateCommand) => Promise<NavigateResultMessage>;
315
+ handleNavigate: (cmd: NavigateCommand, report?: boolean) => Promise<NavigateResultMessage>;
243
316
  }
244
317
  /** Shared voice bot session. */
245
318
  export declare const VoiceBot: VoiceBotClient;
@@ -1 +1 @@
1
- import{AppState as e}from"react-native";import*as t from"./NativeAudio";import{NoiseGate as s}from"./audio/noiseGate";import{base64ByteLength as n,base64ToBytes as i,bytesToBase64 as o}from"./base64";import{logger as a,preview as r,setLogLevel as c}from"./logger";import{findLocalIntent as h}from"./navigation/localIntent";import{decideMove as l,dynamicParams as d,matchScreen as p}from"./navigation/match";import{BYTES_PER_SECOND as u,SAMPLE_RATE as g}from"./protocol";function m(){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 f=new Uint8Array(640),y=e=>(e/u).toFixed(2),S={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=m(),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=g,this.lastReplyNavKey=null,this.playingQuestion=null,this.bargedQuestion=null,this.gate=null,this.inCall=!1,this.lastSessionId=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&&c(e.logLevel),this.wantConnected=!0,this.reconnectAttempt=0,this.clearReconnectTimer(),this.open()},this.disconnect=()=>{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 a.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,n=this.options?.noiseGate??!0;return this.gate=new s({..."object"==typeof n?n:{},enabled:!1!==n,whileSpeaking:this.options?.whileSpeaking??"guard"}),this.inCall=!1,this.stopMic=await t.startRecording((t=>this.onMicFrame(t,e)),(e=>{a.error(`mic error: ${e}`),this.setState({lastError:{code:"mic_failed",message:e}})})),this.isConnected?(this.setState({status:"listening",lastError:null}),this.startBackground(),a.info(`mic started: PCM s16le ${g} Hz mono, 640-byte frames (20 ms), uplink=${e?"base64 TEXT":"BINARY"}, noise gate ${!1===n?"off":"on"}, while bot speaks: ${this.options?.whileSpeaking??"guard"}, barge-in `+(!1===this.options?.bargeIn?"off":"on")),!0):(this.stopRecording(),!1)}catch(e){return a.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.setNavigation=e=>{e!==this.navigation&&(this.navUnsubscribe?.(),this.navUnsubscribe=null,this.navigation=e,e&&(a.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=>{const t="back"===e.action,s={type:"navigate_result",sessionId:this.state.sessionId??"",screen:e.screen??null,action:t?"back":"open",className:null,status:"failed",message:"",requestId:e.requestId??null},n=(e,t="",n=s.className)=>{s.status=e,s.message=t,s.className=n;const i=`→ navigate_result: ${e} ${"back"===s.action?"back":`"${s.screen}"`}`+(n&&n!==s.screen?` → ${n}`:"")+(t?` (${t})`:"");return"failed"===e?a.error(i):"unknown_screen"===e||"not_supported"===e?a.warn(i):a.info(i),this.sendJson(s),s},i=this.navigation;if(!i)return n("not_supported","The app has no navigation registered with the voice bot");try{if(t){const e=i.getCurrentScreen();return await i.goBack()?n("went_back","",e):n("not_supported","Nothing to go back to",e)}if(!e.screen)return n("unknown_screen","No screen given");const s=this.matchScreen(e.screen);if(!s)return n("unknown_screen",`Not in the screens list: ${e.screen}`,null);const o=s.screen,r={...s.params??{},...e.params??{}},c=Object.keys(r).length?r:void 0,h=d(o.name).filter((e=>void 0===c?.[e]||""===c[e]));if(h.length){const e=o.name.replace(/\[(?:\.\.\.)?([^\]]+)\]/g,((e,t)=>`<${t}>`));return n("failed",`${o.name} needs ${h.join(", ")}: send "screen": "${e.replace(/^\(.*?\)\//,"")}" or "params": { ${h.map((e=>`"${e}": "…"`)).join(", ")} }`,o.name)}const p=i.getCurrentScreen(),u=i.getBackStack(),g=l(o.name,p,u,!!c);return"already_on_screen"===g?n("already_on_screen","",o.name):("popTo"===g?await i.popTo(o,c):await i.push(o,c),a.debug(`navigate: ${g} ${o.name}${c?` ${JSON.stringify(c)}`:""} (from ${p??"-"})`),n("opened","",o.name))}catch(e){return n("failed",e?.message??String(e))}},t.onInterruption((e=>this.handleInterruption(e)));try{e.addEventListener("change",(e=>{"active"===e&&this.reconnectTimer&&(a.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(),a.info(`connecting to ${s}`);let i=!1;const o=new WebSocket(s);o.binaryType="arraybuffer",this.ws=o;const r=e.connectTimeoutMs??1e4,c=()=>{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(c,r),this.connectDeadline=Date.now()+r,this.onConnectDeadline=c,o.onopen=()=>{if(this.ws!==o)return;i=!0,this.clearConnectTimer();const t=n&&e.keepSessionOnReconnect&&this.lastSessionId?this.lastSessionId:m();this.lastSessionId=t,this.replyCount=0,this.lastReplyNavKey=null;const s=null!=this.stopMic;this.setState({status:s?"listening":"connected",sessionId:t,lastError:null}),a.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(),e.onSuccess?.({sessionId:t}),e.autoStart&&this.start()},o.onmessage=e=>{this.ws===o&&("string"==typeof e.data?this.handleText(e.data):a.debug(`← RECV binary message ignored (${e.data?.byteLength??"?"} bytes)`))},o.onerror=e=>{this.ws===o&&(e?.message&&a.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 r=t.code??1006,c=`socket closed: code=${r} (${S[r]??"unknown"})${t.reason?` reason="${t.reason}"`:""}`;if(1e3===r?a.info(c):a.warn(c),e.onClose?.({code:r,reason:t.reason??""}),1e3!==r&&this.wantConnected&&this.reconnectEnabled())return this.setState({sessionId:null}),void this.scheduleReconnect(c);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 a.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));a.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){a.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){a.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);a.debug(`→ SEND ${r(t)}`),this.ws.send(t)}else a.warn(`not sent (socket not open): ${r(e,120)}`)}sendConnectMessage(e){this.screens=this.navigation?.getScreens()??[];const t={sessionId:e,domain_id:this.options?.domainId??"",cookie_id:this.options?.cookieId||this.getSavedCookieId()||this.runCookieId,type:"Buffer",deviceId:this.options?.deviceId??1,sampleRate:g,screens:this.screens.map((e=>e.name))};var s;a.info(`→ connect message: domain_id=${t.domain_id||'""'} cookie_id=${s=t.cookie_id,s?`${s.slice(0,8)}…`:"-"} deviceId=${t.deviceId} sampleRate=${t.sampleRate} screens(${t.screens.length})=${JSON.stringify(t.screens)}`),t.screens.length||a.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};a.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&&a.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;a.info(`mic stopped after ${(n/1e3).toFixed(1)} s: sent ${this.framesSent} frames (${y(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=i(e);if(this.inCall)s=f;else if(this.gate){const e=this.gate.process(s,this.state.speaking);void 0!==e.speechEvent&&a.debug(e.speechEvent?`🗣 speech started (level ${this.gate.levelDb.toFixed(0)} dBFS, room ${this.gate.noiseFloorDb.toFixed(0)} dBFS)`:"… speech ended"),e.bargeIn&&!1!==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&&a.warn("mic frame dropped: socket not open"));if(this.framesSent++,a.isEnabled("trace")&&a.trace(`→ SEND audio frame #${this.framesSent} (640 bytes, ${t?"base64 TEXT":"BINARY"})`),1===this.framesSent)a.info("→ first audio frame sent");else if(this.framesSent%250==0){const e=s.bufferedAmount??0,t=this.gate;a.info(`→ audio streaming: ${this.framesSent} frames (${y(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:g,data:o(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(),a.info(`✋ barge-in: you started talking, stopped the reply to "${this.playingQuestion??""}"`),this.bargedQuestion=this.playingQuestion,this.stopSpeakingState())}stopSpeakingState(){this.speakingUntil=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&&a.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(),a.info("📞 phone call: bot audio stopped, the mic sends silence until the call ends")}else"call_ended"===e&&this.inCall&&(this.inCall=!1,a.info("📞 call ended: mic audio resumed"))}handleText(e){let t;try{t=JSON.parse(e)}catch{return void a.warn(`← non-JSON text ignored: ${r(e,120)}`)}if(a.debug(`← RECV ${r(e)}`),!t||"object"!=typeof t)return;if(this.messageListeners.forEach((e=>e(t))),this.setState({lastMessage:t}),"navigate"===t.type)return a.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 c=s.output?.prompt;"string"==typeof c&&c&&(o.lastPrompt=c),o.lastQuestion&&o.lastQuestion!==n&&a.info(`← you said: "${o.lastQuestion}"`),o.lastPrompt&&o.lastPrompt!==i&&a.info(`← bot: "${o.lastPrompt}"`);const h=s.output?.error;h&&0!==h&&"0"!==h&&a.warn(`← server reported error: ${r(s.output,200)}`),s.buffer||o.lastQuestion||o.lastPrompt||a.info(`← message: ${r(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),r="back"===n||/^(back|go_back|goback)$/i.test(o);if(!(r||o&&("navigation"===n||"navigate"===n||"navigate"===i||r||this.matchScreen(o))))return void this.localNavigate(e);const c=`${e.question??""}|${r?"back":o}`,h=Date.now();c===this.lastReplyNavKey&&h-this.lastReplyNavAt<3e3||(this.lastReplyNavKey=c,this.lastReplyNavAt=h,a.info(`← reply asks for ${r?"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(r?{type:"navigate",action:"back"}:{type:"navigate",screen:o}))}playReplyAudio(e,s){const i="string"==typeof e.question?e.question.trim():"";if(i&&i===this.bargedQuestion)a.debug(`← reply #${this.replyCount}: audio not played (you talked over "${i}")`);else{i&&(this.bargedQuestion=null);try{const o=n(s);i&&i!==this.playingQuestion&&(this.state.speaking&&!1!==this.options?.interruptOnNewReply&&this.interruptPlayback(i),this.playingQuestion=i,this.gate?.newReply()),o%2&&a.warn(`reply audio chunk has an odd byte count (${o}); last byte dropped`);const r=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):g}(e);r!==this.lastReplyRate&&(a.info(`reply audio sample rate: ${r} Hz${r===g?" (default)":" (from the server)"}`),this.lastReplyRate=r),t.enqueuePlayback(s,r);const c=o/(2*r);a.debug(`← reply #${this.replyCount}: audio chunk ${o} bytes (${c.toFixed(2)} s at ${r} Hz) queued`),this.markSpeaking(c)}catch(e){a.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(),a.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=h(t,s,this.options?.voiceShortcuts);if(!n)return;const i="back"===n.action?"back":n.screen,o=`${t}|local|${i}`,r=Date.now();o===this.lastReplyNavKey&&r-this.lastReplyNavAt<3e3||(this.lastReplyNavKey=o,this.lastReplyNavAt=r,a.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 s=Date.now();this.speakingUntil=Math.max(this.speakingUntil,s)+1e3*e,this.state.speaking||(this.replyAudioSeconds=0,a.info("🔊 bot speaking (reply audio playing)"),this.setState({speaking:!0})),this.replyAudioSeconds+=e,this.speakingTimer&&clearTimeout(this.speakingTimer),this.speakingTimer=setTimeout((()=>{a.info(`🔇 bot finished speaking (${this.replyAudioSeconds.toFixed(2)} s of audio)`),this.playingQuestion=null,t.releaseAudioFocus(),this.setState({speaking:!1})}),this.speakingUntil-s+150)}sendScreenChanged(){if(!this.isConnected||!this.navigation||!this.state.sessionId)return;const e=this.navigation.getCurrentScreen();if(!e)return;const t=this.navigation.getBackStack(),s=`${e}|${t.join(",")}`;if(s===this.lastSentScreen)return;this.lastSentScreen=s;const n={type:"screen_changed",sessionId:this.state.sessionId,screen:e,backStack:t};a.info(`→ screen_changed: "${e}" backStack=${JSON.stringify(t)}`),this.sendJson(n)}matchScreen(e){const t=this.screens.length?this.screens:this.navigation?.getScreens()??[];return p(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),$={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;