react-native-voice-bot-sdk 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/README.md +10 -3
- package/build/VoiceBotClient.d.ts +7 -0
- package/build/VoiceBotClient.js +1 -1
- package/build/protocol.d.ts +2 -0
- package/build/react/VoiceBotProvider.d.ts +9 -3
- package/build/react/VoiceBotProvider.js +1 -1
- package/docs/ACTIONS.md +1 -1
- package/docs/INTEGRATION.md +10 -3
- package/docs/PROTOCOL.md +3 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.1
|
|
4
|
+
|
|
5
|
+
- **`userId`:** new option on `VoiceBotProvider` and `VoiceBot.connect()`, sent as `user_id` in the
|
|
6
|
+
connect message (next to `domain_id`). Your app's id for the signed-in user in any format (email, phone number, your own id); `""` for
|
|
7
|
+
guests. Never written to the SDK's logs.
|
|
8
|
+
When the provider's `userId` changes (sign in / sign out) it reconnects, so the server gets the
|
|
9
|
+
new user. Backwards compatible: without it `user_id` is `""`.
|
|
10
|
+
|
|
3
11
|
## 0.2.0
|
|
4
12
|
|
|
5
13
|
**Actions:** the AI server can now run operations that the app registers, not only open screens.
|
package/README.md
CHANGED
|
@@ -98,7 +98,7 @@ export default function RootLayout() {
|
|
|
98
98
|
const navigation = useExpoRouterNavigation(); // lets the server open your screens
|
|
99
99
|
|
|
100
100
|
return (
|
|
101
|
-
<VoiceBotProvider url="wss://voice.example.com/demo" domainId="YOUR_DOMAIN_ID" navigation={navigation}>
|
|
101
|
+
<VoiceBotProvider url="wss://voice.example.com/demo" domainId="YOUR_DOMAIN_ID" userId={currentUserId} navigation={navigation}>
|
|
102
102
|
<Stack />
|
|
103
103
|
</VoiceBotProvider>
|
|
104
104
|
);
|
|
@@ -112,13 +112,17 @@ import { VoiceBotProvider } from 'react-native-voice-bot-sdk';
|
|
|
112
112
|
|
|
113
113
|
export default function App() {
|
|
114
114
|
return (
|
|
115
|
-
<VoiceBotProvider url="wss://voice.example.com/demo" domainId="YOUR_DOMAIN_ID">
|
|
115
|
+
<VoiceBotProvider url="wss://voice.example.com/demo" domainId="YOUR_DOMAIN_ID" userId={currentUserId}>
|
|
116
116
|
<AppNavigator />
|
|
117
117
|
</VoiceBotProvider>
|
|
118
118
|
);
|
|
119
119
|
}
|
|
120
120
|
```
|
|
121
121
|
|
|
122
|
+
`url`, `domainId` and `userId` come from your app: the voice server address, your domain id, and
|
|
123
|
+
the id of the signed-in user in any format you choose: an email, a phone number or your own id (leave `userId` out, or pass `""`, for guests; when it changes the
|
|
124
|
+
provider reconnects so the server gets the new user).
|
|
125
|
+
|
|
122
126
|
That's the whole setup for the **widget-only** integration: the provider connects to your server
|
|
123
127
|
and shows the floating mic (bottom-right). The user taps it to talk and taps again to stop.
|
|
124
128
|
|
|
@@ -141,6 +145,7 @@ the mic:
|
|
|
141
145
|
{
|
|
142
146
|
"sessionId": "c0a8f6e2-…",
|
|
143
147
|
"domain_id": "YOUR_DOMAIN_ID",
|
|
148
|
+
"user_id": "YOUR_USER_ID",
|
|
144
149
|
"cookie_id": "9b2e4c1a-…",
|
|
145
150
|
"type": "Buffer",
|
|
146
151
|
"deviceId": 1,
|
|
@@ -190,6 +195,7 @@ with the options from the last `connect()` call and then starts the mic.
|
|
|
190
195
|
|--------|------|-------------|
|
|
191
196
|
| `url` | `string` | **Required.** WebSocket URL of the voice server. |
|
|
192
197
|
| `domainId` | `string` | Sent as `domain_id` in the connect message. Default `""`. |
|
|
198
|
+
| `userId` | `string` | Sent as `user_id`: your app's id for the signed-in user, in any format (email, phone number, your own id). Never logged by the SDK. Default `""` (guest). Connect again when it changes. |
|
|
193
199
|
| `cookieId` | `string` | Sent as `cookie_id`. Default: a random id the SDK saves on the device, so it stays the same across app launches. Pass your own id (e.g. your user's visitor id) to use that instead. |
|
|
194
200
|
| `onSuccess` | `({ sessionId }) => void` | Connected; the connect message (with the screen names) was sent. |
|
|
195
201
|
| `onFailure` | `(error) => void` | Couldn't connect. `error.code`: `connect_failed`, `connect_timeout`, `native_missing`, ... |
|
|
@@ -242,6 +248,7 @@ const { status, isReady, isListening, speaking, lastQuestion, lastPrompt, lastMe
|
|
|
242
248
|
|------|-------------|
|
|
243
249
|
| `url` | Voice server WebSocket URL. When set, the provider connects by itself. |
|
|
244
250
|
| `domainId` | Sent as `domain_id`. |
|
|
251
|
+
| `userId` | Sent as `user_id` (the signed-in user's id; leave out for guests). Changing it reconnects. |
|
|
245
252
|
| `autoConnect` | Default `true` (when `url` is set). |
|
|
246
253
|
| `widget` | Default `true`: the floating mic. Widget props to style it, `false` to use your own button. |
|
|
247
254
|
| `navigation` | A navigation adapter, so the server can open screens (see below). |
|
|
@@ -453,7 +460,7 @@ Metro or in `adb logcat` (tag `ReactNativeJS`):
|
|
|
453
460
|
```
|
|
454
461
|
[VoiceBot] 14:41:41.205 INFO connecting to ws://localhost:8091/demo
|
|
455
462
|
[VoiceBot] 14:41:41.512 INFO connected in 307 ms, session=81185a05-ccbf-43be-8ffc-20eae1c65a64
|
|
456
|
-
[VoiceBot] 14:41:41.514 INFO → connect message: domain_id=your-domain cookie_id=a527edd9… deviceId=1 sampleRate=16000 screens(5)=["cart","index","product/[id]","products","profile"]
|
|
463
|
+
[VoiceBot] 14:41:41.514 INFO → connect message: domain_id=your-domain user_id=(set, hidden) cookie_id=a527edd9… deviceId=1 sampleRate=16000 screens(5)=["cart","index","product/[id]","products","profile"]
|
|
457
464
|
[VoiceBot] 14:41:41.520 INFO → screen_changed: "index" backStack=["index"]
|
|
458
465
|
[VoiceBot] 14:41:43.101 INFO mic started: PCM s16le 16000 Hz mono, 640-byte frames (20 ms), uplink=BINARY
|
|
459
466
|
[VoiceBot] 14:41:43.140 INFO → first audio frame sent
|
|
@@ -45,6 +45,13 @@ export interface ConnectOptions {
|
|
|
45
45
|
uplinkEncoding?: 'binary' | 'base64';
|
|
46
46
|
/** `domain_id` in the connect message: your domain / tenant id. Default `""`. */
|
|
47
47
|
domainId?: string;
|
|
48
|
+
/**
|
|
49
|
+
* `user_id` in the connect message: your app's id for the signed-in user, in any format you choose
|
|
50
|
+
* (an email, a phone number, an internal or random id). Sent as is. Default `""` (no user, e.g. a
|
|
51
|
+
* guest). It is never written to the SDK's logs. When it changes (sign in / sign out), connect again so the server gets the new one;
|
|
52
|
+
* `<VoiceBotProvider userId>` does that for you.
|
|
53
|
+
*/
|
|
54
|
+
userId?: string;
|
|
48
55
|
/**
|
|
49
56
|
* `cookie_id` in the connect message: the visitor id. Default: a random id that the SDK saves on
|
|
50
57
|
* the device, so it stays the same across app launches (until the app is uninstalled or its data
|
package/build/VoiceBotClient.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AppState as e}from"react-native";import*as t from"./NativeAudio";import{ActionEngine as s}from"./actions/engine";import{ActionRegistry as n}from"./actions/registry";import{NoiseGate as i}from"./audio/noiseGate";import{base64ByteLength as o,base64ToBytes as a,bytesToBase64 as r}from"./base64";import{logger as c,preview as h,setLogLevel as l}from"./logger";import{findLocalIntent as d}from"./navigation/localIntent";import{decideMove as p,dynamicParams as u,matchScreen as g}from"./navigation/match";import{BYTES_PER_SECOND as m,SAMPLE_RATE as f}from"./protocol";function y(){const e=new Uint8Array(16),t=globalThis.crypto;if(t?.getRandomValues)t.getRandomValues(e);else for(let t=0;t<16;t++)e[t]=Math.floor(256*Math.random());e[6]=15&e[6]|64,e[8]=63&e[8]|128;const s=Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}const S=new Uint8Array(640),k=e=>(e/m).toFixed(2),b={1e3:"normal",1001:"going away",1002:"protocol error",1003:"unsupported data",1006:"connection lost (no close frame)",1008:"policy violation",1009:"message too big",1011:"server error"};export class VoiceBotClient{constructor(){this.ws=null,this.options=null,this.state={status:"idle",speaking:!1,sessionId:null,lastQuestion:null,lastPrompt:null,lastError:null,lastMessage:null},this.listeners=new Set,this.messageListeners=new Set,this.navigation=null,this.navUnsubscribe=null,this.lastSentScreen=null,this.screens=[],this.runCookieId=y(),this.wantConnected=!1,this.reconnectAttempt=0,this.reconnectTimer=null,this.reconnectDueAt=0,this.connectDeadline=0,this.onConnectDeadline=null,this.backgroundServiceOn=!1,this.stopMic=null,this.seq=0,this.speakingUntil=0,this.speakingTimer=null,this.connectTimer=null,this.connectStartedAt=0,this.micStartedAt=0,this.framesSent=0,this.framesDropped=0,this.replyCount=0,this.replyAudioSeconds=0,this.lastReplyRate=f,this.lastReplyNavKey=null,this.playingQuestion=null,this.speakingEndedAt=0,this.realPlaybackEnd=t.hasPlaybackIdleEvents(),this.bargedQuestion=null,this.gate=null,this.inCall=!1,this.lastSessionId=null,this.actions=new n,this.lastActionsKey="",this.screenContext=null,this.lastReplyNavAt=0,this.getState=()=>this.state,this.subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)}),this.addMessageListener=e=>(this.messageListeners.add(e),()=>{this.messageListeners.delete(e)}),this.connect=e=>{this.options=e,e.logLevel&&l(e.logLevel),this.wantConnected=!0,this.reconnectAttempt=0,this.clearReconnectTimer(),this.open()},this.disconnect=()=>{this.engine.cancelQueued("The app disconnected before this request started"),this.wantConnected=!1,this.reconnectAttempt=0,this.clearReconnectTimer(),this.stopRecording(),t.stopPlayback(),this.playingQuestion=null,this.closeSocket(1e3,"User exited"),this.setState({status:"idle",sessionId:null,speaking:!1})},this.start=async()=>{if(this.isListening)return!0;if(!this.isConnected)return this.reconnectTimer?(this.reconnectNow(),!1):this.options?("connecting"!==this.state.status?this.connect({...this.options,autoStart:!0}):this.options={...this.options,autoStart:!0},!1):(this.fail({code:"not_connected",message:"Call VoiceBot.connect({ url }) before start()"}),!1);try{if(!await t.requestMicPermission())return c.warn("microphone permission denied"),this.setState({lastError:{code:"mic_permission",message:"Microphone permission denied"}}),!1;this.seq=0,this.framesSent=0,this.framesDropped=0,this.micStartedAt=Date.now();const e="base64"===this.options?.uplinkEncoding,s=this.options?.noiseGate??!0;return this.gate=new i({..."object"==typeof s?s:{},enabled:!1!==s,whileSpeaking:this.options?.whileSpeaking??"mute"}),this.inCall=!1,this.stopMic=await t.startRecording((t=>this.onMicFrame(t,e)),(e=>{c.error(`mic error: ${e}`),this.setState({lastError:{code:"mic_failed",message:e}})})),this.isConnected?(this.setState({status:"listening",lastError:null}),this.startBackground(),c.info(`mic started: PCM s16le ${f} Hz mono, 640-byte frames (20 ms), uplink=${e?"base64 TEXT":"BINARY"}, noise gate ${!1===s?"off":"on"}, while bot speaks: ${this.options?.whileSpeaking??"mute"}, barge-in `+(!0===this.options?.bargeIn?"on":"off")),!0):(this.stopRecording(),!1)}catch(e){return c.error(`mic failed to start: ${e?.message??String(e)}`),this.setState({lastError:{code:"mic_failed",message:e?.message??String(e)}}),!1}},this.stop=()=>{this.stopRecording(),this.isConnected&&this.setState({status:"connected"})},this.toggle=async()=>{this.isListening?this.stop():await this.start()},this.registerAction=(e,t)=>this.actions.register(e,t),this.unregisterAction=e=>this.actions.unregister(e),this.setActions=e=>this.actions.replaceAll(e),this.getActions=()=>this.actions.metadata(),this.setConfirmHandler=e=>{this.confirmHandler=e??void 0},this.setScreenContext=e=>{this.screenContext=e?{screen:this.navigation?.getCurrentScreen()??null,params:e}:null,this.sendScreenChanged()},this.setNavigation=e=>{e!==this.navigation&&(this.navUnsubscribe?.(),this.navUnsubscribe=null,this.navigation=e,e&&(c.info(`navigation registered: ${e.kind}, ${e.getScreens().length} screens`),this.navUnsubscribe=e.subscribe((()=>this.sendScreenChanged())),this.isConnected&&this.state.sessionId&&(this.sendScreensUpdate(this.state.sessionId),this.lastSentScreen=null,this.sendScreenChanged())))},this.handleNavigate=async(e,t=!0)=>{const s="back"===e.action,n={type:"navigate_result",sessionId:this.state.sessionId??"",screen:e.screen??null,action:s?"back":"open",className:null,status:"failed",message:"",requestId:e.requestId??null},i=(e,s="",i=n.className)=>{n.status=e,n.message=s,n.className=i;const o=`→ navigate_result: ${e} ${"back"===n.action?"back":`"${n.screen}"`}`+(i&&i!==n.screen?` → ${i}`:"")+(s?` (${s})`:"");return"failed"===e?c.error(o):"unknown_screen"===e||"not_supported"===e?c.warn(o):c.info(o),t&&this.sendJson(n),n},o=this.navigation;if(!o)return i("not_supported","The app has no navigation registered with the voice bot");try{if(s){const e=o.getCurrentScreen();return await o.goBack()?i("went_back","",e):i("not_supported","Nothing to go back to",e)}if(!e.screen)return i("unknown_screen","No screen given");const t=this.matchScreen(e.screen);if(!t)return i("unknown_screen",`Not in the screens list: ${e.screen}`,null);const n=t.screen,a={...t.params??{},...e.params??{}},r=Object.keys(a).length?a:void 0,h=u(n.name).filter((e=>void 0===r?.[e]||""===r[e]));if(h.length){const e=n.name.replace(/\[(?:\.\.\.)?([^\]]+)\]/g,((e,t)=>`<${t}>`));return i("failed",`${n.name} needs ${h.join(", ")}: send "screen": "${e.replace(/^\(.*?\)\//,"")}" or "params": { ${h.map((e=>`"${e}": "…"`)).join(", ")} }`,n.name)}const l=o.getCurrentScreen(),d=o.getBackStack(),g=p(n.name,l,d,!!r);if("already_on_screen"===g)return i("already_on_screen","",n.name);"popTo"===g?await o.popTo(n,r):await o.push(n,r),c.debug(`navigate: ${g} ${n.name}${r?` ${JSON.stringify(r)}`:""} (from ${l??"-"})`);let m=await this.waitForScreen(o,n.name,l,!!r);return m!==n.name&&o.navigate&&(c.warn(`navigate: ${g} didn't reach ${n.name} (still on ${m??"-"}), trying navigate`),await o.navigate(n,r),m=await this.waitForScreen(o,n.name,l,!!r)),m!==n.name?i("failed",`Navigation didn't reach ${n.name}; the app is on ${m??"an unknown screen"}`,n.name):i("opened","",n.name)}catch(e){return i("failed",e?.message??String(e))}},this.engine=new s({registry:this.actions,navigate:(e,t)=>this.navigateForStep(e,t),getConfirmHandler:()=>this.confirmHandler,send:e=>this.trySend(e),sessionId:()=>this.state.sessionId??this.lastSessionId??"",log:{debug:e=>c.debug(e),info:e=>c.info(e),warn:e=>c.warn(e),error:e=>c.error(e)}}),this.actions.onChange((()=>this.sendActionsUpdate())),t.onInterruption((e=>this.handleInterruption(e))),t.onPlaybackIdle((()=>this.finishSpeaking("playback ended")));try{e.addEventListener("change",(e=>{"active"===e&&this.reconnectTimer&&(c.info("app is active again: reconnecting now"),this.reconnectNow())}))}catch{}}setState(e){this.state={...this.state,...e},this.listeners.forEach((e=>e()))}get isConnected(){return"connected"===this.state.status||"listening"===this.state.status}get isListening(){return"listening"===this.state.status}open(){const e=this.options;this.ws&&this.closeSocket(1e3,"Reconnecting");const{url:s}=e,n=this.reconnectAttempt>0;if(!t.isNativeAvailable())return void this.fail({code:"native_missing",message:t.NATIVE_MISSING_MESSAGE});this.setState({status:"connecting",lastError:null}),this.connectStartedAt=Date.now(),c.info(`connecting to ${s}`);let i=!1;const o=new WebSocket(s);o.binaryType="arraybuffer",this.ws=o;const a=e.connectTimeoutMs??1e4,r=()=>{i||this.ws!==o||(this.closeSocket(1e3,"Connect timeout"),n?this.scheduleReconnect(`timed out connecting to ${s}`):this.fail({code:"connect_timeout",message:`Timed out connecting to ${s}`}))};this.connectTimer=setTimeout(r,a),this.connectDeadline=Date.now()+a,this.onConnectDeadline=r,o.onopen=()=>{if(this.ws!==o)return;i=!0,this.clearConnectTimer();const t=n&&e.keepSessionOnReconnect&&this.lastSessionId?this.lastSessionId:y();this.lastSessionId=t,this.replyCount=0,this.lastReplyNavKey=null;const s=null!=this.stopMic;this.setState({status:s?"listening":"connected",sessionId:t,lastError:null}),c.info((n?`reconnected (attempt ${this.reconnectAttempt})`:"connected")+" in "+`${Date.now()-this.connectStartedAt} ms, session=${t}`+(n&&s?`, mic kept running (${this.framesDropped} frames dropped while offline)`:"")),this.reconnectAttempt=0,this.sendConnectMessage(t),this.lastSentScreen=null,this.sendScreenChanged(),this.engine.flush(),e.onSuccess?.({sessionId:t}),e.autoStart&&this.start()},o.onmessage=e=>{this.ws===o&&("string"==typeof e.data?this.handleText(e.data):c.debug(`← RECV binary message ignored (${e.data?.byteLength??"?"} bytes)`))},o.onerror=e=>{this.ws===o&&(e?.message&&c.warn(`socket error: ${e.message}`),i||setTimeout((()=>{if(this.ws!==o)return;this.clearConnectTimer(),this.ws=null;const t=e?.message||`Could not connect to ${s}`;n?this.scheduleReconnect(t):this.fail({code:"connect_failed",message:t})}),500))},o.onclose=t=>{if(this.ws!==o)return;if(this.ws=null,this.clearConnectTimer(),!i){const e=t.reason||`Could not connect to ${s}`;let i="";return/trust anchor|certificate|CertPath|SSL|handshake/i.test(e)?i=" (TLS: the server certificate is not trusted by the phone, e.g. self-signed. Use a certificate from a public CA, or ws:// for testing)":/refused/i.test(e)?i=" (nothing listening on that host/port)":/timeout|timed out|unreachable|no route/i.test(e)?i=" (host not reachable from the phone)":/cleartext/i.test(e)&&(i=" (ws:// is blocked: set allowCleartextTraffic in the config plugin)"),n?void this.scheduleReconnect(e+i):(this.stopRecording(),void this.fail({code:"connect_failed",message:e+i}))}const a=t.code??1006,r=`socket closed: code=${a} (${b[a]??"unknown"})${t.reason?` reason="${t.reason}"`:""}`;if(1e3===a?c.info(r):c.warn(r),e.onClose?.({code:a,reason:t.reason??""}),1e3!==a&&this.wantConnected&&this.reconnectEnabled())return this.setState({sessionId:null}),void this.scheduleReconnect(r);this.stopRecording(),this.setState({status:"idle",sessionId:null})}}reconnectEnabled(){return!1!==this.options?.autoReconnect}scheduleReconnect(e){const t="object"==typeof this.options?.autoReconnect?this.options.autoReconnect:{},s=t.maxAttempts??20,n=t.maxDelayMs??3e4;if(!this.wantConnected)return;if(this.reconnectAttempt>=s)return c.error(`giving up after ${this.reconnectAttempt} reconnect attempts (${e})`),this.reconnectAttempt=0,this.stopRecording(),void this.fail({code:"connect_failed",message:`Reconnect failed: ${e}`});this.reconnectAttempt++;const i=Math.min(n,1e3*2**(this.reconnectAttempt-1));c.warn(`reconnecting in ${(i/1e3).toFixed(0)} s (attempt ${this.reconnectAttempt}/${s}): ${e}`),this.setState({status:"connecting",sessionId:null}),this.options?.onReconnecting?.({attempt:this.reconnectAttempt,delayMs:i}),this.clearReconnectTimer(),this.reconnectDueAt=Date.now()+i,this.reconnectTimer=setTimeout((()=>{this.reconnectTimer=null,this.reconnectDueAt=0,this.wantConnected&&this.open()}),i)}reconnectNow(){this.reconnectTimer&&(this.clearReconnectTimer(),this.wantConnected&&this.open())}clearReconnectTimer(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.reconnectDueAt=0}closeSocket(e,t){const s=this.ws;if(this.ws=null,this.clearConnectTimer(),s){c.info(`→ closing socket: code=${e} reason="${t}"`);try{s.close(e,t)}catch{}}}clearConnectTimer(){this.connectTimer&&clearTimeout(this.connectTimer),this.connectTimer=null,this.connectDeadline=0,this.onConnectDeadline=null}tick(){const e=Date.now();if(this.reconnectDueAt&&e>=this.reconnectDueAt)this.reconnectNow();else if(this.connectDeadline&&e>=this.connectDeadline){const e=this.onConnectDeadline;this.clearConnectTimer(),e?.()}}fail(e){c.error(`${e.code}: ${e.message}`),this.setState({status:"idle",sessionId:null,lastError:e}),this.options?.onFailure?.(e)}sendJson(e){if(this.ws&&this.ws.readyState===WebSocket.OPEN){const t=JSON.stringify(e);c.debug(`→ SEND ${h(t)}`),this.ws.send(t)}else c.warn(`not sent (socket not open): ${h(e,120)}`)}sendConnectMessage(e){this.screens=this.navigation?.getScreens()??[];const t={sessionId:e,domain_id:this.options?.domainId??"",cookie_id:this.options?.cookieId||this.getSavedCookieId()||this.runCookieId,type:"Buffer",deviceId:this.options?.deviceId??1,sampleRate:f,screens:this.screens.map((e=>e.name))},s=this.actions.metadata();var n;s.length&&(t.actions=s),this.lastActionsKey=JSON.stringify(s),c.info(`→ connect message: domain_id=${t.domain_id||'""'} cookie_id=${n=t.cookie_id,n?`${n.slice(0,8)}…`:"-"} deviceId=${t.deviceId} sampleRate=${t.sampleRate} screens(${t.screens.length})=${JSON.stringify(t.screens)}`),s.length&&c.info(`→ actions(${s.length}): ${s.map((e=>e.name+(e.confirm?" (confirm)":""))).join(", ")}`),t.screens.length||c.warn("no screens sent: register navigation on <VoiceBotProvider navigation={...}> to enable voice navigation"),this.sendJson(t)}getSavedCookieId(){return void 0===this.savedCookieId&&(this.savedCookieId=t.getPersistentId("cookie_id")),this.savedCookieId}sendScreensUpdate(e){const t=this.screens.map((e=>e.name)).join("\n");this.screens=this.navigation?.getScreens()??[];const s=this.screens.map((e=>e.name));if(s.join("\n")===t)return;const n={type:"screens",sessionId:e,screens:s};c.info(`→ screens update (${s.length}): ${JSON.stringify(s)}`),this.sendJson(n)}async startBackground(){const e=this.options?.backgroundListening??!0;if(!1===e)return;const s="object"==typeof e&&e.title||"Voice assistant",n="object"==typeof e&&e.text||"Listening…",i=await t.startBackgroundService(s,n);!i||this.stopMic?(this.backgroundServiceOn=i,i&&c.info("background listening on (notification shown while the mic is on)")):t.stopBackgroundService()}stopRecording(){if(this.backgroundServiceOn&&(this.backgroundServiceOn=!1,t.stopBackgroundService()),this.stopMic){const e=this.gate?.flush()??[],s="base64"===this.options?.uplinkEncoding;e.forEach((e=>this.sendFrameBytes(e,s))),this.gate=null,t.stopRecording(),this.stopMic(),this.stopMic=null;const n=Date.now()-this.micStartedAt;c.info(`mic stopped after ${(n/1e3).toFixed(1)} s: sent ${this.framesSent} frames (${k(640*this.framesSent)} s of audio, ${640*this.framesSent} bytes)`+(this.framesDropped?`, dropped ${this.framesDropped} (socket not open)`:""))}}onMicFrame(e,t){this.tick();let s=a(e);if(this.inCall)s=S;else if(this.gate){const e=this.gate.process(s,this.botAudible());void 0!==e.speechEvent&&c.debug(e.speechEvent?`🗣 speech started (level ${this.gate.levelDb.toFixed(0)} dBFS, room ${this.gate.noiseFloorDb.toFixed(0)} dBFS)`:"… speech ended"),e.bargeIn&&!0===this.options?.bargeIn&&this.bargeIn(),s=e.out}s&&this.sendFrameBytes(s,t)}sendFrameBytes(e,t){const s=this.ws;if(!s||s.readyState!==WebSocket.OPEN)return this.framesDropped++,void(1===this.framesDropped&&c.warn("mic frame dropped: socket not open"));if(this.framesSent++,c.isEnabled("trace")&&c.trace(`→ SEND audio frame #${this.framesSent} (640 bytes, ${t?"base64 TEXT":"BINARY"})`),1===this.framesSent)c.info("→ first audio frame sent");else if(this.framesSent%250==0){const e=s.bufferedAmount??0,t=this.gate;c.info(`→ audio streaming: ${this.framesSent} frames (${k(640*this.framesSent)} s)`+(this.framesDropped?`, dropped ${this.framesDropped}`:"")+(t?`, speech ${(100*t.openRatio).toFixed(0)}% / silence ${(100-100*t.openRatio).toFixed(0)}%, room ${t.noiseFloorDb.toFixed(0)} dBFS`:"")+(this.inCall?", in a call (sending silence)":"")+(e>32e3?`, ${e} bytes waiting to send (slow network?)`:""))}t?s.send(JSON.stringify({type:"audio",sessionId:this.state.sessionId,seq:this.seq++,sampleRate:f,data:r(e)})):s.send(function(e){return 0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer}(e))}bargeIn(){this.state.speaking&&(t.stopPlayback(),c.info(`✋ barge-in: you started talking, stopped the reply to "${this.playingQuestion??""}"`),this.bargedQuestion=this.playingQuestion,this.stopSpeakingState())}stopSpeakingState(){this.speakingUntil=Date.now(),this.state.speaking&&(this.speakingEndedAt=Date.now()),this.speakingTimer&&clearTimeout(this.speakingTimer),this.speakingTimer=null,this.playingQuestion=null,t.releaseAudioFocus(),this.state.speaking&&this.setState({speaking:!1})}handleInterruption(e){if("focus_lost"===e)this.state.speaking&&c.info("🔇 another app took the audio: stopped the bot's reply"),this.stopSpeakingState();else if("call_started"===e){if(!1===this.options?.pauseOnCall||!this.stopMic)return;this.inCall=!0,this.stopSpeakingState(),c.info("📞 phone call: bot audio stopped, the mic sends silence until the call ends")}else"call_ended"===e&&this.inCall&&(this.inCall=!1,c.info("📞 call ended: mic audio resumed"))}handleText(e){let t;try{t=JSON.parse(e)}catch{return void c.warn(`← non-JSON text ignored: ${h(e,120)}`)}if(c.debug(`← RECV ${h(e)}`),!t||"object"!=typeof t)return;if(this.messageListeners.forEach((e=>e(t))),this.setState({lastMessage:t}),"actions"===t.type)return void this.engine.handle(t);if("cancel_actions"===t.type)return void(this.engine.cancel(t.requestId)||c.warn(`← cancel_actions ${t.requestId}: nothing running with that id`));if("action_ack"===t.type)return void this.engine.ack(t.requestId);if("navigate"===t.type)return c.info("← navigate: "+("back"===t.action?"back":`screen="${t.screen}"`)+(t.params?` params=${JSON.stringify(t.params)}`:"")+(null!=t.requestId?` requestId=${t.requestId}`:"")),void this.handleNavigate(t);const s=t;if("string"==typeof s.output)try{s.output=JSON.parse(s.output)}catch{}this.replyCount++;const n=this.state.lastQuestion,i=this.state.lastPrompt;"string"==typeof s.buffer&&s.buffer.length>0&&this.playReplyAudio(s,s.buffer);const o={};"string"==typeof s.question&&s.question&&(o.lastQuestion=s.question);const a=s.output?.prompt;"string"==typeof a&&a&&(o.lastPrompt=a),o.lastQuestion&&o.lastQuestion!==n&&c.info(`← you said: "${o.lastQuestion}"`),o.lastPrompt&&o.lastPrompt!==i&&c.info(`← bot: "${o.lastPrompt}"`);const r=s.output?.error;r&&0!==r&&"0"!==r&&c.warn(`← server reported error: ${h(s.output,200)}`),s.buffer||o.lastQuestion||o.lastPrompt||c.info(`← message: ${h(t,200)}`),Object.keys(o).length&&this.setState(o),this.navigateFromReply(s),this.options?.onReply?.(s)}navigateFromReply(e){const t=e.output;if(!t||"object"!=typeof t)return void this.localNavigate(e);const s=e=>"string"==typeof e?e.trim():"",n=s(t.type).toLowerCase(),i=s(t.intent).toLowerCase(),o=s(t.screen)||s(t.class_name)||s(t.target),a="back"===n||/^(back|go_back|goback)$/i.test(o);if(!(a||o&&("navigation"===n||"navigate"===n||"navigate"===i||a||this.matchScreen(o))))return void this.localNavigate(e);const r=`${e.question??""}|${a?"back":o}`,h=Date.now();r===this.lastReplyNavKey&&h-this.lastReplyNavAt<3e3||(this.lastReplyNavKey=r,this.lastReplyNavAt=h,c.info(`← reply asks for ${a?"back":`screen "${o}"`} (type="${s(t.type)}" intent="${s(t.intent)}" screen="${s(t.screen)}" class_name="${s(t.class_name)}" target="${s(t.target)}")`),this.handleNavigate(a?{type:"navigate",action:"back"}:{type:"navigate",screen:o}))}playReplyAudio(e,s){const n="string"==typeof e.question?e.question.trim():"";if(n&&n===this.bargedQuestion)c.debug(`← reply #${this.replyCount}: audio not played (you talked over "${n}")`);else{n&&(this.bargedQuestion=null);try{const i=o(s);n&&n!==this.playingQuestion&&(this.state.speaking&&!1!==this.options?.interruptOnNewReply&&this.interruptPlayback(n),this.playingQuestion=n,this.gate?.newReply()),i%2&&c.warn(`reply audio chunk has an odd byte count (${i}); last byte dropped`);const a=function(e){const t=e.output,s=Number(e.sample_rate??e.sampleRate??t?.sample_rate??t?.sampleRate);return Number.isFinite(s)&&s>=8e3&&s<=48e3?Math.round(s):f}(e);a!==this.lastReplyRate&&(c.info(`reply audio sample rate: ${a} Hz${a===f?" (default)":" (from the server)"}`),this.lastReplyRate=a),t.enqueuePlayback(s,a);const r=i/(2*a);c.debug(`← reply #${this.replyCount}: audio chunk ${i} bytes (${r.toFixed(2)} s at ${a} Hz) queued`),this.markSpeaking(r)}catch(e){c.error(`playback failed: ${e?.message??String(e)}`),this.setState({lastError:{code:"playback_failed",message:e?.message??String(e)}})}}}interruptPlayback(e){const s=Math.max(0,this.speakingUntil-Date.now())/1e3;t.stopPlayback(),c.info(`⏹ stopped old reply audio (${s.toFixed(1)} s left of "${this.playingQuestion??""}") for new reply to "${e}"`),this.speakingUntil=Date.now(),this.replyAudioSeconds=0}localNavigate(e){if(!1===this.options?.localNavigation||!this.navigation)return;const t="string"==typeof e.question?e.question.trim():"";if(!t)return;const s=this.screens.length?this.screens:this.navigation.getScreens(),n=d(t,s,this.options?.voiceShortcuts);if(!n)return;const i="back"===n.action?"back":n.screen,o=`${t}|local|${i}`,a=Date.now();o===this.lastReplyNavKey&&a-this.lastReplyNavAt<3e3||(this.lastReplyNavKey=o,this.lastReplyNavAt=a,c.info(`🧭 local shortcut: "${t}" → ${i} (the server's reply didn't navigate)`),this.handleNavigate("back"===n.action?{type:"navigate",action:"back",requestId:"local"}:{type:"navigate",screen:n.screen,requestId:"local"}))}markSpeaking(e){const t=Date.now();this.speakingUntil=Math.max(this.speakingUntil,t)+1e3*e,this.state.speaking||(this.replyAudioSeconds=0,c.info("🔊 bot speaking (reply audio playing)"),this.setState({speaking:!0})),this.replyAudioSeconds+=e,this.speakingTimer&&clearTimeout(this.speakingTimer);const s=this.realPlaybackEnd?3e3:250;this.speakingTimer=setTimeout((()=>this.finishSpeaking(this.realPlaybackEnd?"fallback timer":"estimated")),this.speakingUntil-t+s)}finishSpeaking(e){this.state.speaking&&(this.speakingTimer&&clearTimeout(this.speakingTimer),this.speakingTimer=null,c.info(`🔇 bot finished speaking (${this.replyAudioSeconds.toFixed(2)} s of audio, ${e})`),this.playingQuestion=null,this.speakingEndedAt=Date.now(),t.releaseAudioFocus(),this.setState({speaking:!1}))}botAudible(){if(this.state.speaking)return!0;const e=this.options?.echoTailMs??600;return Date.now()-this.speakingEndedAt<e}trySend(e){return!(!this.ws||this.ws.readyState!==WebSocket.OPEN||!this.state.sessionId||(this.sendJson(e),0))}sendActionsUpdate(){if(!this.isConnected||!this.state.sessionId)return;const e=this.actions.metadata(),t=JSON.stringify(e);t!==this.lastActionsKey&&(this.lastActionsKey=t,c.info(`→ actions_update (${e.length}): ${e.map((e=>e.name)).join(", ")}`),this.sendJson({type:"actions_update",sessionId:this.state.sessionId,actions:e}))}async navigateForStep(e,t){const s="back"===e?{type:"navigate",action:"back"}:{type:"navigate",screen:e,params:t},n=await this.handleNavigate(s,!1);return{status:n.status,screen:n.className,message:n.message}}currentScreenParams(e){const t={...this.navigation?.getCurrentParams?.()??{}};this.screenContext&&(null===this.screenContext.screen||this.screenContext.screen===e?Object.assign(t,this.screenContext.params):this.screenContext=null);const s={};let n=0;for(const[e,i]of Object.entries(t))if(!(n>=20||e.startsWith("__")||"screen"===e||"params"===e)){if("string"==typeof i&&i.length<=200)s[e]=i;else if("number"==typeof i&&Number.isFinite(i))s[e]=i;else{if("boolean"!=typeof i)continue;s[e]=i}n++}return n?s:void 0}sendScreenChanged(){if(!this.isConnected||!this.navigation||!this.state.sessionId)return;const e=this.navigation.getCurrentScreen();if(!e)return;const t=this.navigation.getBackStack(),s=this.currentScreenParams(e),n=`${e}|${t.join(",")}|${s?JSON.stringify(s):""}`;if(n===this.lastSentScreen)return;this.lastSentScreen=n;const i={type:"screen_changed",sessionId:this.state.sessionId,screen:e,backStack:t};s&&(i.params=s),c.info(`→ screen_changed: "${e}" backStack=${JSON.stringify(t)}${s?` params=${JSON.stringify(s)}`:""}`),this.sendJson(i)}async waitForScreen(t,s,n,i){const o=()=>t.getCurrentScreen();if(e.currentState&&"active"!==e.currentState)return s;for(let e=0;e<30;e++){const e=o();if(e===s&&(e!==n||i))return e;await new Promise((e=>setTimeout((()=>e()),50)))}return o()}matchScreen(e){const t=this.screens.length?this.screens:this.navigation?.getScreens()??[];return g(t,e)}}export const VoiceBot=new VoiceBotClient;
|
|
1
|
+
import{AppState as e}from"react-native";import*as t from"./NativeAudio";import{ActionEngine as s}from"./actions/engine";import{ActionRegistry as n}from"./actions/registry";import{NoiseGate as i}from"./audio/noiseGate";import{base64ByteLength as o,base64ToBytes as a,bytesToBase64 as r}from"./base64";import{logger as c,preview as h,setLogLevel as l}from"./logger";import{findLocalIntent as d}from"./navigation/localIntent";import{decideMove as p,dynamicParams as u,matchScreen as g}from"./navigation/match";import{BYTES_PER_SECOND as m,SAMPLE_RATE as f}from"./protocol";function y(){const e=new Uint8Array(16),t=globalThis.crypto;if(t?.getRandomValues)t.getRandomValues(e);else for(let t=0;t<16;t++)e[t]=Math.floor(256*Math.random());e[6]=15&e[6]|64,e[8]=63&e[8]|128;const s=Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}const S=new Uint8Array(640),k=e=>e.replace(/"user_id":"(?:[^"\\]|\\.)+"/g,'"user_id":"(hidden)"'),b=e=>(e/m).toFixed(2),$={1e3:"normal",1001:"going away",1002:"protocol error",1003:"unsupported data",1006:"connection lost (no close frame)",1008:"policy violation",1009:"message too big",1011:"server error"};export class VoiceBotClient{constructor(){this.ws=null,this.options=null,this.state={status:"idle",speaking:!1,sessionId:null,lastQuestion:null,lastPrompt:null,lastError:null,lastMessage:null},this.listeners=new Set,this.messageListeners=new Set,this.navigation=null,this.navUnsubscribe=null,this.lastSentScreen=null,this.screens=[],this.runCookieId=y(),this.wantConnected=!1,this.reconnectAttempt=0,this.reconnectTimer=null,this.reconnectDueAt=0,this.connectDeadline=0,this.onConnectDeadline=null,this.backgroundServiceOn=!1,this.stopMic=null,this.seq=0,this.speakingUntil=0,this.speakingTimer=null,this.connectTimer=null,this.connectStartedAt=0,this.micStartedAt=0,this.framesSent=0,this.framesDropped=0,this.replyCount=0,this.replyAudioSeconds=0,this.lastReplyRate=f,this.lastReplyNavKey=null,this.playingQuestion=null,this.speakingEndedAt=0,this.realPlaybackEnd=t.hasPlaybackIdleEvents(),this.bargedQuestion=null,this.gate=null,this.inCall=!1,this.lastSessionId=null,this.actions=new n,this.lastActionsKey="",this.screenContext=null,this.lastReplyNavAt=0,this.getState=()=>this.state,this.subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)}),this.addMessageListener=e=>(this.messageListeners.add(e),()=>{this.messageListeners.delete(e)}),this.connect=e=>{this.options=e,e.logLevel&&l(e.logLevel),this.wantConnected=!0,this.reconnectAttempt=0,this.clearReconnectTimer(),this.open()},this.disconnect=()=>{this.engine.cancelQueued("The app disconnected before this request started"),this.wantConnected=!1,this.reconnectAttempt=0,this.clearReconnectTimer(),this.stopRecording(),t.stopPlayback(),this.playingQuestion=null,this.closeSocket(1e3,"User exited"),this.setState({status:"idle",sessionId:null,speaking:!1})},this.start=async()=>{if(this.isListening)return!0;if(!this.isConnected)return this.reconnectTimer?(this.reconnectNow(),!1):this.options?("connecting"!==this.state.status?this.connect({...this.options,autoStart:!0}):this.options={...this.options,autoStart:!0},!1):(this.fail({code:"not_connected",message:"Call VoiceBot.connect({ url }) before start()"}),!1);try{if(!await t.requestMicPermission())return c.warn("microphone permission denied"),this.setState({lastError:{code:"mic_permission",message:"Microphone permission denied"}}),!1;this.seq=0,this.framesSent=0,this.framesDropped=0,this.micStartedAt=Date.now();const e="base64"===this.options?.uplinkEncoding,s=this.options?.noiseGate??!0;return this.gate=new i({..."object"==typeof s?s:{},enabled:!1!==s,whileSpeaking:this.options?.whileSpeaking??"mute"}),this.inCall=!1,this.stopMic=await t.startRecording((t=>this.onMicFrame(t,e)),(e=>{c.error(`mic error: ${e}`),this.setState({lastError:{code:"mic_failed",message:e}})})),this.isConnected?(this.setState({status:"listening",lastError:null}),this.startBackground(),c.info(`mic started: PCM s16le ${f} Hz mono, 640-byte frames (20 ms), uplink=${e?"base64 TEXT":"BINARY"}, noise gate ${!1===s?"off":"on"}, while bot speaks: ${this.options?.whileSpeaking??"mute"}, barge-in `+(!0===this.options?.bargeIn?"on":"off")),!0):(this.stopRecording(),!1)}catch(e){return c.error(`mic failed to start: ${e?.message??String(e)}`),this.setState({lastError:{code:"mic_failed",message:e?.message??String(e)}}),!1}},this.stop=()=>{this.stopRecording(),this.isConnected&&this.setState({status:"connected"})},this.toggle=async()=>{this.isListening?this.stop():await this.start()},this.registerAction=(e,t)=>this.actions.register(e,t),this.unregisterAction=e=>this.actions.unregister(e),this.setActions=e=>this.actions.replaceAll(e),this.getActions=()=>this.actions.metadata(),this.setConfirmHandler=e=>{this.confirmHandler=e??void 0},this.setScreenContext=e=>{this.screenContext=e?{screen:this.navigation?.getCurrentScreen()??null,params:e}:null,this.sendScreenChanged()},this.setNavigation=e=>{e!==this.navigation&&(this.navUnsubscribe?.(),this.navUnsubscribe=null,this.navigation=e,e&&(c.info(`navigation registered: ${e.kind}, ${e.getScreens().length} screens`),this.navUnsubscribe=e.subscribe((()=>this.sendScreenChanged())),this.isConnected&&this.state.sessionId&&(this.sendScreensUpdate(this.state.sessionId),this.lastSentScreen=null,this.sendScreenChanged())))},this.handleNavigate=async(e,t=!0)=>{const s="back"===e.action,n={type:"navigate_result",sessionId:this.state.sessionId??"",screen:e.screen??null,action:s?"back":"open",className:null,status:"failed",message:"",requestId:e.requestId??null},i=(e,s="",i=n.className)=>{n.status=e,n.message=s,n.className=i;const o=`→ navigate_result: ${e} ${"back"===n.action?"back":`"${n.screen}"`}`+(i&&i!==n.screen?` → ${i}`:"")+(s?` (${s})`:"");return"failed"===e?c.error(o):"unknown_screen"===e||"not_supported"===e?c.warn(o):c.info(o),t&&this.sendJson(n),n},o=this.navigation;if(!o)return i("not_supported","The app has no navigation registered with the voice bot");try{if(s){const e=o.getCurrentScreen();return await o.goBack()?i("went_back","",e):i("not_supported","Nothing to go back to",e)}if(!e.screen)return i("unknown_screen","No screen given");const t=this.matchScreen(e.screen);if(!t)return i("unknown_screen",`Not in the screens list: ${e.screen}`,null);const n=t.screen,a={...t.params??{},...e.params??{}},r=Object.keys(a).length?a:void 0,h=u(n.name).filter((e=>void 0===r?.[e]||""===r[e]));if(h.length){const e=n.name.replace(/\[(?:\.\.\.)?([^\]]+)\]/g,((e,t)=>`<${t}>`));return i("failed",`${n.name} needs ${h.join(", ")}: send "screen": "${e.replace(/^\(.*?\)\//,"")}" or "params": { ${h.map((e=>`"${e}": "…"`)).join(", ")} }`,n.name)}const l=o.getCurrentScreen(),d=o.getBackStack(),g=p(n.name,l,d,!!r);if("already_on_screen"===g)return i("already_on_screen","",n.name);"popTo"===g?await o.popTo(n,r):await o.push(n,r),c.debug(`navigate: ${g} ${n.name}${r?` ${JSON.stringify(r)}`:""} (from ${l??"-"})`);let m=await this.waitForScreen(o,n.name,l,!!r);return m!==n.name&&o.navigate&&(c.warn(`navigate: ${g} didn't reach ${n.name} (still on ${m??"-"}), trying navigate`),await o.navigate(n,r),m=await this.waitForScreen(o,n.name,l,!!r)),m!==n.name?i("failed",`Navigation didn't reach ${n.name}; the app is on ${m??"an unknown screen"}`,n.name):i("opened","",n.name)}catch(e){return i("failed",e?.message??String(e))}},this.engine=new s({registry:this.actions,navigate:(e,t)=>this.navigateForStep(e,t),getConfirmHandler:()=>this.confirmHandler,send:e=>this.trySend(e),sessionId:()=>this.state.sessionId??this.lastSessionId??"",log:{debug:e=>c.debug(e),info:e=>c.info(e),warn:e=>c.warn(e),error:e=>c.error(e)}}),this.actions.onChange((()=>this.sendActionsUpdate())),t.onInterruption((e=>this.handleInterruption(e))),t.onPlaybackIdle((()=>this.finishSpeaking("playback ended")));try{e.addEventListener("change",(e=>{"active"===e&&this.reconnectTimer&&(c.info("app is active again: reconnecting now"),this.reconnectNow())}))}catch{}}setState(e){this.state={...this.state,...e},this.listeners.forEach((e=>e()))}get isConnected(){return"connected"===this.state.status||"listening"===this.state.status}get isListening(){return"listening"===this.state.status}open(){const e=this.options;this.ws&&this.closeSocket(1e3,"Reconnecting");const{url:s}=e,n=this.reconnectAttempt>0;if(!t.isNativeAvailable())return void this.fail({code:"native_missing",message:t.NATIVE_MISSING_MESSAGE});this.setState({status:"connecting",lastError:null}),this.connectStartedAt=Date.now(),c.info(`connecting to ${s}`);let i=!1;const o=new WebSocket(s);o.binaryType="arraybuffer",this.ws=o;const a=e.connectTimeoutMs??1e4,r=()=>{i||this.ws!==o||(this.closeSocket(1e3,"Connect timeout"),n?this.scheduleReconnect(`timed out connecting to ${s}`):this.fail({code:"connect_timeout",message:`Timed out connecting to ${s}`}))};this.connectTimer=setTimeout(r,a),this.connectDeadline=Date.now()+a,this.onConnectDeadline=r,o.onopen=()=>{if(this.ws!==o)return;i=!0,this.clearConnectTimer();const t=n&&e.keepSessionOnReconnect&&this.lastSessionId?this.lastSessionId:y();this.lastSessionId=t,this.replyCount=0,this.lastReplyNavKey=null;const s=null!=this.stopMic;this.setState({status:s?"listening":"connected",sessionId:t,lastError:null}),c.info((n?`reconnected (attempt ${this.reconnectAttempt})`:"connected")+" in "+`${Date.now()-this.connectStartedAt} ms, session=${t}`+(n&&s?`, mic kept running (${this.framesDropped} frames dropped while offline)`:"")),this.reconnectAttempt=0,this.sendConnectMessage(t),this.lastSentScreen=null,this.sendScreenChanged(),this.engine.flush(),e.onSuccess?.({sessionId:t}),e.autoStart&&this.start()},o.onmessage=e=>{this.ws===o&&("string"==typeof e.data?this.handleText(e.data):c.debug(`← RECV binary message ignored (${e.data?.byteLength??"?"} bytes)`))},o.onerror=e=>{this.ws===o&&(e?.message&&c.warn(`socket error: ${e.message}`),i||setTimeout((()=>{if(this.ws!==o)return;this.clearConnectTimer(),this.ws=null;const t=e?.message||`Could not connect to ${s}`;n?this.scheduleReconnect(t):this.fail({code:"connect_failed",message:t})}),500))},o.onclose=t=>{if(this.ws!==o)return;if(this.ws=null,this.clearConnectTimer(),!i){const e=t.reason||`Could not connect to ${s}`;let i="";return/trust anchor|certificate|CertPath|SSL|handshake/i.test(e)?i=" (TLS: the server certificate is not trusted by the phone, e.g. self-signed. Use a certificate from a public CA, or ws:// for testing)":/refused/i.test(e)?i=" (nothing listening on that host/port)":/timeout|timed out|unreachable|no route/i.test(e)?i=" (host not reachable from the phone)":/cleartext/i.test(e)&&(i=" (ws:// is blocked: set allowCleartextTraffic in the config plugin)"),n?void this.scheduleReconnect(e+i):(this.stopRecording(),void this.fail({code:"connect_failed",message:e+i}))}const a=t.code??1006,r=`socket closed: code=${a} (${$[a]??"unknown"})${t.reason?` reason="${t.reason}"`:""}`;if(1e3===a?c.info(r):c.warn(r),e.onClose?.({code:a,reason:t.reason??""}),1e3!==a&&this.wantConnected&&this.reconnectEnabled())return this.setState({sessionId:null}),void this.scheduleReconnect(r);this.stopRecording(),this.setState({status:"idle",sessionId:null})}}reconnectEnabled(){return!1!==this.options?.autoReconnect}scheduleReconnect(e){const t="object"==typeof this.options?.autoReconnect?this.options.autoReconnect:{},s=t.maxAttempts??20,n=t.maxDelayMs??3e4;if(!this.wantConnected)return;if(this.reconnectAttempt>=s)return c.error(`giving up after ${this.reconnectAttempt} reconnect attempts (${e})`),this.reconnectAttempt=0,this.stopRecording(),void this.fail({code:"connect_failed",message:`Reconnect failed: ${e}`});this.reconnectAttempt++;const i=Math.min(n,1e3*2**(this.reconnectAttempt-1));c.warn(`reconnecting in ${(i/1e3).toFixed(0)} s (attempt ${this.reconnectAttempt}/${s}): ${e}`),this.setState({status:"connecting",sessionId:null}),this.options?.onReconnecting?.({attempt:this.reconnectAttempt,delayMs:i}),this.clearReconnectTimer(),this.reconnectDueAt=Date.now()+i,this.reconnectTimer=setTimeout((()=>{this.reconnectTimer=null,this.reconnectDueAt=0,this.wantConnected&&this.open()}),i)}reconnectNow(){this.reconnectTimer&&(this.clearReconnectTimer(),this.wantConnected&&this.open())}clearReconnectTimer(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.reconnectDueAt=0}closeSocket(e,t){const s=this.ws;if(this.ws=null,this.clearConnectTimer(),s){c.info(`→ closing socket: code=${e} reason="${t}"`);try{s.close(e,t)}catch{}}}clearConnectTimer(){this.connectTimer&&clearTimeout(this.connectTimer),this.connectTimer=null,this.connectDeadline=0,this.onConnectDeadline=null}tick(){const e=Date.now();if(this.reconnectDueAt&&e>=this.reconnectDueAt)this.reconnectNow();else if(this.connectDeadline&&e>=this.connectDeadline){const e=this.onConnectDeadline;this.clearConnectTimer(),e?.()}}fail(e){c.error(`${e.code}: ${e.message}`),this.setState({status:"idle",sessionId:null,lastError:e}),this.options?.onFailure?.(e)}sendJson(e){if(this.ws&&this.ws.readyState===WebSocket.OPEN){const t=JSON.stringify(e);c.debug(`→ SEND ${h(k(t))}`),this.ws.send(t)}else c.warn(`not sent (socket not open): ${h(k(JSON.stringify(e)),120)}`)}sendConnectMessage(e){this.screens=this.navigation?.getScreens()??[];const t={sessionId:e,domain_id:this.options?.domainId??"",user_id:this.options?.userId??"",cookie_id:this.options?.cookieId||this.getSavedCookieId()||this.runCookieId,type:"Buffer",deviceId:this.options?.deviceId??1,sampleRate:f,screens:this.screens.map((e=>e.name))},s=this.actions.metadata();var n;s.length&&(t.actions=s),this.lastActionsKey=JSON.stringify(s),c.info(`→ connect message: domain_id=${t.domain_id||'""'} user_id=${t.user_id?"(set, hidden)":'""'} cookie_id=${n=t.cookie_id,n?`${n.slice(0,8)}…`:"-"} deviceId=${t.deviceId} sampleRate=${t.sampleRate} screens(${t.screens.length})=${JSON.stringify(t.screens)}`),s.length&&c.info(`→ actions(${s.length}): ${s.map((e=>e.name+(e.confirm?" (confirm)":""))).join(", ")}`),t.screens.length||c.warn("no screens sent: register navigation on <VoiceBotProvider navigation={...}> to enable voice navigation"),this.sendJson(t)}getSavedCookieId(){return void 0===this.savedCookieId&&(this.savedCookieId=t.getPersistentId("cookie_id")),this.savedCookieId}sendScreensUpdate(e){const t=this.screens.map((e=>e.name)).join("\n");this.screens=this.navigation?.getScreens()??[];const s=this.screens.map((e=>e.name));if(s.join("\n")===t)return;const n={type:"screens",sessionId:e,screens:s};c.info(`→ screens update (${s.length}): ${JSON.stringify(s)}`),this.sendJson(n)}async startBackground(){const e=this.options?.backgroundListening??!0;if(!1===e)return;const s="object"==typeof e&&e.title||"Voice assistant",n="object"==typeof e&&e.text||"Listening…",i=await t.startBackgroundService(s,n);!i||this.stopMic?(this.backgroundServiceOn=i,i&&c.info("background listening on (notification shown while the mic is on)")):t.stopBackgroundService()}stopRecording(){if(this.backgroundServiceOn&&(this.backgroundServiceOn=!1,t.stopBackgroundService()),this.stopMic){const e=this.gate?.flush()??[],s="base64"===this.options?.uplinkEncoding;e.forEach((e=>this.sendFrameBytes(e,s))),this.gate=null,t.stopRecording(),this.stopMic(),this.stopMic=null;const n=Date.now()-this.micStartedAt;c.info(`mic stopped after ${(n/1e3).toFixed(1)} s: sent ${this.framesSent} frames (${b(640*this.framesSent)} s of audio, ${640*this.framesSent} bytes)`+(this.framesDropped?`, dropped ${this.framesDropped} (socket not open)`:""))}}onMicFrame(e,t){this.tick();let s=a(e);if(this.inCall)s=S;else if(this.gate){const e=this.gate.process(s,this.botAudible());void 0!==e.speechEvent&&c.debug(e.speechEvent?`🗣 speech started (level ${this.gate.levelDb.toFixed(0)} dBFS, room ${this.gate.noiseFloorDb.toFixed(0)} dBFS)`:"… speech ended"),e.bargeIn&&!0===this.options?.bargeIn&&this.bargeIn(),s=e.out}s&&this.sendFrameBytes(s,t)}sendFrameBytes(e,t){const s=this.ws;if(!s||s.readyState!==WebSocket.OPEN)return this.framesDropped++,void(1===this.framesDropped&&c.warn("mic frame dropped: socket not open"));if(this.framesSent++,c.isEnabled("trace")&&c.trace(`→ SEND audio frame #${this.framesSent} (640 bytes, ${t?"base64 TEXT":"BINARY"})`),1===this.framesSent)c.info("→ first audio frame sent");else if(this.framesSent%250==0){const e=s.bufferedAmount??0,t=this.gate;c.info(`→ audio streaming: ${this.framesSent} frames (${b(640*this.framesSent)} s)`+(this.framesDropped?`, dropped ${this.framesDropped}`:"")+(t?`, speech ${(100*t.openRatio).toFixed(0)}% / silence ${(100-100*t.openRatio).toFixed(0)}%, room ${t.noiseFloorDb.toFixed(0)} dBFS`:"")+(this.inCall?", in a call (sending silence)":"")+(e>32e3?`, ${e} bytes waiting to send (slow network?)`:""))}t?s.send(JSON.stringify({type:"audio",sessionId:this.state.sessionId,seq:this.seq++,sampleRate:f,data:r(e)})):s.send(function(e){return 0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer}(e))}bargeIn(){this.state.speaking&&(t.stopPlayback(),c.info(`✋ barge-in: you started talking, stopped the reply to "${this.playingQuestion??""}"`),this.bargedQuestion=this.playingQuestion,this.stopSpeakingState())}stopSpeakingState(){this.speakingUntil=Date.now(),this.state.speaking&&(this.speakingEndedAt=Date.now()),this.speakingTimer&&clearTimeout(this.speakingTimer),this.speakingTimer=null,this.playingQuestion=null,t.releaseAudioFocus(),this.state.speaking&&this.setState({speaking:!1})}handleInterruption(e){if("focus_lost"===e)this.state.speaking&&c.info("🔇 another app took the audio: stopped the bot's reply"),this.stopSpeakingState();else if("call_started"===e){if(!1===this.options?.pauseOnCall||!this.stopMic)return;this.inCall=!0,this.stopSpeakingState(),c.info("📞 phone call: bot audio stopped, the mic sends silence until the call ends")}else"call_ended"===e&&this.inCall&&(this.inCall=!1,c.info("📞 call ended: mic audio resumed"))}handleText(e){let t;try{t=JSON.parse(e)}catch{return void c.warn(`← non-JSON text ignored: ${h(e,120)}`)}if(c.debug(`← RECV ${h(k(e))}`),!t||"object"!=typeof t)return;if(this.messageListeners.forEach((e=>e(t))),this.setState({lastMessage:t}),"actions"===t.type)return void this.engine.handle(t);if("cancel_actions"===t.type)return void(this.engine.cancel(t.requestId)||c.warn(`← cancel_actions ${t.requestId}: nothing running with that id`));if("action_ack"===t.type)return void this.engine.ack(t.requestId);if("navigate"===t.type)return c.info("← navigate: "+("back"===t.action?"back":`screen="${t.screen}"`)+(t.params?` params=${JSON.stringify(t.params)}`:"")+(null!=t.requestId?` requestId=${t.requestId}`:"")),void this.handleNavigate(t);const s=t;if("string"==typeof s.output)try{s.output=JSON.parse(s.output)}catch{}this.replyCount++;const n=this.state.lastQuestion,i=this.state.lastPrompt;"string"==typeof s.buffer&&s.buffer.length>0&&this.playReplyAudio(s,s.buffer);const o={};"string"==typeof s.question&&s.question&&(o.lastQuestion=s.question);const a=s.output?.prompt;"string"==typeof a&&a&&(o.lastPrompt=a),o.lastQuestion&&o.lastQuestion!==n&&c.info(`← you said: "${o.lastQuestion}"`),o.lastPrompt&&o.lastPrompt!==i&&c.info(`← bot: "${o.lastPrompt}"`);const r=s.output?.error;r&&0!==r&&"0"!==r&&c.warn(`← server reported error: ${h(s.output,200)}`),s.buffer||o.lastQuestion||o.lastPrompt||c.info(`← message: ${h(t,200)}`),Object.keys(o).length&&this.setState(o),this.navigateFromReply(s),this.options?.onReply?.(s)}navigateFromReply(e){const t=e.output;if(!t||"object"!=typeof t)return void this.localNavigate(e);const s=e=>"string"==typeof e?e.trim():"",n=s(t.type).toLowerCase(),i=s(t.intent).toLowerCase(),o=s(t.screen)||s(t.class_name)||s(t.target),a="back"===n||/^(back|go_back|goback)$/i.test(o);if(!(a||o&&("navigation"===n||"navigate"===n||"navigate"===i||a||this.matchScreen(o))))return void this.localNavigate(e);const r=`${e.question??""}|${a?"back":o}`,h=Date.now();r===this.lastReplyNavKey&&h-this.lastReplyNavAt<3e3||(this.lastReplyNavKey=r,this.lastReplyNavAt=h,c.info(`← reply asks for ${a?"back":`screen "${o}"`} (type="${s(t.type)}" intent="${s(t.intent)}" screen="${s(t.screen)}" class_name="${s(t.class_name)}" target="${s(t.target)}")`),this.handleNavigate(a?{type:"navigate",action:"back"}:{type:"navigate",screen:o}))}playReplyAudio(e,s){const n="string"==typeof e.question?e.question.trim():"";if(n&&n===this.bargedQuestion)c.debug(`← reply #${this.replyCount}: audio not played (you talked over "${n}")`);else{n&&(this.bargedQuestion=null);try{const i=o(s);n&&n!==this.playingQuestion&&(this.state.speaking&&!1!==this.options?.interruptOnNewReply&&this.interruptPlayback(n),this.playingQuestion=n,this.gate?.newReply()),i%2&&c.warn(`reply audio chunk has an odd byte count (${i}); last byte dropped`);const a=function(e){const t=e.output,s=Number(e.sample_rate??e.sampleRate??t?.sample_rate??t?.sampleRate);return Number.isFinite(s)&&s>=8e3&&s<=48e3?Math.round(s):f}(e);a!==this.lastReplyRate&&(c.info(`reply audio sample rate: ${a} Hz${a===f?" (default)":" (from the server)"}`),this.lastReplyRate=a),t.enqueuePlayback(s,a);const r=i/(2*a);c.debug(`← reply #${this.replyCount}: audio chunk ${i} bytes (${r.toFixed(2)} s at ${a} Hz) queued`),this.markSpeaking(r)}catch(e){c.error(`playback failed: ${e?.message??String(e)}`),this.setState({lastError:{code:"playback_failed",message:e?.message??String(e)}})}}}interruptPlayback(e){const s=Math.max(0,this.speakingUntil-Date.now())/1e3;t.stopPlayback(),c.info(`⏹ stopped old reply audio (${s.toFixed(1)} s left of "${this.playingQuestion??""}") for new reply to "${e}"`),this.speakingUntil=Date.now(),this.replyAudioSeconds=0}localNavigate(e){if(!1===this.options?.localNavigation||!this.navigation)return;const t="string"==typeof e.question?e.question.trim():"";if(!t)return;const s=this.screens.length?this.screens:this.navigation.getScreens(),n=d(t,s,this.options?.voiceShortcuts);if(!n)return;const i="back"===n.action?"back":n.screen,o=`${t}|local|${i}`,a=Date.now();o===this.lastReplyNavKey&&a-this.lastReplyNavAt<3e3||(this.lastReplyNavKey=o,this.lastReplyNavAt=a,c.info(`🧭 local shortcut: "${t}" → ${i} (the server's reply didn't navigate)`),this.handleNavigate("back"===n.action?{type:"navigate",action:"back",requestId:"local"}:{type:"navigate",screen:n.screen,requestId:"local"}))}markSpeaking(e){const t=Date.now();this.speakingUntil=Math.max(this.speakingUntil,t)+1e3*e,this.state.speaking||(this.replyAudioSeconds=0,c.info("🔊 bot speaking (reply audio playing)"),this.setState({speaking:!0})),this.replyAudioSeconds+=e,this.speakingTimer&&clearTimeout(this.speakingTimer);const s=this.realPlaybackEnd?3e3:250;this.speakingTimer=setTimeout((()=>this.finishSpeaking(this.realPlaybackEnd?"fallback timer":"estimated")),this.speakingUntil-t+s)}finishSpeaking(e){this.state.speaking&&(this.speakingTimer&&clearTimeout(this.speakingTimer),this.speakingTimer=null,c.info(`🔇 bot finished speaking (${this.replyAudioSeconds.toFixed(2)} s of audio, ${e})`),this.playingQuestion=null,this.speakingEndedAt=Date.now(),t.releaseAudioFocus(),this.setState({speaking:!1}))}botAudible(){if(this.state.speaking)return!0;const e=this.options?.echoTailMs??600;return Date.now()-this.speakingEndedAt<e}trySend(e){return!(!this.ws||this.ws.readyState!==WebSocket.OPEN||!this.state.sessionId||(this.sendJson(e),0))}sendActionsUpdate(){if(!this.isConnected||!this.state.sessionId)return;const e=this.actions.metadata(),t=JSON.stringify(e);t!==this.lastActionsKey&&(this.lastActionsKey=t,c.info(`→ actions_update (${e.length}): ${e.map((e=>e.name)).join(", ")}`),this.sendJson({type:"actions_update",sessionId:this.state.sessionId,actions:e}))}async navigateForStep(e,t){const s="back"===e?{type:"navigate",action:"back"}:{type:"navigate",screen:e,params:t},n=await this.handleNavigate(s,!1);return{status:n.status,screen:n.className,message:n.message}}currentScreenParams(e){const t={...this.navigation?.getCurrentParams?.()??{}};this.screenContext&&(null===this.screenContext.screen||this.screenContext.screen===e?Object.assign(t,this.screenContext.params):this.screenContext=null);const s={};let n=0;for(const[e,i]of Object.entries(t))if(!(n>=20||e.startsWith("__")||"screen"===e||"params"===e)){if("string"==typeof i&&i.length<=200)s[e]=i;else if("number"==typeof i&&Number.isFinite(i))s[e]=i;else{if("boolean"!=typeof i)continue;s[e]=i}n++}return n?s:void 0}sendScreenChanged(){if(!this.isConnected||!this.navigation||!this.state.sessionId)return;const e=this.navigation.getCurrentScreen();if(!e)return;const t=this.navigation.getBackStack(),s=this.currentScreenParams(e),n=`${e}|${t.join(",")}|${s?JSON.stringify(s):""}`;if(n===this.lastSentScreen)return;this.lastSentScreen=n;const i={type:"screen_changed",sessionId:this.state.sessionId,screen:e,backStack:t};s&&(i.params=s),c.info(`→ screen_changed: "${e}" backStack=${JSON.stringify(t)}${s?` params=${JSON.stringify(s)}`:""}`),this.sendJson(i)}async waitForScreen(t,s,n,i){const o=()=>t.getCurrentScreen();if(e.currentState&&"active"!==e.currentState)return s;for(let e=0;e<30;e++){const e=o();if(e===s&&(e!==n||i))return e;await new Promise((e=>setTimeout((()=>e()),50)))}return o()}matchScreen(e){const t=this.screens.length?this.screens:this.navigation?.getScreens()??[];return g(t,e)}}export const VoiceBot=new VoiceBotClient;
|
package/build/protocol.d.ts
CHANGED
|
@@ -16,6 +16,8 @@ export interface ConnectMessage {
|
|
|
16
16
|
sessionId: string;
|
|
17
17
|
/** Host app's domain / tenant id (from `connect({ domainId })`). */
|
|
18
18
|
domain_id: string;
|
|
19
|
+
/** The app's user id (from `connect({ userId })`): any string the app chooses (email, phone, id); `""` for guests. */
|
|
20
|
+
user_id: string;
|
|
19
21
|
/** Visitor id (from `connect({ cookieId })`, or a random id kept for the app run). */
|
|
20
22
|
cookie_id: string;
|
|
21
23
|
type: 'Buffer';
|
|
@@ -14,6 +14,12 @@ export interface VoiceBotProviderProps {
|
|
|
14
14
|
url?: string;
|
|
15
15
|
/** Your domain / tenant id, sent as `domain_id`. */
|
|
16
16
|
domainId?: string;
|
|
17
|
+
/**
|
|
18
|
+
* Your app's id for the signed-in user, sent as `user_id`: an email, a phone number or any id of
|
|
19
|
+
* yours (sent as is, never logged). Leave it out (or `""`) for guests.
|
|
20
|
+
* When it changes (sign in / sign out) the provider reconnects, so the server gets the new user.
|
|
21
|
+
*/
|
|
22
|
+
userId?: string;
|
|
17
23
|
/** Connect as soon as the provider mounts (when `url` is set). Default `true`. */
|
|
18
24
|
autoConnect?: boolean;
|
|
19
25
|
/**
|
|
@@ -39,7 +45,7 @@ export interface VoiceBotProviderProps {
|
|
|
39
45
|
/** Every JSON message from the server (replies, navigate commands, custom messages). */
|
|
40
46
|
onMessage?(message: Record<string, unknown>): void;
|
|
41
47
|
/** Advanced options, the same as `VoiceBot.connect()` (noise gate, barge-in, reconnect, logs ...). */
|
|
42
|
-
options?: Omit<ConnectOptions, 'url' | 'domainId' | 'onSuccess' | 'onFailure' | 'onClose' | 'onReply'>;
|
|
48
|
+
options?: Omit<ConnectOptions, 'url' | 'domainId' | 'userId' | 'onSuccess' | 'onFailure' | 'onClose' | 'onReply'>;
|
|
43
49
|
/**
|
|
44
50
|
* Actions of your app the AI server may run, by name. Each has a description, a params schema
|
|
45
51
|
* and a `run` function that uses your app's own APIs. See docs/ACTIONS.md. Optional: without it
|
|
@@ -59,8 +65,8 @@ export declare const alertConfirm: ConfirmHandler;
|
|
|
59
65
|
/**
|
|
60
66
|
* Wrap your app once. With `url` it connects to your voice server and shows the floating mic:
|
|
61
67
|
*
|
|
62
|
-
* <VoiceBotProvider url="wss://voice.example.com/demo" domainId="your-domain-id" navigation={navigation}>
|
|
68
|
+
* <VoiceBotProvider url="wss://voice.example.com/demo" domainId="your-domain-id" userId={user?.id} navigation={navigation}>
|
|
63
69
|
* <App />
|
|
64
70
|
* </VoiceBotProvider>
|
|
65
71
|
*/
|
|
66
|
-
export declare function VoiceBotProvider({ children, url, domainId, autoConnect, widget, navigation, onConnect, onError, onClose, onReply, onMessage, options, actions, onConfirmAction, disconnectOnUnmount, }: VoiceBotProviderProps): React.JSX.Element;
|
|
72
|
+
export declare function VoiceBotProvider({ children, url, domainId, userId, autoConnect, widget, navigation, onConnect, onError, onClose, onReply, onMessage, options, actions, onConfirmAction, disconnectOnUnmount, }: VoiceBotProviderProps): React.JSX.Element;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{jsx as
|
|
1
|
+
import{jsx as e,jsxs as n}from"react/jsx-runtime";import{useEffect as o,useRef as t}from"react";import{Alert as r,StyleSheet as s,View as i}from"react-native";import{VoiceBot as c}from"../VoiceBotClient";import{VoiceBotWidget as l}from"./VoiceBotWidget";export const alertConfirm=e=>new Promise((n=>{let o=!1;const t=e=>{o||(o=!0,n(e))};e.signal.addEventListener?.("abort",(()=>t("cancelled"))),r.alert(e.title,e.message||void 0,[{text:e.cancelLabel,style:"cancel",onPress:()=>t("rejected")},{text:e.confirmLabel,onPress:()=>t("approved")}],{cancelable:!0,onDismiss:()=>t("cancelled")})}));export function VoiceBotProvider({children:r,url:s,domainId:d,userId:u,autoConnect:m=!0,widget:p=!0,navigation:f=null,onConnect:C,onError:g,onClose:v,onReply:x,onMessage:y,options:b,actions:j,onConfirmAction:E,disconnectOnUnmount:M=!0}){const R=t({onConnect:C,onError:g,onClose:v,onReply:x,onMessage:y,options:b});return R.current={onConnect:C,onError:g,onClose:v,onReply:x,onMessage:y,options:b},o((()=>{c.setNavigation(f)}),[f]),o((()=>c.addMessageListener((e=>R.current.onMessage?.(e)))),[]),o((()=>{if(j)return c.setActions(j),()=>c.setActions({})}),[j]),o((()=>{c.setConfirmHandler(E??alertConfirm)}),[E]),o((()=>{if(s&&m)return c.connect({...R.current.options,url:s,domainId:d,userId:u,onSuccess:e=>R.current.onConnect?.(e),onFailure:e=>R.current.onError?.(e),onClose:e=>R.current.onClose?.(e),onReply:e=>R.current.onReply?.(e)}),()=>c.disconnect()}),[s,d,u,m]),o((()=>()=>{c.setNavigation(null),M&&c.disconnect()}),[M]),n(i,{style:a.fill,children:[r,p?e(l,{..."object"==typeof p?p:{}}):null]})}const a=s.create({fill:{flex:1}});
|
package/docs/ACTIONS.md
CHANGED
|
@@ -44,7 +44,7 @@ const actions: Record<string, ActionDefinition> = {
|
|
|
44
44
|
},
|
|
45
45
|
};
|
|
46
46
|
|
|
47
|
-
<VoiceBotProvider url={URL} domainId="…" navigation={navigation} actions={actions}>
|
|
47
|
+
<VoiceBotProvider url={URL} domainId="…" userId={currentUserId} navigation={navigation} actions={actions}>
|
|
48
48
|
```
|
|
49
49
|
|
|
50
50
|
Without React, or for actions added later:
|
package/docs/INTEGRATION.md
CHANGED
|
@@ -71,7 +71,7 @@ import { useExpoRouterNavigation } from 'react-native-voice-bot-sdk/expo-router'
|
|
|
71
71
|
export default function RootLayout() {
|
|
72
72
|
const navigation = useExpoRouterNavigation();
|
|
73
73
|
return (
|
|
74
|
-
<VoiceBotProvider url="wss://voice.example.com/demo" domainId="YOUR_DOMAIN_ID" navigation={navigation}>
|
|
74
|
+
<VoiceBotProvider url="wss://voice.example.com/demo" domainId="YOUR_DOMAIN_ID" userId={currentUserId} navigation={navigation}>
|
|
75
75
|
<Stack />
|
|
76
76
|
</VoiceBotProvider>
|
|
77
77
|
);
|
|
@@ -89,13 +89,19 @@ const navigation = createReactNavigationAdapter(navigationRef);
|
|
|
89
89
|
|
|
90
90
|
export default function App() {
|
|
91
91
|
return (
|
|
92
|
-
<VoiceBotProvider url="wss://voice.example.com/demo" domainId="YOUR_DOMAIN_ID" navigation={navigation}>
|
|
92
|
+
<VoiceBotProvider url="wss://voice.example.com/demo" domainId="YOUR_DOMAIN_ID" userId={currentUserId} navigation={navigation}>
|
|
93
93
|
<NavigationContainer ref={navigationRef}>{/* your navigators */}</NavigationContainer>
|
|
94
94
|
</VoiceBotProvider>
|
|
95
95
|
);
|
|
96
96
|
}
|
|
97
97
|
```
|
|
98
98
|
|
|
99
|
+
`userId` is your app's id for the signed-in user, sent to the server as `user_id`. Use whatever
|
|
100
|
+
identifies your users: an email, a phone number or your own id. The SDK sends it as is and never
|
|
101
|
+
writes it to its logs. Leave it out (or
|
|
102
|
+
pass `""`) for guests. When it changes (sign in / sign out) the provider reconnects, so the server
|
|
103
|
+
always knows who is talking.
|
|
104
|
+
|
|
99
105
|
**No navigation by voice:** leave out `navigation`. The bot still listens and answers.
|
|
100
106
|
|
|
101
107
|
### What is sent to the server
|
|
@@ -109,7 +115,7 @@ code, data or component names. Leave screens out with
|
|
|
109
115
|
Hide the widget and use the hook:
|
|
110
116
|
|
|
111
117
|
```tsx
|
|
112
|
-
<VoiceBotProvider url={URL} domainId={DOMAIN_ID} widget={false}>
|
|
118
|
+
<VoiceBotProvider url={URL} domainId={DOMAIN_ID} userId={currentUserId} widget={false}>
|
|
113
119
|
```
|
|
114
120
|
|
|
115
121
|
```tsx
|
|
@@ -129,6 +135,7 @@ function TalkButton() {
|
|
|
129
135
|
<VoiceBotProvider
|
|
130
136
|
url={URL}
|
|
131
137
|
domainId={DOMAIN_ID}
|
|
138
|
+
userId={currentUserId}
|
|
132
139
|
onConnect={({ sessionId }) => analytics.track('voice_connected', { sessionId })}
|
|
133
140
|
onError={(e) => console.warn('voice bot', e.code, e.message)}
|
|
134
141
|
onReply={(reply) => console.log('user said', reply.question, 'bot said', reply.output?.prompt)}
|
package/docs/PROTOCOL.md
CHANGED
|
@@ -11,7 +11,7 @@ Transport: one WebSocket connection per session, e.g. `ws://<host>:8091/demo`.
|
|
|
11
11
|
|
|
12
12
|
| # | Direction | Frame | Content |
|
|
13
13
|
|---|-----------|-------|---------|
|
|
14
|
-
| 1 | App → Server | TEXT, once, first | Connect `{sessionId, domain_id, cookie_id, type:"Buffer", deviceId, sampleRate:16000, screens[]}` |
|
|
14
|
+
| 1 | App → Server | TEXT, once, first | Connect `{sessionId, domain_id, user_id, cookie_id, type:"Buffer", deviceId, sampleRate:16000, screens[]}` |
|
|
15
15
|
| 3 | App → Server | TEXT, right after 1 and on every screen change | `{type:"screen_changed", sessionId, screen, backStack[]}` |
|
|
16
16
|
| 4 | App → Server | BINARY stream | 640-byte frames of PCM s16le / 16 kHz / mono, in order, no gaps |
|
|
17
17
|
| 5 | Server → App | TEXT stream | Reply `{session_id, question, output{...}, buffer}`; `buffer` = base64 PCM s16le 16 kHz mono |
|
|
@@ -30,6 +30,7 @@ names of the app's UI screens in one JSON object:
|
|
|
30
30
|
{
|
|
31
31
|
"sessionId": "c0a8f6e2-5b1d-4f0e-9d7a-2b6c1e3f4a5b",
|
|
32
32
|
"domain_id": "demo-domain",
|
|
33
|
+
"user_id": "u_10293",
|
|
33
34
|
"cookie_id": "9b2e4c1a-7f3d-4e8b-a1c6-5d0f2e9b7a34",
|
|
34
35
|
"type": "Buffer",
|
|
35
36
|
"deviceId": 1,
|
|
@@ -42,6 +43,7 @@ names of the app's UI screens in one JSON object:
|
|
|
42
43
|
|-------|---------|
|
|
43
44
|
| `sessionId` | Random UUID v4, new for every connection. |
|
|
44
45
|
| `domain_id` | The host app's domain / tenant id, from `connect({ domainId })`. `""` if not set. |
|
|
46
|
+
| `user_id` | The host app's id for the signed-in user, from `connect({ userId })`. **Any string format the app chooses:** an email, a phone number, or an internal or random id; don't assume one format. `""` for guests (no user signed in). When the user signs in or out, the app reconnects with the new value (new `sessionId`). Since 0.2.1. |
|
|
45
47
|
| `cookie_id` | Visitor id, from `connect({ cookieId })`. If the app doesn't pass one, a random UUID saved on the device: the same across app launches until the app is uninstalled or its data is cleared. |
|
|
46
48
|
| `type` | Always `"Buffer"`. |
|
|
47
49
|
| `deviceId` | Default `1`; the app may override it. |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "react-native-voice-bot-sdk",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
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",
|