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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.2
4
+
5
+ Navigation fixes for Expo Router apps with tabs, nested folders and dynamic routes, and local
6
+ voice navigation.
7
+
8
+ - **Local voice navigation (new, on by default):** when the server's reply doesn't navigate, the
9
+ SDK still opens a screen if the user clearly asked for one ("open my cart", "show my orders",
10
+ "take me to my notifications", "go back"). Screen words come from your route names; add your own
11
+ with `voiceShortcuts` (`{ '(tabs)/cart': ['bag', 'basket'] }`). Sentences like "add this to my
12
+ cart" or "search for shoes" never navigate, and the server's own navigation always wins. The
13
+ server gets `navigate_result` with `requestId: "local"`. Turn it off with `localNavigation: false`.
14
+
15
+ - **Tabs:** opening a tab from a screen pushed above the tab bar (e.g. Cart from Profile) now goes
16
+ back to the tab bar and switches tab, instead of pushing a second copy of the tabs. Switching
17
+ between tabs no longer grows the back stack.
18
+ - **Dynamic routes:** the server can send a concrete path, e.g. `product/blue-shoes` or
19
+ `orders/A1001`, and the SDK opens `product/[slug]` / `orders/[orderNumber]` with those params.
20
+ A dynamic route without its params now fails with a clear `navigate_result` message instead of
21
+ opening a broken page.
22
+ - **Names:** `home` and `/` open the home screen; short names (`cart`, `orders`, `profile`) and
23
+ paths (`/cart`) match the full route names.
24
+ - Links use the URL path (`/cart`, `/product/[slug]`) instead of the group path.
25
+
3
26
  ## 0.1.1
4
27
 
5
28
  Documentation only, no code changes.
package/README.md CHANGED
@@ -206,6 +206,8 @@ with the options from the last `connect()` call and then starts the mic.
206
206
  | `bargeIn` | `boolean` | Default `true`: talking over the bot stops its reply. |
207
207
  | `pauseOnCall` | `boolean` | Default `true`: during a phone call, stop the bot's audio and send silence. |
208
208
  | `keepSessionOnReconnect` | `boolean` | Default `false`. `true` keeps the same `sessionId` after an automatic reconnect. |
209
+ | `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). |
210
+ | `voiceShortcuts` | `Record<screen, string[]>` | Extra words for local navigation, e.g. `{ '(tabs)/cart': ['bag', 'basket'] }`. |
209
211
  | `logLevel` | `'trace' \| 'debug' \| 'info' \| 'warn' \| 'error' \| 'none'` | Console logging, see [Logs](#logs). |
210
212
 
211
213
  ### `useVoiceBot()`
@@ -324,6 +326,31 @@ The SDK only opens screens it sent to the server, and follows the usual back sta
324
326
  The result goes back to the server as `navigate_result`, and every screen change (voice, tap or
325
327
  Back) is sent as `screen_changed` with the back stack. Pick the adapter for your app:
326
328
 
329
+ ### Local voice navigation
330
+
331
+ If the server's reply doesn't navigate (`type: "none"`) but the user clearly asked for a screen,
332
+ the SDK opens it itself:
333
+
334
+ | User says | Opens |
335
+ |-----------|-------|
336
+ | "Open my cart", "go to my cart" | `(tabs)/cart` |
337
+ | "Show my orders" | `orders/index` |
338
+ | "Take me to my notifications please" | `account/notifications` |
339
+ | "Take me home" | the screen at `/` |
340
+ | "Go back" | back one screen |
341
+ | "Add this to my cart", "search for shoes", "my cart" | nothing (not an "open" request) |
342
+
343
+ It needs an "open"-style word (open, show, go to, take me to, view …) and a word that names a
344
+ screen. The words come from your route names (`account/addresses` → "addresses", "address");
345
+ dynamic routes like `product/[slug]` are left to the server. Add your own words:
346
+
347
+ ```tsx
348
+ <VoiceBotProvider url={URL} options={{ voiceShortcuts: { '(tabs)/cart': ['bag', 'basket'], 'orders/index': ['order history'] } }}>
349
+ ```
350
+
351
+ The server's own navigation always wins, and the server still gets `navigate_result` (with
352
+ `requestId: "local"`) and `screen_changed`. Turn it off with `options={{ localNavigation: false }}`.
353
+
327
354
  ### Expo Router
328
355
 
329
356
  ```tsx
@@ -1,5 +1,6 @@
1
1
  import { type NoiseGateOptions, type WhileSpeaking } from './audio/noiseGate';
2
2
  import { type LogLevel } from './logger';
3
+ import { type VoiceShortcuts } from './navigation/localIntent';
3
4
  import type { NavigationAdapter } from './navigation/types';
4
5
  import { type BotReply, type NavigateCommand, type NavigateResultMessage } from './protocol';
5
6
  export type VoiceBotStatus = 'idle' | 'connecting' | 'connected' | 'listening';
@@ -110,6 +111,18 @@ export interface ConnectOptions {
110
111
  * conversation. Default `false`: every connection is a new session.
111
112
  */
112
113
  keepSessionOnReconnect?: boolean;
114
+ /**
115
+ * When the server's reply doesn't navigate, open a screen anyway if the user clearly asked for
116
+ * one ("open my cart", "show my orders", "go back"). The screen words come from your route names;
117
+ * sentences like "add this to my cart" never navigate, and the server's own navigation always
118
+ * wins. Default `true`.
119
+ */
120
+ localNavigation?: boolean;
121
+ /**
122
+ * Extra words for local navigation, per screen name: `{ '(tabs)/cart': ['bag', 'basket'] }`.
123
+ * Used together with an "open"-style word ("open my bag").
124
+ */
125
+ voiceShortcuts?: VoiceShortcuts;
113
126
  }
114
127
  type Listener = () => void;
115
128
  type MessageListener = (message: Record<string, unknown>) => void;
@@ -217,12 +230,14 @@ export declare class VoiceBotClient {
217
230
  private playReplyAudio;
218
231
  /** Stops the audio of the previous reply so the reply to a new question plays right away. */
219
232
  private interruptPlayback;
233
+ /** The server's reply didn't navigate: open a screen if the user clearly asked for one. */
234
+ private localNavigate;
220
235
  private markSpeaking;
221
236
  /** Registers (or clears with `null`) the host app's navigation. */
222
237
  setNavigation: (adapter: NavigationAdapter | null) => void;
223
238
  private sendScreenChanged;
224
- /** Finds a screen by full name, path, or unique last segment (case-insensitive). */
225
- private resolveScreen;
239
+ /** Finds the screen the server asked for (see `matchScreen` for the rules). */
240
+ private matchScreen;
226
241
  /** Runs a navigate command (also usable by the host for testing). */
227
242
  handleNavigate: (cmd: NavigateCommand) => Promise<NavigateResultMessage>;
228
243
  }
@@ -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{BYTES_PER_SECOND as h,SAMPLE_RATE as l}from"./protocol";function d(){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 p=new Uint8Array(640),u=e=>(e/h).toFixed(2),g={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=d(),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=l,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 ${l} 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.resolveScreen(e.screen);if(!s)return n("unknown_screen",`Not in the screens list: ${e.screen}`,null);const o=e.params,a=i.getCurrentScreen();return a!==s.name||o?(i.getBackStack().includes(s.name)&&a!==s.name?await i.popTo(s,o):await i.push(s,o),n("opened","",s.name)):n("already_on_screen","",s.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:d();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} (${g[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:l,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 (${u(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=p;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 (${u(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:l,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;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.resolveScreen(o))))return;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):l}(e);r!==this.lastReplyRate&&(a.info(`reply audio sample rate: ${r} Hz${r===l?" (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}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)}resolveScreen(e){const t=this.screens.length?this.screens:this.navigation?.getScreens()??[],s=t.find((t=>t.name===e||t.path===e));if(s)return s;const n=e.replace(/^\//,"").toLowerCase(),i=t.filter((e=>e.name.toLowerCase()===n||e.path?.replace(/^\//,"").toLowerCase()===n));if(1===i.length)return i[0];const o=t.filter((e=>{const t=e.name.split("/").filter((e=>"index"!==e&&!/^\(.*\)$/.test(e))),s=(t[t.length-1]??"index").toLowerCase();return s===n||s.replace(/screen$/,"")===n.replace(/screen$/,"")}));return 1===o.length?o[0]:null}}export const VoiceBot=new VoiceBotClient;
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,6 +1,6 @@
1
1
  import { type SitemapType } from 'expo-router';
2
2
  import type { ScreenInfo } from './protocol';
3
- import type { NavigationAdapter } from './navigation/types';
3
+ import type { NavigationAdapter, NavParams } from './navigation/types';
4
4
  export interface ExpoRouterNavigationOptions {
5
5
  /** Route names to leave out (e.g. `['modal', 'settings/debug']`). */
6
6
  exclude?: string[];
@@ -11,6 +11,11 @@ export declare function routeNameFromContextKey(key: string): string;
11
11
  export declare function routePathFromName(name: string): string;
12
12
  /** Collects the screen routes (no layouts, no internal or generated routes) from the sitemap. */
13
13
  export declare function screensFromSitemap(root: SitemapType | null, exclude?: string[]): ScreenInfo[];
14
+ /**
15
+ * Turns a route name + params into an href Expo Router accepts. Uses the URL path (`/cart`,
16
+ * `/product/[slug]`); keeps the group (`/(tabs)/cart`) only when two screens share a path.
17
+ */
18
+ export declare function hrefFor(screen: ScreenInfo, screens: ScreenInfo[], params?: NavParams): any;
14
19
  /** Hook that returns a navigation adapter for Expo Router. Call it in your root `_layout.tsx`. */
15
20
  export declare function useExpoRouterNavigation(options?: ExpoRouterNavigationOptions): NavigationAdapter;
16
21
  export type { NavigationAdapter } from './navigation/types';
@@ -1 +1 @@
1
- import{useMemo as e}from"react";import{router as t,useNavigationContainerRef as r,useSitemap as o}from"expo-router";import{flattenBackStack as n}from"./navigation/state";const a=/(^|\/)_layout$/;export function routeNameFromContextKey(e){return e.replace(/^\.\//,"").replace(/(\.(ios|android|web|native))?\.[jt]sx?$/,"")}export function routePathFromName(e){return"/"+e.split("/").filter((e=>e&&"index"!==e&&!/^\(.*\)$/.test(e))).join("/")}export function screensFromSitemap(e,t=[]){const r=new Map,o=new Set(t),n=e=>{const t=routeNameFromContextKey(e.contextKey),s=t.split("/").pop()??"";!!(a.test(t)||e.isInternal||e.isGenerated||s.startsWith("+")||s.startsWith("_"))||o.has(t)||r.has(t)||r.set(t,{name:t,path:routePathFromName(t)}),e.children.forEach(n)};return e&&n(e),[...r.values()].sort(((e,t)=>e.name.localeCompare(t.name)))}function s(e,t){const r="/"+e.name.split("/").filter((e=>"index"!==e)).join("/");return t&&Object.keys(t).length?{pathname:r,params:t}:r}export function useExpoRouterNavigation(a={}){const i=r(),c=o(),u=(a.exclude??[]).join("|");return e((()=>{const e=screensFromSitemap(c,a.exclude),r=()=>{return n(i?.isReady()?(e=i.getRootState())&&1===e.routes?.length&&"__root"===e.routes[0].name?e.routes[0].state:e:void 0,!0);var e};return{kind:"expo-router",getScreens:()=>e,getCurrentScreen:()=>{const e=r();return e.length?e[e.length-1]:null},getBackStack:r,push:(e,r)=>t.push(s(e,r)),popTo:(e,r)=>t.dismissTo(s(e,r)),goBack:()=>!!t.canGoBack()&&(t.back(),!0),subscribe:e=>i.addListener("state",(()=>e()))}}),[i,c,u])}
1
+ import{useMemo as e}from"react";import{router as t,useNavigationContainerRef as r,useSitemap as o}from"expo-router";import{topGroup as n}from"./navigation/match";import{flattenBackStack as a}from"./navigation/state";const s=/(^|\/)_layout$/;export function routeNameFromContextKey(e){return e.replace(/^\.\//,"").replace(/(\.(ios|android|web|native))?\.[jt]sx?$/,"")}export function routePathFromName(e){return"/"+e.split("/").filter((e=>e&&"index"!==e&&!/^\(.*\)$/.test(e))).join("/")}export function screensFromSitemap(e,t=[]){const r=new Map,o=new Set(t),n=e=>{const t=routeNameFromContextKey(e.contextKey),a=t.split("/").pop()??"";!!(s.test(t)||e.isInternal||e.isGenerated||a.startsWith("+")||a.startsWith("_"))||o.has(t)||r.has(t)||r.set(t,{name:t,path:routePathFromName(t)}),e.children.forEach(n)};return e&&n(e),[...r.values()].sort(((e,t)=>e.name.localeCompare(t.name)))}export function hrefFor(e,t,r){const o=routePathFromName(e.name),n=t.some((t=>t.name!==e.name&&routePathFromName(t.name)===o))?"/"+e.name.split("/").filter((e=>"index"!==e)).join("/"):o;return r&&Object.keys(r).length?{pathname:n,params:r}:n}export function useExpoRouterNavigation(s={}){const i=r(),m=o(),u=(s.exclude??[]).join("|");return e((()=>{const e=screensFromSitemap(m,s.exclude),r=()=>{return a(i?.isReady()?(e=i.getRootState())&&1===e.routes?.length&&"__root"===e.routes[0].name?e.routes[0].state:e:void 0,!0);var e};return{kind:"expo-router",getScreens:()=>e,getCurrentScreen:()=>{const e=r();return e.length?e[e.length-1]:null},getBackStack:r,push:(o,a)=>{const s=r(),i=s.length?s[s.length-1]:null,m=n(o.name);m&&n(i)===m?t.navigate(hrefFor(o,e,a)):t.push(hrefFor(o,e,a))},popTo:(r,o)=>t.dismissTo(hrefFor(r,e,o)),goBack:()=>!!t.canGoBack()&&(t.back(),!0),subscribe:e=>i.addListener("state",(()=>e()))}}),[i,m,u])}
package/build/index.d.ts CHANGED
@@ -12,6 +12,9 @@ export type { NavigationRefLike, ReactNavigationAdapterOptions } from './navigat
12
12
  export { createCallbackNavigation } from './navigation/callbackNavigation';
13
13
  export type { CallbackNavigationAdapter, CallbackNavigationOptions } from './navigation/callbackNavigation';
14
14
  export { flattenBackStack } from './navigation/state';
15
+ export { matchScreen } from './navigation/match';
16
+ export { findLocalIntent } from './navigation/localIntent';
17
+ export type { VoiceShortcuts, LocalIntent } from './navigation/localIntent';
15
18
  export { isNativeAvailable } from './NativeAudio';
16
19
  export { NoiseGate, frameLevelDb } from './audio/noiseGate';
17
20
  export type { NoiseGateOptions, WhileSpeaking } from './audio/noiseGate';
package/build/index.js CHANGED
@@ -1 +1 @@
1
- export{VoiceBot,VoiceBotClient}from"./VoiceBotClient";export{VoiceBotProvider}from"./react/VoiceBotProvider";export{VoiceBotWidget}from"./react/VoiceBotWidget";export{useVoiceBot}from"./react/useVoiceBot";export{createReactNavigationAdapter}from"./navigation/reactNavigation";export{createCallbackNavigation}from"./navigation/callbackNavigation";export{flattenBackStack}from"./navigation/state";export{isNativeAvailable}from"./NativeAudio";export{NoiseGate,frameLevelDb}from"./audio/noiseGate";export{setLogLevel,getLogLevel,setLogHandler}from"./logger";export*from"./protocol";
1
+ export{VoiceBot,VoiceBotClient}from"./VoiceBotClient";export{VoiceBotProvider}from"./react/VoiceBotProvider";export{VoiceBotWidget}from"./react/VoiceBotWidget";export{useVoiceBot}from"./react/useVoiceBot";export{createReactNavigationAdapter}from"./navigation/reactNavigation";export{createCallbackNavigation}from"./navigation/callbackNavigation";export{flattenBackStack}from"./navigation/state";export{matchScreen}from"./navigation/match";export{findLocalIntent}from"./navigation/localIntent";export{isNativeAvailable}from"./NativeAudio";export{NoiseGate,frameLevelDb}from"./audio/noiseGate";export{setLogLevel,getLogLevel,setLogHandler}from"./logger";export*from"./protocol";
@@ -0,0 +1,28 @@
1
+ import type { ScreenInfo } from '../protocol';
2
+ /**
3
+ * Local voice navigation: used only when the server's reply doesn't navigate.
4
+ *
5
+ * It looks at what the user said (the reply's `question`) and opens a screen when the sentence is
6
+ * clearly a request to open one: an "open"-style word ("open", "show", "go to", "take me to" …)
7
+ * followed by a word that names a screen. The words come from the app's route names
8
+ * (`(tabs)/cart` → "cart", `orders/index` → "orders" / "order", `account/addresses` →
9
+ * "addresses" / "address", `(tabs)/index` → "home"), plus any `voiceShortcuts` the app adds.
10
+ *
11
+ * Sentences about doing something with a thing ("add this to my cart", "remove from my wishlist",
12
+ * "search for shoes", "buy", "pay") never navigate.
13
+ */
14
+ export type VoiceShortcuts = Record<string, string[]>;
15
+ export type LocalIntent = {
16
+ action: 'back';
17
+ } | {
18
+ action: 'open';
19
+ screen: string;
20
+ keyword: string;
21
+ };
22
+ /** Words that name a screen, from its route name: `account/addresses` → `addresses`, `address`. */
23
+ export declare function screenKeywords(name: string): string[];
24
+ /**
25
+ * Finds a clear "open screen" request in `said`. Returns null when the sentence isn't one, when no
26
+ * screen word is found, or when two screens match equally well.
27
+ */
28
+ export declare function findLocalIntent(said: string, screens: ScreenInfo[], shortcuts?: VoiceShortcuts): LocalIntent | null;
@@ -0,0 +1 @@
1
+ const e=["open","show","show me","go to","goto","go into","take me to","bring me to","navigate to","switch to","move to","jump to","view","see","display","launch","visit","check","check my","bring up","pull up","load","i want to see","i want to go to","let me see","go","take me"],t=["add","remove","delete","clear","empty","buy","purchase","pay","cancel","return","track","search for","find","look for","save","put","move this","update","change","edit"],o=/^(please\s+)?(go\s+back|back|go\s+to\s+the\s+previous\s+(page|screen)|previous\s+(page|screen))(\s+please)?$/,s=e=>` ${e.toLowerCase().replace(/[^a-z0-9\s'-]/g," ").replace(/\s+/g," ").trim()} `,n=(e,t)=>e.includes(` ${t} `);export function screenKeywords(e){const t=e.split("/").filter((e=>e&&!/^\(.*\)$/.test(e)));if(t.some((e=>/^\[.*\]$/.test(e))))return[];const o=t.filter((e=>"index"!==e));if(!o.length)return["home","home page","home screen","main page","start"];const s=o[o.length-1].replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").toLowerCase(),n=new Set([s]);return s.endsWith("ies")?n.add(s.slice(0,-3)+"y"):s.endsWith("sses")?n.add(s.slice(0,-2)):s.endsWith("s")&&!s.endsWith("ss")?n.add(s.slice(0,-1)):n.add(s+"s"),[...n]}export function findLocalIntent(r,c,a={}){const i=s(r),l=i.trim();if(!l)return null;if(o.test(l))return{action:"back"};if(t.some((e=>n(i,e))))return null;if(!e.some((e=>n(i,e))))return null;const u=new Set(c.map((e=>e.name))),d=[];for(const[e,t]of Object.entries(a))if(u.has(e))for(const o of t)d.push({screen:e,keyword:s(o).trim(),custom:!0});for(const e of c)for(const t of screenKeywords(e.name))d.push({screen:e.name,keyword:t,custom:!1});const m=d.filter((e=>e.keyword&&n(i,e.keyword)));if(!m.length)return null;m.sort(((e,t)=>Number(t.custom)-Number(e.custom)||t.keyword.length-e.keyword.length));const p=m[0];return m.filter((e=>e.screen!==p.screen&&e.custom===p.custom&&e.keyword.length===p.keyword.length)).length?null:{action:"open",screen:p.screen,keyword:p.keyword}}
@@ -0,0 +1,31 @@
1
+ import type { ScreenInfo } from '../protocol';
2
+ import type { NavParams } from './types';
3
+ /** `(tabs)/cart` → `(tabs)`; `account/profile` → null. The navigator group a route lives in. */
4
+ export declare function topGroup(name: string | null | undefined): string | null;
5
+ /** Param names of a dynamic route: `orders/[orderNumber]` → `['orderNumber']`. */
6
+ export declare function dynamicParams(name: string): string[];
7
+ export interface ScreenMatch {
8
+ screen: ScreenInfo;
9
+ /** Params taken from a concrete path, e.g. `product/blue-shoes` → `{ slug: 'blue-shoes' }`. */
10
+ params?: NavParams;
11
+ }
12
+ /**
13
+ * Finds the screen the server asked for. Tried in order:
14
+ * 1. exact route name or path (`(tabs)/cart`, `/cart`);
15
+ * 2. the same, ignoring case and leading/trailing slashes (`Cart`, `cart/`);
16
+ * 3. `home` or `/` → the screen whose path is `/`;
17
+ * 4. a concrete path of a dynamic route (`product/blue-shoes` → `product/[slug]` with `slug`);
18
+ * 5. the last part of the name, if exactly one screen has it (`profile` → `account/profile`,
19
+ * `orders` → `orders/index`); a trailing `Screen` is ignored (`ProfileScreen`).
20
+ */
21
+ export declare function matchScreen(screens: ScreenInfo[], query: string): ScreenMatch | null;
22
+ export type NavMove = 'already_on_screen' | 'push' | 'popTo';
23
+ /**
24
+ * How to reach `target` from the current back stack, like a user would:
25
+ * - already visible (and no new params) → nothing;
26
+ * - in the back stack → pop back to it;
27
+ * - in a group (e.g. `(tabs)`) that is lower in the stack while the user is on a pushed screen
28
+ * above it → pop back to that group and switch to the screen;
29
+ * - otherwise → push it (switching tabs inside the same group counts as a push).
30
+ */
31
+ export declare function decideMove(target: string, current: string | null, stack: string[], hasParams: boolean): NavMove;
@@ -0,0 +1 @@
1
+ const e=e=>/^\(.*\)$/.test(e),t=/^\[(?:\.\.\.)?([^\]]+)\]$/;export function topGroup(t){const n=(t??"").split("/")[0];return e(n)?n:null}export function dynamicParams(e){return e.split("/").map((e=>t.exec(e)?.[1])).filter((e=>!!e))}function n(t){return t.split("/").filter((t=>t&&"index"!==t&&!e(t)))}export function matchScreen(o,c){const s=c.trim();if(!s)return null;const i=o.find((e=>e.name===s||e.path===s));if(i)return{screen:i};const u=s.replace(/^\/+|\/+$/g,""),a=u.toLowerCase(),p=o.filter((e=>e.name.toLowerCase()===a||(e.path??"").replace(/^\/+|\/+$/g,"").toLowerCase()===a));if(1===p.length)return{screen:p[0]};if(""===a||"home"===a){const e=o.filter((e=>"/"===e.path||0===n(e.name).length));if(1===e.length)return{screen:e[0]}}const l=u.split("/").filter((t=>t&&!e(t)));for(const e of o){if(!dynamicParams(e.name).length)continue;const o=n(e.name);if(o.length!==l.length)continue;const c={};if(o.every(((e,n)=>{const o=t.exec(e);return o?(c[o[1]]=r(l[n]),!0):e.toLowerCase()===l[n].toLowerCase()})))return{screen:e,params:c}}const f=a.replace(/screen$/,""),m=o.filter((e=>{const r=n(e.name),o=(r[r.length-1]??"index").toLowerCase();return!t.test(o)&&(o===a||o.replace(/screen$/,"")===f)}));return 1===m.length?{screen:m[0]}:null}function r(e){try{return decodeURIComponent(e)}catch{return e}}export function decideMove(e,t,n,r){if(t===e&&!r)return"already_on_screen";if(n.includes(e)&&t!==e&&!r)return"popTo";const o=topGroup(e);return o&&topGroup(t)!==o&&n.some((e=>topGroup(e)===o))?"popTo":"push"}
@@ -149,6 +149,7 @@ Pass any `VoiceBot.connect()` option in `options`:
149
149
  whileSpeaking: 'guard', // ignore the bot's own voice (default)
150
150
  backgroundListening: { title: 'Shop assistant', text: 'Listening…' },
151
151
  cookieId: currentUser?.visitorId, // your own visitor id (default: saved on the device)
152
+ voiceShortcuts: { '(tabs)/cart': ['bag', 'basket'] }, // extra words: "open my bag" -> cart
152
153
  logLevel: 'debug', // every request and response in the console
153
154
  }}
154
155
  >
package/docs/PROTOCOL.md CHANGED
@@ -188,6 +188,15 @@ matching and back stack rules as `navigate` (section 6), and answers with `navig
188
188
  `requestId`). If `type` isn't `"navigation"` (and `intent` isn't `"navigate"`), the name is used only
189
189
  when it is exactly one of the app's screens. A reply split over several chunks navigates only once (same screen within 3 s); the same request later navigates again.
190
190
 
191
+ ### 5c. Local navigation in the app — **RN**
192
+
193
+ If a reply doesn't navigate (`output.type` is `"none"`, or no screen is given) and the user's
194
+ `question` is a clear request to open a screen ("open my cart", "show my orders", "go back"), the
195
+ app opens it by itself and sends `navigate_result` with **`"requestId": "local"`**, then
196
+ `screen_changed`. Requests about doing something ("add this to my cart", "search for shoes") are
197
+ left alone. Returning proper navigation from the server is still the better fix: the app's rules
198
+ are simple keyword checks.
199
+
191
200
  ## 6. Navigate (Server → App, TEXT)
192
201
 
193
202
  ```json
@@ -196,6 +205,10 @@ when it is exactly one of the app's screens. A reply split over several chunks n
196
205
  { "type": "navigate", "action": "back", "requestId": 3 }
197
206
  ```
198
207
 
208
+ - `screen` can be a name from `screens` (`(tabs)/cart`), its path (`/cart`), a short name
209
+ (`cart`), `home`, or a **concrete path for a dynamic route** (`product/blue-shoes` opens
210
+ `product/[slug]` with `slug = "blue-shoes"`). Dynamic routes need their values: either that way
211
+ or in `params`.
199
212
  - `screen` is matched in this order:
200
213
  1. an exact name from `screens` (or its URL path, e.g. `/products`);
201
214
  2. the same, case-insensitive (`Products`, `/products`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-voice-bot-sdk",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Drop-in voice assistant widget for React Native and Expo apps: talks to your voice server over a WebSocket, plays the spoken reply, and lets the server open screens in your app.",
5
5
  "main": "build/index.js",
6
6
  "types": "build/index.d.ts",