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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +75 -2
  2. package/README.md +81 -10
  3. package/android/src/main/java/expo/modules/voicebot/VoiceBotAudioModule.kt +47 -2
  4. package/build/NativeAudio.d.ts +4 -0
  5. package/build/NativeAudio.js +1 -1
  6. package/build/VoiceBotClient.d.ts +88 -7
  7. package/build/VoiceBotClient.js +1 -1
  8. package/build/actions/engine.d.ts +84 -0
  9. package/build/actions/engine.js +1 -0
  10. package/build/actions/registry.d.ts +28 -0
  11. package/build/actions/registry.js +1 -0
  12. package/build/actions/schema.d.ts +43 -0
  13. package/build/actions/schema.js +1 -0
  14. package/build/actions/types.d.ts +152 -0
  15. package/build/actions/types.js +1 -0
  16. package/build/expo-router.d.ts +6 -1
  17. package/build/expo-router.js +1 -1
  18. package/build/index.d.ts +10 -1
  19. package/build/index.js +1 -1
  20. package/build/logger.js +1 -1
  21. package/build/navigation/localIntent.d.ts +28 -0
  22. package/build/navigation/localIntent.js +1 -0
  23. package/build/navigation/match.d.ts +31 -0
  24. package/build/navigation/match.js +1 -0
  25. package/build/navigation/reactNavigation.js +1 -1
  26. package/build/navigation/state.d.ts +3 -0
  27. package/build/navigation/state.js +1 -1
  28. package/build/navigation/types.d.ts +7 -0
  29. package/build/protocol.d.ts +7 -0
  30. package/build/react/VoiceBotProvider.d.ts +15 -1
  31. package/build/react/VoiceBotProvider.js +1 -1
  32. package/build/react/useVoiceBot.d.ts +2 -0
  33. package/build/react/useVoiceBot.js +1 -1
  34. package/build/react/useVoiceBotAction.d.ts +15 -0
  35. package/build/react/useVoiceBotAction.js +1 -0
  36. package/docs/ACTIONS.md +207 -0
  37. package/docs/INTEGRATION.md +10 -3
  38. package/docs/PROTOCOL.md +102 -1
  39. package/ios/VoiceBotAudioModule.swift +16 -2
  40. package/package.json +5 -1
@@ -1 +1 @@
1
- import{jsx as o,jsxs as n}from"react/jsx-runtime";import{useEffect as e,useRef as r}from"react";import{StyleSheet as t,View as i}from"react-native";import{VoiceBot as s}from"../VoiceBotClient";import{VoiceBotWidget as c}from"./VoiceBotWidget";export function VoiceBotProvider({children:t,url:a,domainId:u,autoConnect:p=!0,widget:d=!0,navigation:m=null,onConnect:f,onError:C,onClose:g,onReply:y,onMessage:v,options:x,disconnectOnUnmount:M=!0}){const R=r({onConnect:f,onError:C,onClose:g,onReply:y,onMessage:v,options:x});return R.current={onConnect:f,onError:C,onClose:g,onReply:y,onMessage:v,options:x},e((()=>{s.setNavigation(m)}),[m]),e((()=>s.addMessageListener((o=>R.current.onMessage?.(o)))),[]),e((()=>{if(a&&p)return s.connect({...R.current.options,url:a,domainId:u,onSuccess:o=>R.current.onConnect?.(o),onFailure:o=>R.current.onError?.(o),onClose:o=>R.current.onClose?.(o),onReply:o=>R.current.onReply?.(o)}),()=>s.disconnect()}),[a,u,p]),e((()=>()=>{s.setNavigation(null),M&&s.disconnect()}),[M]),n(i,{style:l.fill,children:[t,d?o(c,{..."object"==typeof d?d:{}}):null]})}const l=t.create({fill:{flex:1}});
1
+ import{jsx as n,jsxs as e}from"react/jsx-runtime";import{useEffect as o,useRef as t}from"react";import{Alert as r,StyleSheet as s,View as i}from"react-native";import{VoiceBot as c}from"../VoiceBotClient";import{VoiceBotWidget as l}from"./VoiceBotWidget";export const alertConfirm=n=>new Promise((e=>{let o=!1;const t=n=>{o||(o=!0,e(n))};n.signal.addEventListener?.("abort",(()=>t("cancelled"))),r.alert(n.title,n.message||void 0,[{text:n.cancelLabel,style:"cancel",onPress:()=>t("rejected")},{text:n.confirmLabel,onPress:()=>t("approved")}],{cancelable:!0,onDismiss:()=>t("cancelled")})}));export function VoiceBotProvider({children:r,url:s,domainId:d,autoConnect:m=!0,widget:u=!0,navigation:p=null,onConnect:f,onError:C,onClose:g,onReply:v,onMessage:x,options:y,actions:b,onConfirmAction:j,disconnectOnUnmount:E=!0}){const M=t({onConnect:f,onError:C,onClose:g,onReply:v,onMessage:x,options:y});return M.current={onConnect:f,onError:C,onClose:g,onReply:v,onMessage:x,options:y},o((()=>{c.setNavigation(p)}),[p]),o((()=>c.addMessageListener((n=>M.current.onMessage?.(n)))),[]),o((()=>{if(b)return c.setActions(b),()=>c.setActions({})}),[b]),o((()=>{c.setConfirmHandler(j??alertConfirm)}),[j]),o((()=>{if(s&&m)return c.connect({...M.current.options,url:s,domainId:d,onSuccess:n=>M.current.onConnect?.(n),onFailure:n=>M.current.onError?.(n),onClose:n=>M.current.onClose?.(n),onReply:n=>M.current.onReply?.(n)}),()=>c.disconnect()}),[s,d,m]),o((()=>()=>{c.setNavigation(null),E&&c.disconnect()}),[E]),e(i,{style:a.fill,children:[r,u?n(l,{..."object"==typeof u?u:{}}):null]})}const a=s.create({fill:{flex:1}});
@@ -12,6 +12,8 @@ export interface UseVoiceBot extends VoiceBotState {
12
12
  stop: typeof VoiceBot.stop;
13
13
  toggle: typeof VoiceBot.toggle;
14
14
  addMessageListener: typeof VoiceBot.addMessageListener;
15
+ registerAction: typeof VoiceBot.registerAction;
16
+ setScreenContext: typeof VoiceBot.setScreenContext;
15
17
  }
16
18
  /** React hook for the shared voice bot session. Re-renders on every state change. */
17
19
  export declare function useVoiceBot(): UseVoiceBot;
@@ -1 +1 @@
1
- import{useSyncExternalStore as t}from"react";import{VoiceBot as e}from"../VoiceBotClient";export function useVoiceBot(){const s=t(e.subscribe,e.getState,e.getState);return{...s,isConnected:"connected"===s.status||"listening"===s.status,isListening:"listening"===s.status,isReady:"connected"===s.status||"listening"===s.status,error:s.lastError,connect:e.connect,disconnect:e.disconnect,start:e.start,stop:e.stop,toggle:e.toggle,addMessageListener:e.addMessageListener}}
1
+ import{useSyncExternalStore as t}from"react";import{VoiceBot as e}from"../VoiceBotClient";export function useVoiceBot(){const s=t(e.subscribe,e.getState,e.getState);return{...s,isConnected:"connected"===s.status||"listening"===s.status,isListening:"listening"===s.status,isReady:"connected"===s.status||"listening"===s.status,error:s.lastError,connect:e.connect,disconnect:e.disconnect,start:e.start,stop:e.stop,toggle:e.toggle,addMessageListener:e.addMessageListener,registerAction:e.registerAction,setScreenContext:e.setScreenContext}}
@@ -0,0 +1,15 @@
1
+ import type { ActionDefinition } from '../actions/types';
2
+ /**
3
+ * Registers an action while the calling component is mounted (e.g. an action that only makes
4
+ * sense on one screen). The latest `run` is always used. The server is told when it appears and
5
+ * disappears (`actions_update`).
6
+ *
7
+ * useVoiceBotAction('select_option', { description: 'Select an option on this screen',
8
+ * params: { option: 'string' }, run: ({ option }) => setOption(option) });
9
+ */
10
+ export declare function useVoiceBotAction(name: string, definition: ActionDefinition): void;
11
+ /**
12
+ * Tells the server what the user is looking at on this screen, e.g. `{ itemId: 'A12' }`, so it
13
+ * understands "add this one". Cleared when the screen changes.
14
+ */
15
+ export declare function useVoiceBotScreenContext(params: Record<string, string | number | boolean> | null | undefined): void;
@@ -0,0 +1 @@
1
+ import{useEffect as t,useRef as n}from"react";import{VoiceBot as e}from"../VoiceBotClient";export function useVoiceBotAction(o,r){const i=n(r);i.current=r;const{description:c,params:s,timeoutMs:m,confirm:u,idempotent:f}=r,p=JSON.stringify({description:c,params:s,timeoutMs:m,confirm:!!u,idempotent:f});t((()=>{const t=i.current;return e.registerAction(o,{...t,confirm:t.confirm,run:(t,n)=>i.current.run(t,n)})}),[o,p])}export function useVoiceBotScreenContext(n){const o=n?JSON.stringify(n):"";t((()=>(e.setScreenContext(n??null),()=>e.setScreenContext(null))),[o])}
@@ -0,0 +1,207 @@
1
+ # Actions: let the AI server do things in your app
2
+
3
+ Since 0.2.0 the AI server can ask your app to **perform operations**, not only open screens:
4
+ "add a medium T-shirt to my cart and go to checkout", "move my booking to Friday", "mark this task
5
+ done". The SDK is product-independent: it doesn't know about carts, bookings or tasks. **Your app
6
+ registers its own actions**; the SDK validates and runs them, and reports real results.
7
+
8
+ Actions are optional. Without them the SDK sends exactly the same messages as before.
9
+
10
+ ## Who does what
11
+
12
+ | | Responsible for |
13
+ |---|---|
14
+ | **AI server** | Speech understanding, intent, conversation context, choosing actions, filling in params, the spoken answer. |
15
+ | **SDK** | Voice and session, the action allowlist, validating params, running steps in order, timeouts, confirmation, cancellation, navigation, reporting results. |
16
+ | **Your app** | The action handlers: business logic, your APIs, your data, your UI. |
17
+
18
+ ## 1. Register actions
19
+
20
+ With the provider (the usual way):
21
+
22
+ ```tsx
23
+ import { ActionError, VoiceBotProvider, type ActionDefinition } from 'react-native-voice-bot-sdk';
24
+
25
+ const actions: Record<string, ActionDefinition> = {
26
+ add_to_cart: {
27
+ description: 'Add a product to the cart. Products with sizes need a size.',
28
+ params: {
29
+ product: { type: 'string', description: 'Product id or name' },
30
+ size: 'string?',
31
+ quantity: { type: 'integer', required: false, min: 1, max: 10 },
32
+ },
33
+ run: async ({ product, size, quantity = 1 }, { signal }) => {
34
+ const item = await api.findProduct(product, { signal }); // your API
35
+ if (!item) throw new ActionError('PRODUCT_NOT_FOUND', `There is no product called ${product}`);
36
+ await cart.add(item.id, size, quantity); // your state
37
+ return { ok: true, data: { name: item.name, size, quantity, items: cart.count() } };
38
+ },
39
+ },
40
+ place_order: {
41
+ description: 'Place the order for the items in the cart',
42
+ confirm: { title: 'Place this order?', message: () => `Total ${cart.total()}` },
43
+ run: async () => ({ ok: true, data: await api.placeOrder() }),
44
+ },
45
+ };
46
+
47
+ <VoiceBotProvider url={URL} domainId="…" navigation={navigation} actions={actions}>
48
+ ```
49
+
50
+ Without React, or for actions added later:
51
+
52
+ ```ts
53
+ const remove = VoiceBot.registerAction('mark_done', { description: 'Mark a task done', params: { taskId: 'string' }, run });
54
+ remove(); // unregister
55
+ ```
56
+
57
+ For an action that only makes sense on one screen, use the hook. It's registered while the screen
58
+ is mounted:
59
+
60
+ ```tsx
61
+ useVoiceBotAction('select_seat', { description: 'Select a seat on this flight', params: { seat: 'string' }, run: ({ seat }) => select(seat) });
62
+ ```
63
+
64
+ ### Definition
65
+
66
+ | Field | Meaning |
67
+ |-------|---------|
68
+ | `description` | Required. One sentence; the AI server uses it to choose actions. |
69
+ | `params` | Param schema (below). Params that aren't listed are **rejected**. |
70
+ | `run(params, context)` | Does the work. `context` has `requestId`, `step` and `signal` (aborted on timeout or cancel; pass it to `fetch`). |
71
+ | `timeoutMs` | Default 15000. On timeout the step fails with `TIMEOUT` and `signal` is aborted. |
72
+ | `confirm` | `true`, or `{ title, message, confirmLabel, cancelLabel }` (`message` can be a function of the params). The user must approve first. |
73
+ | `idempotent` | Tells the server that running it twice is safe (informational). |
74
+
75
+ ### Param schema
76
+
77
+ Short forms: `'string'`, `'number'`, `'integer'`, `'boolean'`, `'object'`, `'array'`, `'any'`;
78
+ add `?` for optional (`'number?'`); `'S|M|L'` is a choice (also `'S|M|L?'`). Or an object:
79
+ `{ type, required, enum, min, max, description }`. `min` / `max` are values for numbers and
80
+ lengths for strings and lists.
81
+
82
+ Numbers and booleans sent as strings (`"2"`, `"true"`) are converted; choices match without case
83
+ (`"m"` → `"M"`).
84
+
85
+ ### Handler results
86
+
87
+ | Handler does | Step result |
88
+ |--------------|-------------|
89
+ | resolves (nothing, or `{ ok: true, data }`) | `ok`, with `data` |
90
+ | returns `{ ok: false, code, message, data }` | `failed` with that code and message |
91
+ | `throw new ActionError(code, message, data)` | `failed` with that code and message |
92
+ | throws anything else | `failed`, `ACTION_FAILED`, "The operation could not be completed" (the real error stays in your app's log; it is never sent) |
93
+ | doesn't finish in `timeoutMs` | `timeout`; it may still complete in the app, so make operations safe to check or retry |
94
+
95
+ Only resolve when the operation **really happened**. The SDK never reports success on its own.
96
+ `data` must be JSON and under 16 000 characters; don't put personal data in it that the server
97
+ doesn't need.
98
+
99
+ ## 2. What the server is told
100
+
101
+ The connect message gets an `actions` list (metadata only, never handlers):
102
+
103
+ ```json
104
+ "actions": [
105
+ { "name": "add_to_cart", "description": "Add a product to the cart. …",
106
+ "params": { "product": { "type": "string", "required": true, "description": "Product id or name" },
107
+ "size": { "type": "string", "required": false },
108
+ "quantity": { "type": "integer", "required": false, "min": 1, "max": 10 } },
109
+ "confirm": false, "idempotent": false, "timeoutMs": 15000 }
110
+ ]
111
+ ```
112
+
113
+ If actions change while connected, the SDK sends `{ "type": "actions_update", "actions": [...] }`.
114
+
115
+ ## 3. How a request runs
116
+
117
+ ```
118
+ server: {"type":"actions","requestId":"req_001","steps":[
119
+ {"action":"add_to_cart","params":{"product":"t-shirt","size":"M"}},
120
+ {"navigate":"checkout"}]}
121
+ SDK: validate request → step 1: allowlist → validate params → (confirm) → run handler → wait
122
+ → step 2: navigate (normal navigation rules, checks the screen changed)
123
+ → {"type":"action_result","requestId":"req_001","status":"ok","results":[…]}
124
+ ```
125
+
126
+ - Steps run **one after another**; requests run one at a time, in order of arrival.
127
+ - A failed step stops the request; the remaining steps are reported as `skipped`. Steps with
128
+ `"optional": true` may fail without stopping it.
129
+ - `{"navigate": "screen"}` uses the same rules as `navigate` messages (`"back"` goes back).
130
+ - Exactly **one** `action_result` per request.
131
+
132
+ ### Request lifecycle and safety
133
+
134
+ | State | Meaning |
135
+ |-------|---------|
136
+ | `queued` | Received, waiting for an earlier request. |
137
+ | `running` | A step is running. |
138
+ | `completed` | Finished; the result was sent (or is waiting for the socket). |
139
+
140
+ - **Repeated requestId:** never run again. The server gets `action_status` (`queued`, `running`, or
141
+ `completed` with the earlier result).
142
+ - **Connection lost during an action:** the action is not cancelled or repeated. Its result is sent
143
+ as soon as the socket is open again (after the new connect message).
144
+ - **Cancel:** `{"type":"cancel_actions","requestId":"…"}` stops a queued request, or aborts the
145
+ running step's `signal` (and an open confirmation).
146
+ - **Acknowledgement (optional):** `{"type":"action_ack","requestId":"…"}`.
147
+ - Finished requests are remembered for 10 minutes (at most 200), then forgotten.
148
+ - The SDK can't guarantee exactly-once execution across app restarts: make handlers idempotent
149
+ where your backend allows (e.g. pass `requestId` as an idempotency key).
150
+
151
+ ## 4. Confirmation
152
+
153
+ For actions with `confirm`, the SDK asks the user **before** running, and the server can't skip it.
154
+ The provider shows a native alert by default. Your own UI:
155
+
156
+ ```tsx
157
+ <VoiceBotProvider … onConfirmAction={async (req) => {
158
+ // req: { action, title, message, params, confirmLabel, cancelLabel, signal, requestId }
159
+ return await myConfirmSheet.show(req.title, req.message); // true only on an explicit tap
160
+ }}>
161
+ ```
162
+
163
+ Results: approved → the action runs; declined → `rejected` / `CONFIRMATION_REJECTED`; dismissed,
164
+ cancelled or no answer in 60 s → `cancelled`; no confirmation UI at all →
165
+ `CONFIRMATION_UNAVAILABLE` (never runs).
166
+
167
+ **Payments:** don't make "pay" an action. Navigate to your checkout and let the customer pay there.
168
+ The SDK never collects or stores payment details.
169
+
170
+ ## 5. Screen context
171
+
172
+ `screen_changed` now carries small params about what the user is looking at, so the server can
173
+ understand "add **this** one":
174
+
175
+ ```json
176
+ { "type": "screen_changed", "screen": "product/[slug]", "backStack": ["(tabs)/index", "product/[slug]"],
177
+ "params": { "slug": "basic-tee", "product": "basic-tee", "productName": "Basic T-shirt" } }
178
+ ```
179
+
180
+ Route params are included automatically (Expo Router, React Navigation). Add your own:
181
+
182
+ ```tsx
183
+ useVoiceBotScreenContext({ product: item.id, productName: item.name }); // or VoiceBot.setScreenContext(...)
184
+ ```
185
+
186
+ Only flat strings (up to 200 characters), numbers and booleans are sent, at most 20. It's cleared
187
+ when the user moves to another screen. Don't put personal data here.
188
+
189
+ ## 6. Error codes
190
+
191
+ | Code | When |
192
+ |------|------|
193
+ | `INVALID_REQUEST` | The request itself is malformed (no steps, too many steps (> 20), a step without exactly one of `action` / `navigate`). In the result's top-level `error`. |
194
+ | `UNKNOWN_ACTION` | The app didn't register that action. |
195
+ | `INVALID_PARAMS` | Params don't match the schema; `details` lists each param. |
196
+ | `ACTION_FAILED` | The handler failed without a specific code. |
197
+ | `TIMEOUT` | The handler didn't finish in time. |
198
+ | `CONFIRMATION_REJECTED` | The user declined. |
199
+ | `CONFIRMATION_UNAVAILABLE` | The action needs confirmation and the app has no confirmation UI. |
200
+ | `CANCELLED` | Cancelled by the server, or the confirmation was dismissed or timed out. |
201
+ | `UNKNOWN_SCREEN`, `NOT_SUPPORTED`, `NAVIGATION_FAILED` | A navigate step failed. |
202
+ | *your own* | Whatever your handler throws with `ActionError` (e.g. `OUT_OF_STOCK`). |
203
+
204
+ ## 7. Try it
205
+
206
+ The example app registers demo shop actions (`example/src/lib/voiceActions.ts`, with a real cart in
207
+ `example/src/lib/store.ts`). These are only for the demo; the SDK contains none of them.
@@ -145,15 +145,22 @@ Pass any `VoiceBot.connect()` option in `options`:
145
145
  url={URL}
146
146
  options={{
147
147
  noiseGate: { thresholdDb: 8 }, // more sensitive mic (default 10)
148
- bargeIn: true, // talking over the bot stops it (default)
149
- whileSpeaking: 'guard', // ignore the bot's own voice (default)
148
+ whileSpeaking: 'mute', // mic silent while the bot speaks (default; stops echo loops)
149
+ // bargeIn: true, whileSpeaking: 'guard', // talk over the bot: only with headsets
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
  >
155
156
  ```
156
157
 
158
+ ## 7b. Actions (optional)
159
+
160
+ To let the server do things in your app (add to cart, book, update a record …), register actions
161
+ on the provider with a description, a params schema and a `run` function that uses your own code.
162
+ Mark sensitive ones with `confirm`. See [ACTIONS.md](https://unpkg.com/react-native-voice-bot-sdk/docs/ACTIONS.md).
163
+
157
164
  ## 8. Test
158
165
 
159
166
  1. Run the app on a real phone (the emulator's mic works too, but less like real use).
@@ -184,6 +191,6 @@ packages needed) that checks the connect message and the audio frames.
184
191
  | `CLEARTEXT communication … not permitted` | `ws://` URL in a release build. Use `wss://`, or `allowCleartextTraffic: true` for testing. |
185
192
  | Connects, but the bot never answers | Check the server logs for the `sessionId`. In a noisy room, the server may not detect the end of a sentence; try closer to the phone. |
186
193
  | The bot's voice sounds slow or deep | The server's audio sample rate doesn't match `sample_rate` in its replies. |
187
- | The reply stops by itself | Barge-in: someone talked loudly over it. Use `options={{ bargeIn: false }}` to turn it off. |
194
+ | The reply stops by itself, or the bot answers itself | The bot's voice came back through the mic. Keep the default `whileSpeaking: 'mute'` and `bargeIn: false`. |
188
195
  | No mic in the background | Android: allow notifications (Android 13+), and don't turn off `backgroundListening`. iOS: not supported yet. |
189
196
  | "App isn't responding" right after starting a dev build | Metro was still building the bundle. Wait or reopen the app; release builds don't do this. |
package/docs/PROTOCOL.md CHANGED
@@ -17,6 +17,9 @@ Transport: one WebSocket connection per session, e.g. `ws://<host>:8091/demo`.
17
17
  | 5 | Server → App | TEXT stream | Reply `{session_id, question, output{...}, buffer}`; `buffer` = base64 PCM s16le 16 kHz mono |
18
18
  | 6 | Server → App | TEXT, any time | `{type:"navigate", screen, params?, requestId?}` or `{type:"navigate", action:"back"}` |
19
19
  | 7 | App → Server | TEXT, answer to 6 | `{type:"navigate_result", sessionId, screen, action, className, status, message, requestId}` |
20
+ | 8 | Server → App | TEXT, any time | **0.2.0** `{type:"actions", requestId, steps[]}`: run registered actions and navigation, in order |
21
+ | 9 | App → Server | TEXT, once per request | **0.2.0** `{type:"action_result", requestId, status, results[]}` |
22
+ | 10 | Server → App | TEXT, optional | **0.2.0** `cancel_actions` / `action_ack` |
20
23
 
21
24
  ## 1. Connect message (App → Server, first TEXT frame) — **RN**
22
25
 
@@ -188,6 +191,15 @@ matching and back stack rules as `navigate` (section 6), and answers with `navig
188
191
  `requestId`). If `type` isn't `"navigation"` (and `intent` isn't `"navigate"`), the name is used only
189
192
  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
193
 
194
+ ### 5c. Local navigation in the app — **RN**
195
+
196
+ If a reply doesn't navigate (`output.type` is `"none"`, or no screen is given) and the user's
197
+ `question` is a clear request to open a screen ("open my cart", "show my orders", "go back"), the
198
+ app opens it by itself and sends `navigate_result` with **`"requestId": "local"`**, then
199
+ `screen_changed`. Requests about doing something ("add this to my cart", "search for shoes") are
200
+ left alone. Returning proper navigation from the server is still the better fix: the app's rules
201
+ are simple keyword checks.
202
+
191
203
  ## 6. Navigate (Server → App, TEXT)
192
204
 
193
205
  ```json
@@ -196,6 +208,10 @@ when it is exactly one of the app's screens. A reply split over several chunks n
196
208
  { "type": "navigate", "action": "back", "requestId": 3 }
197
209
  ```
198
210
 
211
+ - `screen` can be a name from `screens` (`(tabs)/cart`), its path (`/cart`), a short name
212
+ (`cart`), `home`, or a **concrete path for a dynamic route** (`product/blue-shoes` opens
213
+ `product/[slug]` with `slug = "blue-shoes"`). Dynamic routes need their values: either that way
214
+ or in `params`.
199
215
  - `screen` is matched in this order:
200
216
  1. an exact name from `screens` (or its URL path, e.g. `/products`);
201
217
  2. the same, case-insensitive (`Products`, `/products`);
@@ -241,7 +257,7 @@ The SDK never closes the app: `back` on the first screen returns `not_supported`
241
257
  | `already_on_screen` | The user is already on that screen. |
242
258
  | `unknown_screen` | Not in the `screens` list (`className` is `null`). |
243
259
  | `not_supported` | Nothing to go back to, or the app didn't register navigation with the SDK. |
244
- | `failed` | The navigation call threw; the reason is in `message`. |
260
+ | `failed` | The navigation call threw, or the visible screen didn't change; the reason is in `message`. |
245
261
 
246
262
  ## 8. Example session
247
263
 
@@ -269,3 +285,88 @@ app team which one you want).
269
285
 
270
286
  The app closes the socket with code `1000` and reason `"User exited"` when the host calls
271
287
  `disconnect()` or the provider unmounts.
288
+
289
+ ## 11. Actions — **0.2.0, optional**
290
+
291
+ Only apps that register actions use these messages; for other apps nothing changes. Full guide:
292
+ [ACTIONS.md](https://unpkg.com/react-native-voice-bot-sdk/docs/ACTIONS.md).
293
+
294
+ ### 11a. Advertised actions (connect message)
295
+
296
+ The connect message gets an `actions` array (left out when the app has none):
297
+
298
+ ```json
299
+ "actions": [
300
+ { "name": "add_to_cart", "description": "Add a product to the cart. Products with sizes need a size.",
301
+ "params": { "product": { "type": "string", "required": true },
302
+ "size": { "type": "string", "required": false },
303
+ "quantity": { "type": "integer", "required": false, "min": 1, "max": 10 } },
304
+ "confirm": false, "idempotent": false, "timeoutMs": 15000 }
305
+ ]
306
+ ```
307
+
308
+ `type` is one of `string`, `number`, `integer`, `boolean`, `object`, `array`, `any`; `enum` lists
309
+ allowed values. If the list changes while connected the app sends
310
+ `{ "type": "actions_update", "sessionId", "actions": [...] }` (replace the stored list).
311
+
312
+ ### 11b. Request (Server → App)
313
+
314
+ ```json
315
+ { "type": "actions", "requestId": "req_001",
316
+ "steps": [ { "action": "add_to_cart", "params": { "product": "t-shirt", "size": "M", "quantity": 1 } },
317
+ { "navigate": "checkout" } ] }
318
+ ```
319
+
320
+ - `requestId` (string or number) is required and must be unique per request; it is echoed back.
321
+ - `steps`: 1–20, each with exactly one of `action` (+ `params`) or `navigate` (a screen from
322
+ `screens`, a concrete path like `product/blue-shoes`, or `"back"`; `params` allowed). `"optional": true`
323
+ lets a step fail without stopping the request.
324
+ - Steps run in order; requests run one at a time. A failed step stops the request.
325
+ - Only advertised actions run; params are checked against the schema (unknown params are rejected).
326
+ - Actions with `"confirm": true` are only run after the user taps Confirm in the app. **Never send
327
+ payment as an action**; navigate to the checkout screen and let the user pay.
328
+
329
+ ### 11c. Result (App → Server), exactly one per request
330
+
331
+ ```json
332
+ { "type": "action_result", "sessionId": "…", "requestId": "req_001", "status": "ok",
333
+ "results": [ { "action": "add_to_cart", "status": "ok", "data": { "added": { "name": "Basic T-shirt", "size": "M" } } },
334
+ { "navigate": "checkout", "status": "opened", "screen": "checkout" } ] }
335
+ ```
336
+
337
+ ```json
338
+ { "type": "action_result", "sessionId": "…", "requestId": "req_004", "status": "failed",
339
+ "results": [ { "action": "add_to_cart", "status": "failed", "error": { "code": "OUT_OF_STOCK", "message": "Hoodie is sold out in M" } },
340
+ { "navigate": "checkout", "status": "skipped" } ] }
341
+ ```
342
+
343
+ | Field | Values |
344
+ |-------|--------|
345
+ | `status` (request) | `ok`, `failed`, `rejected` (user declined), `cancelled`, `timeout` |
346
+ | action step `status` | `ok`, `failed`, `rejected`, `cancelled`, `timeout`, `skipped` |
347
+ | navigate step `status` | `opened`, `went_back`, `already_on_screen` (success) · `unknown_screen`, `not_supported`, `failed`, `skipped`, `cancelled` |
348
+ | `error.code` | `INVALID_REQUEST`, `UNKNOWN_ACTION`, `INVALID_PARAMS` (+ `details`), `ACTION_FAILED`, `TIMEOUT`, `CONFIRMATION_REJECTED`, `CONFIRMATION_UNAVAILABLE`, `CANCELLED`, `UNKNOWN_SCREEN`, `NOT_SUPPORTED`, `NAVIGATION_FAILED`, or the app's own (e.g. `OUT_OF_STOCK`) |
349
+ | `error.message` | Safe to say to the user. Internal errors are never sent. |
350
+
351
+ A malformed request gets `status: "failed"` with a top-level `error` (`INVALID_REQUEST`). A request
352
+ without `requestId` is ignored.
353
+
354
+ Use the result for the spoken answer ("Done, the medium T-shirt is in your bag" / "Sorry, it's sold
355
+ out in M"). `TIMEOUT` means the app didn't answer in time; the operation may still complete.
356
+
357
+ ### 11d. Repeats, cancel, acknowledgement, connection loss
358
+
359
+ - **Same `requestId` again:** not run again. Answer: `{ "type": "action_status", "requestId",
360
+ "state": "queued" | "running" | "completed", "result"?: <the earlier action_result> }`.
361
+ - **Cancel:** `{ "type": "cancel_actions", "requestId": "req_008" }` → the request ends with
362
+ `status: "cancelled"` (the running step's work is aborted if the app supports it).
363
+ - **Ack (optional):** `{ "type": "action_ack", "requestId": "req_001" }` once you stored the result.
364
+ - **Connection lost while running:** the app finishes the step (it doesn't run it again) and sends
365
+ the `action_result` after the next connect message. With a new `sessionId` unless the app sets
366
+ `keepSessionOnReconnect`; the `sessionId` inside the result is the one the request arrived on.
367
+
368
+ ### 11e. Screen context
369
+
370
+ `screen_changed` may include `params`: small flat values about the visible screen (route params
371
+ and app context), e.g. `{ "slug": "basic-tee", "productName": "Basic T-shirt" }`. Use them to resolve
372
+ "this one".
@@ -28,11 +28,12 @@ public class VoiceBotAudioModule: Module {
28
28
  public func definition() -> ModuleDefinition {
29
29
  Name("VoiceBotAudio")
30
30
 
31
- Events("onAudioFrame", "onAudioError", "onAudioInterruption")
31
+ Events("onAudioFrame", "onAudioError", "onAudioInterruption", "onPlaybackIdle")
32
32
 
33
33
  Constants([
34
34
  "sampleRate": Int(Self.sampleRate),
35
35
  "frameBytes": Self.frameBytes,
36
+ "playbackIdleEvents": true,
36
37
  ])
37
38
 
38
39
  // A random id saved on the device (UserDefaults), the same across app launches.
@@ -76,6 +77,8 @@ public class VoiceBotAudioModule: Module {
76
77
  }
77
78
 
78
79
  Function("stopPlayback") {
80
+ self.playbackGeneration += 1
81
+ self.pendingBuffers = 0
79
82
  self.player.stop()
80
83
  }
81
84
 
@@ -124,6 +127,8 @@ public class VoiceBotAudioModule: Module {
124
127
 
125
128
  /** Format of the reply audio being played; reconnects the player when the rate changes. */
126
129
  private lazy var playbackFormat: AVAudioFormat = floatFormat
130
+ private var pendingBuffers = 0
131
+ private var playbackGeneration = 0
127
132
 
128
133
  private func usePlaybackRate(_ rate: Double) {
129
134
  if playbackFormat.sampleRate == rate { return }
@@ -210,7 +215,16 @@ public class VoiceBotAudioModule: Module {
210
215
  if !recording { try configureSession() }
211
216
  attachPlayerIfNeeded()
212
217
  if !engine.isRunning { try engine.start() }
213
- player.scheduleBuffer(buf, completionHandler: nil)
218
+ // Count buffers until they have really been played, then tell JS (the real end of the reply).
219
+ pendingBuffers += 1
220
+ let generation = playbackGeneration
221
+ player.scheduleBuffer(buf, completionCallbackType: .dataPlayedBack) { [weak self] _ in
222
+ DispatchQueue.main.async {
223
+ guard let self = self, generation == self.playbackGeneration else { return }
224
+ self.pendingBuffers = max(0, self.pendingBuffers - 1)
225
+ if self.pendingBuffers == 0 { self.sendEvent("onPlaybackIdle", [:]) }
226
+ }
227
+ }
214
228
  if !player.isPlaying { player.play() }
215
229
  } catch {
216
230
  sendEvent("onAudioError", ["message": "Playback failed: \(error.localizedDescription)"])
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.2.0",
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",
@@ -26,6 +26,7 @@
26
26
  "ios",
27
27
  "README.md",
28
28
  "LICENSE",
29
+ "docs/ACTIONS.md",
29
30
  "docs/PROTOCOL.md",
30
31
  "docs/INTEGRATION.md",
31
32
  "CHANGELOG.md",
@@ -39,6 +40,9 @@
39
40
  "build:release": "npm run build && node scripts/minify-build.mjs"
40
41
  },
41
42
  "keywords": [
43
+ "actions",
44
+ "agentic",
45
+ "ai-agent",
42
46
  "ai-bot",
43
47
  "assistant",
44
48
  "expo",