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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,55 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0
4
+
5
+ **Actions:** the AI server can now run operations that the app registers, not only open screens.
6
+ Fully optional and backwards compatible: apps without actions send exactly the same messages.
7
+
8
+ - **Action registry:** `actions` prop on `VoiceBotProvider`, `VoiceBot.registerAction()`,
9
+ `useVoiceBotAction()`. Each action has a description, a params schema (short forms like
10
+ `'string?'`, `'S|M|L'`, or full specs with min/max/enum), a `run` handler, `timeoutMs`, `confirm`
11
+ and `idempotent`. The SDK contains no business actions.
12
+ - **Protocol:** `actions` metadata in the connect message (and `actions_update`); new messages
13
+ `actions` (server → app), `action_result` (one per request), `action_status` (repeats),
14
+ `cancel_actions`, `action_ack`. See docs/PROTOCOL.md section 11.
15
+ - **Execution engine:** steps run in order (actions and navigation), requests one at a time;
16
+ allowlist and param validation; per-action timeouts with an abort signal; a failed step stops the
17
+ request; repeated requestIds are never run twice; results that finish while offline are sent after
18
+ reconnecting; finished requests are forgotten after 10 minutes. Thrown errors are reported with
19
+ safe messages (`ActionError` for your own codes).
20
+ - **Confirmation:** actions marked `confirm` run only after the user approves; default native alert,
21
+ or your own UI with `onConfirmAction`. The server can't skip it.
22
+ - **Screen context:** `screen_changed` includes small `params` (route params plus
23
+ `useVoiceBotScreenContext()` / `VoiceBot.setScreenContext()`).
24
+ - **Echo (breaking voice, cut-off sentences, repeated replies):** on a phone loudspeaker the bot's
25
+ own voice reached the mic at speech level, so barge-in cut replies off and the server answered the
26
+ bot's own words. Now the mic is **muted while the bot speaks** by default (`whileSpeaking: 'mute'`,
27
+ plus `echoTailMs`, default 600 ms, after playback), and **barge-in is off** by default
28
+ (`bargeIn: true` to enable, with `whileSpeaking: 'guard'`, for headsets).
29
+ - **Real end of playback:** the native module sends `onPlaybackIdle` when the speaker has played the
30
+ last frame of the reply (Android: AudioTrack playback position; iOS: buffers played back), so
31
+ "speaking" and the mute end on time instead of on an estimate. Needs a native rebuild; older
32
+ native code falls back to the estimate.
33
+ - **Logs:** SDK warnings and errors no longer use `console.warn` / `console.error`, so they don't
34
+ pop up React Native's LogBox in the host app (the level is still in each line).
35
+ - Example app: a demo shop with a real cart and example actions (search, add/remove/update cart,
36
+ coupon, cart summary, place order with confirmation).
37
+
38
+ ## 0.1.3
39
+
40
+ Navigation fixes found in a real app (Expo Router, tabs, a start route left out of the screens).
41
+
42
+ - **Switching to a tab you visited before** ("open my account" from the Cart tab) now always
43
+ switches tabs. Before, some tab setups were treated like a back stack, the SDK tried to "go back"
44
+ to the tab (`dismissTo`), nothing happened, and it still reported `opened`.
45
+ - **Home with an excluded start route:** when the app has a root `index` (e.g. one that redirects
46
+ to a welcome screen) next to `(tabs)/index`, opening Home now goes to `(tabs)/index` instead of
47
+ the start route. The SDK checks every route the app has, not only the ones it sends.
48
+ - **No more false "opened":** after navigating, the SDK checks that the visible screen really
49
+ changed. If not, it tries once more with `router.navigate`, and otherwise reports `failed` with
50
+ the screen the app is on.
51
+ - Tip for tab apps: move the floating mic above your tab bar with `widget={{ bottom: 90 }}`.
52
+
3
53
  ## 0.1.2
4
54
 
5
55
  Navigation fixes for Expo Router apps with tabs, nested folders and dynamic routes, and local
@@ -49,8 +99,8 @@ React Native and Expo apps.
49
99
  Navigation, or your own router (callbacks).
50
100
  - **Cleaner audio for the server.** A noise gate sends silence instead of room noise between
51
101
  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'`).
102
+ - **Barge-in (optional).** With `bargeIn: true` and `whileSpeaking: 'guard'`, talking over the bot
103
+ stops its reply. Off by default (see 0.2.0).
54
104
  - **New replies replace old ones.** A reply to a new question stops the previous reply's audio.
55
105
  - **Background listening (Android).** The mic keeps working when the app is in the background,
56
106
  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
@@ -155,7 +157,7 @@ the mic:
155
157
  <VoiceBotProvider url={URL} widget={false}> {/* no widget: use your own button */}
156
158
  ```
157
159
 
158
- You can also place `<VoiceBotWidget />` yourself anywhere. The widget shows a spinner while
160
+ 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
161
  connecting, a pulsing red ring while listening, and green while the bot is speaking.
160
162
 
161
163
  ## Your own button
@@ -202,8 +204,9 @@ with the options from the last `connect()` call and then starts the mic.
202
204
  | `backgroundListening` | `boolean \| { title?, text? }` | Android: keep listening in the background, with a notification while the mic is on. Default `true`. See [Background listening](#background-listening). |
203
205
  | `interruptOnNewReply` | `boolean` | Default `true`: a reply to a new question stops the old reply's audio and plays right away. Parts of the same reply still play in order. `false` queues every reply. |
204
206
  | `noiseGate` | `boolean \| { thresholdDb?, minLevelDb?, hangoverMs?, preRollMs? }` | Default `true`: send silence instead of room noise between sentences. See [Noise gate and barge-in](#noise-gate-and-barge-in). |
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. |
207
+ | `whileSpeaking` | `'mute' \| 'guard' \| 'listen'` | What the mic does while the bot speaks. Default `'mute'`. |
208
+ | `bargeIn` | `boolean` | Default `false`. `true`: talking over the bot stops its reply (use with headsets and `whileSpeaking: 'guard'`). |
209
+ | `echoTailMs` | `number` | Default `600`: the mic stays muted this long after the reply has finished playing. |
207
210
  | `pauseOnCall` | `boolean` | Default `true`: during a phone call, stop the bot's audio and send silence. |
208
211
  | `keepSessionOnReconnect` | `boolean` | Default `false`. `true` keeps the same `sessionId` after an automatic reconnect. |
209
212
  | `localNavigation` | `boolean` | Default `true`: when the server doesn't navigate, open the screen the user clearly asked for ("open my cart"). See [Local voice navigation](#local-voice-navigation). |
@@ -229,6 +232,8 @@ const { status, isReady, isListening, speaking, lastQuestion, lastPrompt, lastMe
229
232
  | `error` / `lastError` | Last error (`{ code, message }`), or `null`. |
230
233
  | `start`, `stop`, `toggle` | Mic on / off. `start()` asks for the mic permission the first time and reconnects if needed. |
231
234
  | `connect`, `disconnect` | Same as `VoiceBot.connect()` / `disconnect()`. |
235
+ | `registerAction(name, def)` | Register an action; returns an unregister function. |
236
+ | `setScreenContext(params)` | Small context about the visible screen, sent with `screen_changed`. |
232
237
  | `addMessageListener(fn)` | Every JSON message from the server. Returns an unsubscribe function. |
233
238
 
234
239
  ### `<VoiceBotProvider>`
@@ -242,11 +247,43 @@ const { status, isReady, isListening, speaking, lastQuestion, lastPrompt, lastMe
242
247
  | `navigation` | A navigation adapter, so the server can open screens (see below). |
243
248
  | `onConnect`, `onError`, `onClose` | Connection callbacks. |
244
249
  | `onReply`, `onMessage` | Every reply / every JSON message from the server. |
250
+ | `actions` | Actions the server may run (see [Actions](#actions-020)). |
251
+ | `onConfirmAction` | Your confirmation UI for actions with `confirm`. Default: a native alert. |
245
252
  | `options` | Any other `VoiceBot.connect()` option (`noiseGate`, `bargeIn`, `autoReconnect`, `logLevel` …). |
246
253
  | `disconnectOnUnmount` | Default `true`. |
247
254
 
248
255
  Without `url`, call `VoiceBot.connect({ url, … })` yourself (for example after login).
249
256
 
257
+ ## Actions (0.2.0)
258
+
259
+ Let the AI server run operations of your app. Register them on the provider; the SDK validates
260
+ params, asks for confirmation where you require it, runs them in order with timeouts, and tells the
261
+ server the real result. The SDK has no business logic of its own.
262
+
263
+ ```tsx
264
+ <VoiceBotProvider
265
+ url={URL}
266
+ navigation={navigation}
267
+ actions={{
268
+ add_to_cart: {
269
+ description: 'Add a product to the cart',
270
+ params: { product: 'string', size: 'string?', quantity: 'integer?' },
271
+ run: async ({ product, size, quantity = 1 }) => {
272
+ const line = await cart.add(product, size, quantity); // your code
273
+ return { ok: true, data: line };
274
+ },
275
+ },
276
+ place_order: { description: 'Place the order', confirm: true, run: () => api.placeOrder() },
277
+ }}
278
+ >
279
+ ```
280
+
281
+ The server sends `{"type":"actions","requestId":"req_001","steps":[{"action":"add_to_cart",…},{"navigate":"checkout"}]}`
282
+ and gets one `action_result`. Also: `useVoiceBotAction()` for screen-only actions,
283
+ `useVoiceBotScreenContext()` so the server knows what "this" is, `ActionError` for safe error
284
+ codes, `onConfirmAction` for your own confirmation UI. Full guide:
285
+ [docs/ACTIONS.md](https://unpkg.com/react-native-voice-bot-sdk/docs/ACTIONS.md).
286
+
250
287
  ## Reconnecting
251
288
 
252
289
  If the connection drops (Wi-Fi change, server restart, close code other than 1000), the SDK
@@ -285,12 +322,19 @@ VoiceBot.connect({ url, noiseGate: { thresholdDb: 8 } }); // more sensitive (def
285
322
  VoiceBot.connect({ url, noiseGate: false }); // send the mic unchanged
286
323
  ```
287
324
 
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.
325
+ **While the bot speaks** (`whileSpeaking`): `'mute'` (default) sends silence while the reply plays
326
+ and for `echoTailMs` (600 ms) after the speaker has really finished. On a phone's loudspeaker the
327
+ bot's own voice comes back into the mic about as loud as a person (echo cancellation often doesn't
328
+ remove it); without the mute the server hears the bot, answers itself, and replies cut each other
329
+ off. `'guard'` only counts clearly louder speech (for headsets). `'listen'` treats it like any other
330
+ time.
331
+
332
+ **Barge-in** (`bargeIn`, default off): with `whileSpeaking: 'guard'`, when the user talks over the
333
+ bot for about 300 ms clearly louder than the reply's echo, the reply stops and the rest of it isn't
334
+ played. Turn it on only where echo is low (headsets); on a loudspeaker the echo can trigger it.
291
335
 
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.
336
+ **End of playback:** the native module reports when the speaker has really played the last of the
337
+ reply (`onPlaybackIdle`), so "speaking" and the mute end at the right time, not on an estimate.
294
338
 
295
339
  **Other apps and calls.** While the bot speaks it takes the audio focus, so music from other apps
296
340
  gets quieter. If another app takes the audio (or a call comes in), the bot's reply stops. During a
@@ -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';
@@ -97,13 +99,23 @@ export interface ConnectOptions {
97
99
  */
98
100
  noiseGate?: boolean | Omit<NoiseGateOptions, 'enabled' | 'whileSpeaking'>;
99
101
  /**
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.
102
+ * What the mic does while the bot is speaking. `'mute'` (default): send silence, so the bot's own
103
+ * voice coming out of the speaker can't reach the server (on a phone speaker, echo cancellation
104
+ * often doesn't remove it). `'guard'`: only louder speech counts (use with headsets, together with
105
+ * `bargeIn`). `'listen'`: same as any other time.
103
106
  */
104
107
  whileSpeaking?: WhileSpeaking;
105
- /** Stop the bot's reply when the user starts talking over it (about 200 ms of speech). Default `true`. */
108
+ /**
109
+ * Stop the bot's reply when the user starts talking over it. Default `false`: on a phone speaker
110
+ * the bot's own echo can be mistaken for the user and cut the reply off. Needs
111
+ * `whileSpeaking: 'guard'` (or 'listen').
112
+ */
106
113
  bargeIn?: boolean;
114
+ /**
115
+ * After the bot's reply has finished playing, keep the mic muted this long (ms), so the end of
116
+ * the reply and room echo don't reach the server. Default 600. Only with `whileSpeaking: 'mute'`.
117
+ */
118
+ echoTailMs?: number;
107
119
  /** During a phone call, stop the bot's audio and send silence until the call ends. Default `true`. */
108
120
  pauseOnCall?: boolean;
109
121
  /**
@@ -164,11 +176,23 @@ export declare class VoiceBotClient {
164
176
  private lastReplyNavKey;
165
177
  /** `question` of the reply whose audio is playing (to tell new replies from more chunks). */
166
178
  private playingQuestion;
179
+ /** When the bot last stopped speaking (for the echo tail). */
180
+ private speakingEndedAt;
181
+ private readonly realPlaybackEnd;
167
182
  /** Reply the user talked over: its remaining chunks are not played. */
168
183
  private bargedQuestion;
169
184
  private gate;
170
185
  private inCall;
171
186
  private lastSessionId;
187
+ /**
188
+ * Actions the host app lets the AI server run. Register with `VoiceBot.registerAction()` or the
189
+ * provider's `actions` prop. Empty by default: then the SDK behaves exactly as without actions.
190
+ */
191
+ readonly actions: ActionRegistry;
192
+ private readonly engine;
193
+ private confirmHandler;
194
+ private lastActionsKey;
195
+ private screenContext;
172
196
  private lastReplyNavAt;
173
197
  getState: () => VoiceBotState;
174
198
  /** Subscribe to state changes. Returns an unsubscribe function. */
@@ -232,14 +256,56 @@ export declare class VoiceBotClient {
232
256
  private interruptPlayback;
233
257
  /** The server's reply didn't navigate: open a screen if the user clearly asked for one. */
234
258
  private localNavigate;
259
+ /**
260
+ * The bot's reply is (still) playing. With native playback-end events the reply ends when the
261
+ * speaker has really played everything (`onPlaybackIdle`); the timer is only a fallback.
262
+ * Otherwise the end is estimated from the audio length.
263
+ */
235
264
  private markSpeaking;
265
+ private finishSpeaking;
266
+ /** True while the bot's voice may still be coming out of the speaker (reply + echo tail). */
267
+ private botAudible;
268
+ /**
269
+ * Lets the AI server run an action of your app. Returns a function that removes it again.
270
+ * The server learns about it in the connect message (or an `actions_update` if already connected).
271
+ */
272
+ registerAction: (name: string, definition: ActionDefinition) => (() => void);
273
+ unregisterAction: (name: string) => void;
274
+ /** Replaces all registered actions (what the provider's `actions` prop does). */
275
+ setActions: (actions: Record<string, ActionDefinition>) => void;
276
+ /** What the server is told about the registered actions. */
277
+ getActions: () => ActionMetadata[];
278
+ /**
279
+ * The UI that asks the user before an action marked `confirm` runs. The provider sets a default
280
+ * (a native alert); pass your own to show your own sheet, or `null` to remove it (such actions
281
+ * then fail with CONFIRMATION_UNAVAILABLE).
282
+ */
283
+ setConfirmHandler: (handler: ConfirmHandler | null) => void;
284
+ /**
285
+ * Small context about what the user is looking at, sent with `screen_changed` (e.g.
286
+ * `{ itemId: 'A12', selectedColor: 'red' }`), so the server understands "this one". It's cleared
287
+ * when the user moves to another screen. Only short strings, numbers and booleans are sent; don't
288
+ * put personal data here.
289
+ */
290
+ setScreenContext: (params: Record<string, unknown> | null) => void;
291
+ private trySend;
292
+ private sendActionsUpdate;
293
+ /** A navigate step of an actions request: the normal navigation rules, reported in action_result. */
294
+ private navigateForStep;
295
+ /** Route params of the visible screen plus the app's context: short, flat values only. */
296
+ private currentScreenParams;
236
297
  /** Registers (or clears with `null`) the host app's navigation. */
237
298
  setNavigation: (adapter: NavigationAdapter | null) => void;
238
299
  private sendScreenChanged;
300
+ /**
301
+ * Waits (up to about 1.5 s) for the visible screen to become `target`. Returns the visible screen.
302
+ * Skipped in the background, where JS timers are paused.
303
+ */
304
+ private waitForScreen;
239
305
  /** Finds the screen the server asked for (see `matchScreen` for the rules). */
240
306
  private matchScreen;
241
307
  /** Runs a navigate command (also usable by the host for testing). */
242
- handleNavigate: (cmd: NavigateCommand) => Promise<NavigateResultMessage>;
308
+ handleNavigate: (cmd: NavigateCommand, report?: boolean) => Promise<NavigateResultMessage>;
243
309
  }
244
310
  /** Shared voice bot session. */
245
311
  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/m).toFixed(2),b={1e3:"normal",1001:"going away",1002:"protocol error",1003:"unsupported data",1006:"connection lost (no close frame)",1008:"policy violation",1009:"message too big",1011:"server error"};export class VoiceBotClient{constructor(){this.ws=null,this.options=null,this.state={status:"idle",speaking:!1,sessionId:null,lastQuestion:null,lastPrompt:null,lastError:null,lastMessage:null},this.listeners=new Set,this.messageListeners=new Set,this.navigation=null,this.navUnsubscribe=null,this.lastSentScreen=null,this.screens=[],this.runCookieId=y(),this.wantConnected=!1,this.reconnectAttempt=0,this.reconnectTimer=null,this.reconnectDueAt=0,this.connectDeadline=0,this.onConnectDeadline=null,this.backgroundServiceOn=!1,this.stopMic=null,this.seq=0,this.speakingUntil=0,this.speakingTimer=null,this.connectTimer=null,this.connectStartedAt=0,this.micStartedAt=0,this.framesSent=0,this.framesDropped=0,this.replyCount=0,this.replyAudioSeconds=0,this.lastReplyRate=f,this.lastReplyNavKey=null,this.playingQuestion=null,this.speakingEndedAt=0,this.realPlaybackEnd=t.hasPlaybackIdleEvents(),this.bargedQuestion=null,this.gate=null,this.inCall=!1,this.lastSessionId=null,this.actions=new n,this.lastActionsKey="",this.screenContext=null,this.lastReplyNavAt=0,this.getState=()=>this.state,this.subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)}),this.addMessageListener=e=>(this.messageListeners.add(e),()=>{this.messageListeners.delete(e)}),this.connect=e=>{this.options=e,e.logLevel&&l(e.logLevel),this.wantConnected=!0,this.reconnectAttempt=0,this.clearReconnectTimer(),this.open()},this.disconnect=()=>{this.engine.cancelQueued("The app disconnected before this request started"),this.wantConnected=!1,this.reconnectAttempt=0,this.clearReconnectTimer(),this.stopRecording(),t.stopPlayback(),this.playingQuestion=null,this.closeSocket(1e3,"User exited"),this.setState({status:"idle",sessionId:null,speaking:!1})},this.start=async()=>{if(this.isListening)return!0;if(!this.isConnected)return this.reconnectTimer?(this.reconnectNow(),!1):this.options?("connecting"!==this.state.status?this.connect({...this.options,autoStart:!0}):this.options={...this.options,autoStart:!0},!1):(this.fail({code:"not_connected",message:"Call VoiceBot.connect({ url }) before start()"}),!1);try{if(!await t.requestMicPermission())return c.warn("microphone permission denied"),this.setState({lastError:{code:"mic_permission",message:"Microphone permission denied"}}),!1;this.seq=0,this.framesSent=0,this.framesDropped=0,this.micStartedAt=Date.now();const e="base64"===this.options?.uplinkEncoding,s=this.options?.noiseGate??!0;return this.gate=new i({..."object"==typeof s?s:{},enabled:!1!==s,whileSpeaking:this.options?.whileSpeaking??"mute"}),this.inCall=!1,this.stopMic=await t.startRecording((t=>this.onMicFrame(t,e)),(e=>{c.error(`mic error: ${e}`),this.setState({lastError:{code:"mic_failed",message:e}})})),this.isConnected?(this.setState({status:"listening",lastError:null}),this.startBackground(),c.info(`mic started: PCM s16le ${f} Hz mono, 640-byte frames (20 ms), uplink=${e?"base64 TEXT":"BINARY"}, noise gate ${!1===s?"off":"on"}, while bot speaks: ${this.options?.whileSpeaking??"mute"}, barge-in `+(!0===this.options?.bargeIn?"on":"off")),!0):(this.stopRecording(),!1)}catch(e){return c.error(`mic failed to start: ${e?.message??String(e)}`),this.setState({lastError:{code:"mic_failed",message:e?.message??String(e)}}),!1}},this.stop=()=>{this.stopRecording(),this.isConnected&&this.setState({status:"connected"})},this.toggle=async()=>{this.isListening?this.stop():await this.start()},this.registerAction=(e,t)=>this.actions.register(e,t),this.unregisterAction=e=>this.actions.unregister(e),this.setActions=e=>this.actions.replaceAll(e),this.getActions=()=>this.actions.metadata(),this.setConfirmHandler=e=>{this.confirmHandler=e??void 0},this.setScreenContext=e=>{this.screenContext=e?{screen:this.navigation?.getCurrentScreen()??null,params:e}:null,this.sendScreenChanged()},this.setNavigation=e=>{e!==this.navigation&&(this.navUnsubscribe?.(),this.navUnsubscribe=null,this.navigation=e,e&&(c.info(`navigation registered: ${e.kind}, ${e.getScreens().length} screens`),this.navUnsubscribe=e.subscribe((()=>this.sendScreenChanged())),this.isConnected&&this.state.sessionId&&(this.sendScreensUpdate(this.state.sessionId),this.lastSentScreen=null,this.sendScreenChanged())))},this.handleNavigate=async(e,t=!0)=>{const s="back"===e.action,n={type:"navigate_result",sessionId:this.state.sessionId??"",screen:e.screen??null,action:s?"back":"open",className:null,status:"failed",message:"",requestId:e.requestId??null},i=(e,s="",i=n.className)=>{n.status=e,n.message=s,n.className=i;const o=`→ navigate_result: ${e} ${"back"===n.action?"back":`"${n.screen}"`}`+(i&&i!==n.screen?` → ${i}`:"")+(s?` (${s})`:"");return"failed"===e?c.error(o):"unknown_screen"===e||"not_supported"===e?c.warn(o):c.info(o),t&&this.sendJson(n),n},o=this.navigation;if(!o)return i("not_supported","The app has no navigation registered with the voice bot");try{if(s){const e=o.getCurrentScreen();return await o.goBack()?i("went_back","",e):i("not_supported","Nothing to go back to",e)}if(!e.screen)return i("unknown_screen","No screen given");const t=this.matchScreen(e.screen);if(!t)return i("unknown_screen",`Not in the screens list: ${e.screen}`,null);const n=t.screen,a={...t.params??{},...e.params??{}},r=Object.keys(a).length?a:void 0,h=u(n.name).filter((e=>void 0===r?.[e]||""===r[e]));if(h.length){const e=n.name.replace(/\[(?:\.\.\.)?([^\]]+)\]/g,((e,t)=>`<${t}>`));return i("failed",`${n.name} needs ${h.join(", ")}: send "screen": "${e.replace(/^\(.*?\)\//,"")}" or "params": { ${h.map((e=>`"${e}": "…"`)).join(", ")} }`,n.name)}const l=o.getCurrentScreen(),d=o.getBackStack(),g=p(n.name,l,d,!!r);if("already_on_screen"===g)return i("already_on_screen","",n.name);"popTo"===g?await o.popTo(n,r):await o.push(n,r),c.debug(`navigate: ${g} ${n.name}${r?` ${JSON.stringify(r)}`:""} (from ${l??"-"})`);let m=await this.waitForScreen(o,n.name,l,!!r);return m!==n.name&&o.navigate&&(c.warn(`navigate: ${g} didn't reach ${n.name} (still on ${m??"-"}), trying navigate`),await o.navigate(n,r),m=await this.waitForScreen(o,n.name,l,!!r)),m!==n.name?i("failed",`Navigation didn't reach ${n.name}; the app is on ${m??"an unknown screen"}`,n.name):i("opened","",n.name)}catch(e){return i("failed",e?.message??String(e))}},this.engine=new s({registry:this.actions,navigate:(e,t)=>this.navigateForStep(e,t),getConfirmHandler:()=>this.confirmHandler,send:e=>this.trySend(e),sessionId:()=>this.state.sessionId??this.lastSessionId??"",log:{debug:e=>c.debug(e),info:e=>c.info(e),warn:e=>c.warn(e),error:e=>c.error(e)}}),this.actions.onChange((()=>this.sendActionsUpdate())),t.onInterruption((e=>this.handleInterruption(e))),t.onPlaybackIdle((()=>this.finishSpeaking("playback ended")));try{e.addEventListener("change",(e=>{"active"===e&&this.reconnectTimer&&(c.info("app is active again: reconnecting now"),this.reconnectNow())}))}catch{}}setState(e){this.state={...this.state,...e},this.listeners.forEach((e=>e()))}get isConnected(){return"connected"===this.state.status||"listening"===this.state.status}get isListening(){return"listening"===this.state.status}open(){const e=this.options;this.ws&&this.closeSocket(1e3,"Reconnecting");const{url:s}=e,n=this.reconnectAttempt>0;if(!t.isNativeAvailable())return void this.fail({code:"native_missing",message:t.NATIVE_MISSING_MESSAGE});this.setState({status:"connecting",lastError:null}),this.connectStartedAt=Date.now(),c.info(`connecting to ${s}`);let i=!1;const o=new WebSocket(s);o.binaryType="arraybuffer",this.ws=o;const a=e.connectTimeoutMs??1e4,r=()=>{i||this.ws!==o||(this.closeSocket(1e3,"Connect timeout"),n?this.scheduleReconnect(`timed out connecting to ${s}`):this.fail({code:"connect_timeout",message:`Timed out connecting to ${s}`}))};this.connectTimer=setTimeout(r,a),this.connectDeadline=Date.now()+a,this.onConnectDeadline=r,o.onopen=()=>{if(this.ws!==o)return;i=!0,this.clearConnectTimer();const t=n&&e.keepSessionOnReconnect&&this.lastSessionId?this.lastSessionId:y();this.lastSessionId=t,this.replyCount=0,this.lastReplyNavKey=null;const s=null!=this.stopMic;this.setState({status:s?"listening":"connected",sessionId:t,lastError:null}),c.info((n?`reconnected (attempt ${this.reconnectAttempt})`:"connected")+" in "+`${Date.now()-this.connectStartedAt} ms, session=${t}`+(n&&s?`, mic kept running (${this.framesDropped} frames dropped while offline)`:"")),this.reconnectAttempt=0,this.sendConnectMessage(t),this.lastSentScreen=null,this.sendScreenChanged(),this.engine.flush(),e.onSuccess?.({sessionId:t}),e.autoStart&&this.start()},o.onmessage=e=>{this.ws===o&&("string"==typeof e.data?this.handleText(e.data):c.debug(`← RECV binary message ignored (${e.data?.byteLength??"?"} bytes)`))},o.onerror=e=>{this.ws===o&&(e?.message&&c.warn(`socket error: ${e.message}`),i||setTimeout((()=>{if(this.ws!==o)return;this.clearConnectTimer(),this.ws=null;const t=e?.message||`Could not connect to ${s}`;n?this.scheduleReconnect(t):this.fail({code:"connect_failed",message:t})}),500))},o.onclose=t=>{if(this.ws!==o)return;if(this.ws=null,this.clearConnectTimer(),!i){const e=t.reason||`Could not connect to ${s}`;let i="";return/trust anchor|certificate|CertPath|SSL|handshake/i.test(e)?i=" (TLS: the server certificate is not trusted by the phone, e.g. self-signed. Use a certificate from a public CA, or ws:// for testing)":/refused/i.test(e)?i=" (nothing listening on that host/port)":/timeout|timed out|unreachable|no route/i.test(e)?i=" (host not reachable from the phone)":/cleartext/i.test(e)&&(i=" (ws:// is blocked: set allowCleartextTraffic in the config plugin)"),n?void this.scheduleReconnect(e+i):(this.stopRecording(),void this.fail({code:"connect_failed",message:e+i}))}const a=t.code??1006,r=`socket closed: code=${a} (${b[a]??"unknown"})${t.reason?` reason="${t.reason}"`:""}`;if(1e3===a?c.info(r):c.warn(r),e.onClose?.({code:a,reason:t.reason??""}),1e3!==a&&this.wantConnected&&this.reconnectEnabled())return this.setState({sessionId:null}),void this.scheduleReconnect(r);this.stopRecording(),this.setState({status:"idle",sessionId:null})}}reconnectEnabled(){return!1!==this.options?.autoReconnect}scheduleReconnect(e){const t="object"==typeof this.options?.autoReconnect?this.options.autoReconnect:{},s=t.maxAttempts??20,n=t.maxDelayMs??3e4;if(!this.wantConnected)return;if(this.reconnectAttempt>=s)return c.error(`giving up after ${this.reconnectAttempt} reconnect attempts (${e})`),this.reconnectAttempt=0,this.stopRecording(),void this.fail({code:"connect_failed",message:`Reconnect failed: ${e}`});this.reconnectAttempt++;const i=Math.min(n,1e3*2**(this.reconnectAttempt-1));c.warn(`reconnecting in ${(i/1e3).toFixed(0)} s (attempt ${this.reconnectAttempt}/${s}): ${e}`),this.setState({status:"connecting",sessionId:null}),this.options?.onReconnecting?.({attempt:this.reconnectAttempt,delayMs:i}),this.clearReconnectTimer(),this.reconnectDueAt=Date.now()+i,this.reconnectTimer=setTimeout((()=>{this.reconnectTimer=null,this.reconnectDueAt=0,this.wantConnected&&this.open()}),i)}reconnectNow(){this.reconnectTimer&&(this.clearReconnectTimer(),this.wantConnected&&this.open())}clearReconnectTimer(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.reconnectDueAt=0}closeSocket(e,t){const s=this.ws;if(this.ws=null,this.clearConnectTimer(),s){c.info(`→ closing socket: code=${e} reason="${t}"`);try{s.close(e,t)}catch{}}}clearConnectTimer(){this.connectTimer&&clearTimeout(this.connectTimer),this.connectTimer=null,this.connectDeadline=0,this.onConnectDeadline=null}tick(){const e=Date.now();if(this.reconnectDueAt&&e>=this.reconnectDueAt)this.reconnectNow();else if(this.connectDeadline&&e>=this.connectDeadline){const e=this.onConnectDeadline;this.clearConnectTimer(),e?.()}}fail(e){c.error(`${e.code}: ${e.message}`),this.setState({status:"idle",sessionId:null,lastError:e}),this.options?.onFailure?.(e)}sendJson(e){if(this.ws&&this.ws.readyState===WebSocket.OPEN){const t=JSON.stringify(e);c.debug(`→ SEND ${h(t)}`),this.ws.send(t)}else c.warn(`not sent (socket not open): ${h(e,120)}`)}sendConnectMessage(e){this.screens=this.navigation?.getScreens()??[];const t={sessionId:e,domain_id:this.options?.domainId??"",cookie_id:this.options?.cookieId||this.getSavedCookieId()||this.runCookieId,type:"Buffer",deviceId:this.options?.deviceId??1,sampleRate:f,screens:this.screens.map((e=>e.name))},s=this.actions.metadata();var n;s.length&&(t.actions=s),this.lastActionsKey=JSON.stringify(s),c.info(`→ connect message: domain_id=${t.domain_id||'""'} cookie_id=${n=t.cookie_id,n?`${n.slice(0,8)}…`:"-"} deviceId=${t.deviceId} sampleRate=${t.sampleRate} screens(${t.screens.length})=${JSON.stringify(t.screens)}`),s.length&&c.info(`→ actions(${s.length}): ${s.map((e=>e.name+(e.confirm?" (confirm)":""))).join(", ")}`),t.screens.length||c.warn("no screens sent: register navigation on <VoiceBotProvider navigation={...}> to enable voice navigation"),this.sendJson(t)}getSavedCookieId(){return void 0===this.savedCookieId&&(this.savedCookieId=t.getPersistentId("cookie_id")),this.savedCookieId}sendScreensUpdate(e){const t=this.screens.map((e=>e.name)).join("\n");this.screens=this.navigation?.getScreens()??[];const s=this.screens.map((e=>e.name));if(s.join("\n")===t)return;const n={type:"screens",sessionId:e,screens:s};c.info(`→ screens update (${s.length}): ${JSON.stringify(s)}`),this.sendJson(n)}async startBackground(){const e=this.options?.backgroundListening??!0;if(!1===e)return;const s="object"==typeof e&&e.title||"Voice assistant",n="object"==typeof e&&e.text||"Listening…",i=await t.startBackgroundService(s,n);!i||this.stopMic?(this.backgroundServiceOn=i,i&&c.info("background listening on (notification shown while the mic is on)")):t.stopBackgroundService()}stopRecording(){if(this.backgroundServiceOn&&(this.backgroundServiceOn=!1,t.stopBackgroundService()),this.stopMic){const e=this.gate?.flush()??[],s="base64"===this.options?.uplinkEncoding;e.forEach((e=>this.sendFrameBytes(e,s))),this.gate=null,t.stopRecording(),this.stopMic(),this.stopMic=null;const n=Date.now()-this.micStartedAt;c.info(`mic stopped after ${(n/1e3).toFixed(1)} s: sent ${this.framesSent} frames (${k(640*this.framesSent)} s of audio, ${640*this.framesSent} bytes)`+(this.framesDropped?`, dropped ${this.framesDropped} (socket not open)`:""))}}onMicFrame(e,t){this.tick();let s=a(e);if(this.inCall)s=S;else if(this.gate){const e=this.gate.process(s,this.botAudible());void 0!==e.speechEvent&&c.debug(e.speechEvent?`🗣 speech started (level ${this.gate.levelDb.toFixed(0)} dBFS, room ${this.gate.noiseFloorDb.toFixed(0)} dBFS)`:"… speech ended"),e.bargeIn&&!0===this.options?.bargeIn&&this.bargeIn(),s=e.out}s&&this.sendFrameBytes(s,t)}sendFrameBytes(e,t){const s=this.ws;if(!s||s.readyState!==WebSocket.OPEN)return this.framesDropped++,void(1===this.framesDropped&&c.warn("mic frame dropped: socket not open"));if(this.framesSent++,c.isEnabled("trace")&&c.trace(`→ SEND audio frame #${this.framesSent} (640 bytes, ${t?"base64 TEXT":"BINARY"})`),1===this.framesSent)c.info("→ first audio frame sent");else if(this.framesSent%250==0){const e=s.bufferedAmount??0,t=this.gate;c.info(`→ audio streaming: ${this.framesSent} frames (${k(640*this.framesSent)} s)`+(this.framesDropped?`, dropped ${this.framesDropped}`:"")+(t?`, speech ${(100*t.openRatio).toFixed(0)}% / silence ${(100-100*t.openRatio).toFixed(0)}%, room ${t.noiseFloorDb.toFixed(0)} dBFS`:"")+(this.inCall?", in a call (sending silence)":"")+(e>32e3?`, ${e} bytes waiting to send (slow network?)`:""))}t?s.send(JSON.stringify({type:"audio",sessionId:this.state.sessionId,seq:this.seq++,sampleRate:f,data:r(e)})):s.send(function(e){return 0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer}(e))}bargeIn(){this.state.speaking&&(t.stopPlayback(),c.info(`✋ barge-in: you started talking, stopped the reply to "${this.playingQuestion??""}"`),this.bargedQuestion=this.playingQuestion,this.stopSpeakingState())}stopSpeakingState(){this.speakingUntil=Date.now(),this.state.speaking&&(this.speakingEndedAt=Date.now()),this.speakingTimer&&clearTimeout(this.speakingTimer),this.speakingTimer=null,this.playingQuestion=null,t.releaseAudioFocus(),this.state.speaking&&this.setState({speaking:!1})}handleInterruption(e){if("focus_lost"===e)this.state.speaking&&c.info("🔇 another app took the audio: stopped the bot's reply"),this.stopSpeakingState();else if("call_started"===e){if(!1===this.options?.pauseOnCall||!this.stopMic)return;this.inCall=!0,this.stopSpeakingState(),c.info("📞 phone call: bot audio stopped, the mic sends silence until the call ends")}else"call_ended"===e&&this.inCall&&(this.inCall=!1,c.info("📞 call ended: mic audio resumed"))}handleText(e){let t;try{t=JSON.parse(e)}catch{return void c.warn(`← non-JSON text ignored: ${h(e,120)}`)}if(c.debug(`← RECV ${h(e)}`),!t||"object"!=typeof t)return;if(this.messageListeners.forEach((e=>e(t))),this.setState({lastMessage:t}),"actions"===t.type)return void this.engine.handle(t);if("cancel_actions"===t.type)return void(this.engine.cancel(t.requestId)||c.warn(`← cancel_actions ${t.requestId}: nothing running with that id`));if("action_ack"===t.type)return void this.engine.ack(t.requestId);if("navigate"===t.type)return c.info("← navigate: "+("back"===t.action?"back":`screen="${t.screen}"`)+(t.params?` params=${JSON.stringify(t.params)}`:"")+(null!=t.requestId?` requestId=${t.requestId}`:"")),void this.handleNavigate(t);const s=t;if("string"==typeof s.output)try{s.output=JSON.parse(s.output)}catch{}this.replyCount++;const n=this.state.lastQuestion,i=this.state.lastPrompt;"string"==typeof s.buffer&&s.buffer.length>0&&this.playReplyAudio(s,s.buffer);const o={};"string"==typeof s.question&&s.question&&(o.lastQuestion=s.question);const a=s.output?.prompt;"string"==typeof a&&a&&(o.lastPrompt=a),o.lastQuestion&&o.lastQuestion!==n&&c.info(`← you said: "${o.lastQuestion}"`),o.lastPrompt&&o.lastPrompt!==i&&c.info(`← bot: "${o.lastPrompt}"`);const r=s.output?.error;r&&0!==r&&"0"!==r&&c.warn(`← server reported error: ${h(s.output,200)}`),s.buffer||o.lastQuestion||o.lastPrompt||c.info(`← message: ${h(t,200)}`),Object.keys(o).length&&this.setState(o),this.navigateFromReply(s),this.options?.onReply?.(s)}navigateFromReply(e){const t=e.output;if(!t||"object"!=typeof t)return void this.localNavigate(e);const s=e=>"string"==typeof e?e.trim():"",n=s(t.type).toLowerCase(),i=s(t.intent).toLowerCase(),o=s(t.screen)||s(t.class_name)||s(t.target),a="back"===n||/^(back|go_back|goback)$/i.test(o);if(!(a||o&&("navigation"===n||"navigate"===n||"navigate"===i||a||this.matchScreen(o))))return void this.localNavigate(e);const r=`${e.question??""}|${a?"back":o}`,h=Date.now();r===this.lastReplyNavKey&&h-this.lastReplyNavAt<3e3||(this.lastReplyNavKey=r,this.lastReplyNavAt=h,c.info(`← reply asks for ${a?"back":`screen "${o}"`} (type="${s(t.type)}" intent="${s(t.intent)}" screen="${s(t.screen)}" class_name="${s(t.class_name)}" target="${s(t.target)}")`),this.handleNavigate(a?{type:"navigate",action:"back"}:{type:"navigate",screen:o}))}playReplyAudio(e,s){const n="string"==typeof e.question?e.question.trim():"";if(n&&n===this.bargedQuestion)c.debug(`← reply #${this.replyCount}: audio not played (you talked over "${n}")`);else{n&&(this.bargedQuestion=null);try{const i=o(s);n&&n!==this.playingQuestion&&(this.state.speaking&&!1!==this.options?.interruptOnNewReply&&this.interruptPlayback(n),this.playingQuestion=n,this.gate?.newReply()),i%2&&c.warn(`reply audio chunk has an odd byte count (${i}); last byte dropped`);const a=function(e){const t=e.output,s=Number(e.sample_rate??e.sampleRate??t?.sample_rate??t?.sampleRate);return Number.isFinite(s)&&s>=8e3&&s<=48e3?Math.round(s):f}(e);a!==this.lastReplyRate&&(c.info(`reply audio sample rate: ${a} Hz${a===f?" (default)":" (from the server)"}`),this.lastReplyRate=a),t.enqueuePlayback(s,a);const r=i/(2*a);c.debug(`← reply #${this.replyCount}: audio chunk ${i} bytes (${r.toFixed(2)} s at ${a} Hz) queued`),this.markSpeaking(r)}catch(e){c.error(`playback failed: ${e?.message??String(e)}`),this.setState({lastError:{code:"playback_failed",message:e?.message??String(e)}})}}}interruptPlayback(e){const s=Math.max(0,this.speakingUntil-Date.now())/1e3;t.stopPlayback(),c.info(`⏹ stopped old reply audio (${s.toFixed(1)} s left of "${this.playingQuestion??""}") for new reply to "${e}"`),this.speakingUntil=Date.now(),this.replyAudioSeconds=0}localNavigate(e){if(!1===this.options?.localNavigation||!this.navigation)return;const t="string"==typeof e.question?e.question.trim():"";if(!t)return;const s=this.screens.length?this.screens:this.navigation.getScreens(),n=d(t,s,this.options?.voiceShortcuts);if(!n)return;const i="back"===n.action?"back":n.screen,o=`${t}|local|${i}`,a=Date.now();o===this.lastReplyNavKey&&a-this.lastReplyNavAt<3e3||(this.lastReplyNavKey=o,this.lastReplyNavAt=a,c.info(`🧭 local shortcut: "${t}" → ${i} (the server's reply didn't navigate)`),this.handleNavigate("back"===n.action?{type:"navigate",action:"back",requestId:"local"}:{type:"navigate",screen:n.screen,requestId:"local"}))}markSpeaking(e){const t=Date.now();this.speakingUntil=Math.max(this.speakingUntil,t)+1e3*e,this.state.speaking||(this.replyAudioSeconds=0,c.info("🔊 bot speaking (reply audio playing)"),this.setState({speaking:!0})),this.replyAudioSeconds+=e,this.speakingTimer&&clearTimeout(this.speakingTimer);const s=this.realPlaybackEnd?3e3:250;this.speakingTimer=setTimeout((()=>this.finishSpeaking(this.realPlaybackEnd?"fallback timer":"estimated")),this.speakingUntil-t+s)}finishSpeaking(e){this.state.speaking&&(this.speakingTimer&&clearTimeout(this.speakingTimer),this.speakingTimer=null,c.info(`🔇 bot finished speaking (${this.replyAudioSeconds.toFixed(2)} s of audio, ${e})`),this.playingQuestion=null,this.speakingEndedAt=Date.now(),t.releaseAudioFocus(),this.setState({speaking:!1}))}botAudible(){if(this.state.speaking)return!0;const e=this.options?.echoTailMs??600;return Date.now()-this.speakingEndedAt<e}trySend(e){return!(!this.ws||this.ws.readyState!==WebSocket.OPEN||!this.state.sessionId||(this.sendJson(e),0))}sendActionsUpdate(){if(!this.isConnected||!this.state.sessionId)return;const e=this.actions.metadata(),t=JSON.stringify(e);t!==this.lastActionsKey&&(this.lastActionsKey=t,c.info(`→ actions_update (${e.length}): ${e.map((e=>e.name)).join(", ")}`),this.sendJson({type:"actions_update",sessionId:this.state.sessionId,actions:e}))}async navigateForStep(e,t){const s="back"===e?{type:"navigate",action:"back"}:{type:"navigate",screen:e,params:t},n=await this.handleNavigate(s,!1);return{status:n.status,screen:n.className,message:n.message}}currentScreenParams(e){const t={...this.navigation?.getCurrentParams?.()??{}};this.screenContext&&(null===this.screenContext.screen||this.screenContext.screen===e?Object.assign(t,this.screenContext.params):this.screenContext=null);const s={};let n=0;for(const[e,i]of Object.entries(t))if(!(n>=20||e.startsWith("__")||"screen"===e||"params"===e)){if("string"==typeof i&&i.length<=200)s[e]=i;else if("number"==typeof i&&Number.isFinite(i))s[e]=i;else{if("boolean"!=typeof i)continue;s[e]=i}n++}return n?s:void 0}sendScreenChanged(){if(!this.isConnected||!this.navigation||!this.state.sessionId)return;const e=this.navigation.getCurrentScreen();if(!e)return;const t=this.navigation.getBackStack(),s=this.currentScreenParams(e),n=`${e}|${t.join(",")}|${s?JSON.stringify(s):""}`;if(n===this.lastSentScreen)return;this.lastSentScreen=n;const i={type:"screen_changed",sessionId:this.state.sessionId,screen:e,backStack:t};s&&(i.params=s),c.info(`→ screen_changed: "${e}" backStack=${JSON.stringify(t)}${s?` params=${JSON.stringify(s)}`:""}`),this.sendJson(i)}async waitForScreen(t,s,n,i){const o=()=>t.getCurrentScreen();if(e.currentState&&"active"!==e.currentState)return s;for(let e=0;e<30;e++){const e=o();if(e===s&&(e!==n||i))return e;await new Promise((e=>setTimeout((()=>e()),50)))}return o()}matchScreen(e){const t=this.screens.length?this.screens:this.navigation?.getScreens()??[];return g(t,e)}}export const VoiceBot=new VoiceBotClient;
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Runs `actions` requests from the AI server: validates them, runs their steps one after another
3
+ * (registered actions via the host app's handlers, and navigation via the SDK's navigation), asks
4
+ * for confirmation where the app requires it, and reports one `action_result` per request.
5
+ *
6
+ * It has no UI or React Native dependencies; the client gives it a transport, a navigator and
7
+ * (optionally) a confirmation UI.
8
+ *
9
+ * Lifecycle of a request (by requestId):
10
+ * queued → running → completed (result sent, or kept until the socket is back) → forgotten after
11
+ * `retainMs`. A repeated request is never run twice while the SDK remembers it: the server gets an
12
+ * `action_status` (queued / running / completed with the earlier result) instead.
13
+ */
14
+ import { type ActionRegistry } from './registry.js';
15
+ import { type ActionResultMessage, type ActionStatusMessage, type ConfirmHandler, type NavigateStepResult } from './types.js';
16
+ export interface NavigateOutcome {
17
+ status: NavigateStepResult['status'];
18
+ screen?: string | null;
19
+ message?: string;
20
+ }
21
+ export interface EngineLog {
22
+ debug(m: string): void;
23
+ info(m: string): void;
24
+ warn(m: string): void;
25
+ error(m: string): void;
26
+ }
27
+ export interface ActionEngineDeps {
28
+ registry: ActionRegistry;
29
+ /** Opens a screen ("back" goes back) using the SDK's navigation, without sending navigate_result. */
30
+ navigate(target: string, params?: Record<string, unknown>): Promise<NavigateOutcome>;
31
+ /** The host's confirmation UI, if any. */
32
+ getConfirmHandler(): ConfirmHandler | undefined;
33
+ /** Sends a message; returns false when it couldn't be sent (no open socket). */
34
+ send(message: ActionResultMessage | ActionStatusMessage): boolean;
35
+ sessionId(): string;
36
+ log?: EngineLog;
37
+ /** How long a user has to answer a confirmation. Default 60 s. */
38
+ confirmTimeoutMs?: number;
39
+ /** How long finished requests are remembered (for repeats and unsent results). Default 10 min. */
40
+ retainMs?: number;
41
+ /** At most this many requests are remembered. Default 200. */
42
+ maxRetained?: number;
43
+ /** At most this many steps per request. Default 20. */
44
+ maxSteps?: number;
45
+ }
46
+ type EntryState = 'queued' | 'running' | 'completed';
47
+ export declare class ActionEngine {
48
+ private readonly deps;
49
+ private entries;
50
+ private queue;
51
+ private running;
52
+ private readonly log;
53
+ constructor(deps: ActionEngineDeps);
54
+ /** Handles an incoming `actions` message. Never throws. */
55
+ handle(message: unknown): void;
56
+ /** `cancel_actions`: stops a queued or running request. Returns false if it isn't active. */
57
+ cancel(requestId: string | number): boolean;
58
+ /** Cancels requests that haven't started (e.g. the user disconnected). Running steps finish. */
59
+ cancelQueued(reason: string): void;
60
+ /** `action_ack`: the server got the result. */
61
+ ack(requestId: string | number): void;
62
+ /** Sends results that couldn't be sent before (call when the socket is open again). */
63
+ flush(): number;
64
+ /** Where a request is in its lifecycle (for the host app and tests). */
65
+ state(requestId: string | number): {
66
+ state: EntryState | 'unknown';
67
+ delivered: boolean;
68
+ acknowledged: boolean;
69
+ };
70
+ /** True while a request is queued or running. */
71
+ get busy(): boolean;
72
+ private checkSteps;
73
+ private pump;
74
+ private run;
75
+ private runNavigate;
76
+ private runAction;
77
+ private askConfirmation;
78
+ private skipped;
79
+ private finish;
80
+ private sendStatus;
81
+ /** Forgets old finished requests, so memory stays small. Unsent results are kept until `retainMs`. */
82
+ private prune;
83
+ }
84
+ export {};