react-native-voice-bot-sdk 0.1.2 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +60 -2
- package/README.md +64 -13
- package/android/src/main/java/expo/modules/voicebot/VoiceBotAudioModule.kt +47 -2
- package/build/NativeAudio.d.ts +4 -0
- package/build/NativeAudio.js +1 -1
- package/build/VoiceBotClient.d.ts +78 -5
- package/build/VoiceBotClient.js +1 -1
- package/build/actions/engine.d.ts +84 -0
- package/build/actions/engine.js +1 -0
- package/build/actions/registry.d.ts +28 -0
- package/build/actions/registry.js +1 -0
- package/build/actions/schema.d.ts +43 -0
- package/build/actions/schema.js +1 -0
- package/build/actions/types.d.ts +152 -0
- package/build/actions/types.js +1 -0
- package/build/expo-router.js +1 -1
- package/build/index.d.ts +7 -1
- package/build/index.js +1 -1
- package/build/logger.js +1 -1
- package/build/navigation/match.js +1 -1
- package/build/navigation/reactNavigation.js +1 -1
- package/build/navigation/state.d.ts +3 -0
- package/build/navigation/state.js +1 -1
- package/build/navigation/types.d.ts +7 -0
- package/build/protocol.d.ts +9 -0
- package/build/react/VoiceBotProvider.d.ts +23 -3
- package/build/react/VoiceBotProvider.js +1 -1
- package/build/react/useVoiceBot.d.ts +2 -0
- package/build/react/useVoiceBot.js +1 -1
- package/build/react/useVoiceBotAction.d.ts +15 -0
- package/build/react/useVoiceBotAction.js +1 -0
- package/docs/ACTIONS.md +207 -0
- package/docs/INTEGRATION.md +19 -6
- package/docs/PROTOCOL.md +92 -2
- package/ios/VoiceBotAudioModule.swift +16 -2
- package/package.json +5 -1
package/docs/ACTIONS.md
ADDED
|
@@ -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="…" userId={currentUserId} 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.
|
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)}
|
|
@@ -145,8 +152,8 @@ Pass any `VoiceBot.connect()` option in `options`:
|
|
|
145
152
|
url={URL}
|
|
146
153
|
options={{
|
|
147
154
|
noiseGate: { thresholdDb: 8 }, // more sensitive mic (default 10)
|
|
148
|
-
|
|
149
|
-
whileSpeaking: 'guard',
|
|
155
|
+
whileSpeaking: 'mute', // mic silent while the bot speaks (default; stops echo loops)
|
|
156
|
+
// bargeIn: true, whileSpeaking: 'guard', // talk over the bot: only with headsets
|
|
150
157
|
backgroundListening: { title: 'Shop assistant', text: 'Listening…' },
|
|
151
158
|
cookieId: currentUser?.visitorId, // your own visitor id (default: saved on the device)
|
|
152
159
|
voiceShortcuts: { '(tabs)/cart': ['bag', 'basket'] }, // extra words: "open my bag" -> cart
|
|
@@ -155,6 +162,12 @@ Pass any `VoiceBot.connect()` option in `options`:
|
|
|
155
162
|
>
|
|
156
163
|
```
|
|
157
164
|
|
|
165
|
+
## 7b. Actions (optional)
|
|
166
|
+
|
|
167
|
+
To let the server do things in your app (add to cart, book, update a record …), register actions
|
|
168
|
+
on the provider with a description, a params schema and a `run` function that uses your own code.
|
|
169
|
+
Mark sensitive ones with `confirm`. See [ACTIONS.md](https://unpkg.com/react-native-voice-bot-sdk/docs/ACTIONS.md).
|
|
170
|
+
|
|
158
171
|
## 8. Test
|
|
159
172
|
|
|
160
173
|
1. Run the app on a real phone (the emulator's mic works too, but less like real use).
|
|
@@ -185,6 +198,6 @@ packages needed) that checks the connect message and the audio frames.
|
|
|
185
198
|
| `CLEARTEXT communication … not permitted` | `ws://` URL in a release build. Use `wss://`, or `allowCleartextTraffic: true` for testing. |
|
|
186
199
|
| 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. |
|
|
187
200
|
| The bot's voice sounds slow or deep | The server's audio sample rate doesn't match `sample_rate` in its replies. |
|
|
188
|
-
| The reply stops by itself |
|
|
201
|
+
| 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`. |
|
|
189
202
|
| No mic in the background | Android: allow notifications (Android 13+), and don't turn off `backgroundListening`. iOS: not supported yet. |
|
|
190
203
|
| "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
|
@@ -11,12 +11,15 @@ 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 |
|
|
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
|
|
|
@@ -27,6 +30,7 @@ names of the app's UI screens in one JSON object:
|
|
|
27
30
|
{
|
|
28
31
|
"sessionId": "c0a8f6e2-5b1d-4f0e-9d7a-2b6c1e3f4a5b",
|
|
29
32
|
"domain_id": "demo-domain",
|
|
33
|
+
"user_id": "u_10293",
|
|
30
34
|
"cookie_id": "9b2e4c1a-7f3d-4e8b-a1c6-5d0f2e9b7a34",
|
|
31
35
|
"type": "Buffer",
|
|
32
36
|
"deviceId": 1,
|
|
@@ -39,6 +43,7 @@ names of the app's UI screens in one JSON object:
|
|
|
39
43
|
|-------|---------|
|
|
40
44
|
| `sessionId` | Random UUID v4, new for every connection. |
|
|
41
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. |
|
|
42
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. |
|
|
43
48
|
| `type` | Always `"Buffer"`. |
|
|
44
49
|
| `deviceId` | Default `1`; the app may override it. |
|
|
@@ -254,7 +259,7 @@ The SDK never closes the app: `back` on the first screen returns `not_supported`
|
|
|
254
259
|
| `already_on_screen` | The user is already on that screen. |
|
|
255
260
|
| `unknown_screen` | Not in the `screens` list (`className` is `null`). |
|
|
256
261
|
| `not_supported` | Nothing to go back to, or the app didn't register navigation with the SDK. |
|
|
257
|
-
| `failed` | The navigation call threw; the reason is in `message`. |
|
|
262
|
+
| `failed` | The navigation call threw, or the visible screen didn't change; the reason is in `message`. |
|
|
258
263
|
|
|
259
264
|
## 8. Example session
|
|
260
265
|
|
|
@@ -282,3 +287,88 @@ app team which one you want).
|
|
|
282
287
|
|
|
283
288
|
The app closes the socket with code `1000` and reason `"User exited"` when the host calls
|
|
284
289
|
`disconnect()` or the provider unmounts.
|
|
290
|
+
|
|
291
|
+
## 11. Actions — **0.2.0, optional**
|
|
292
|
+
|
|
293
|
+
Only apps that register actions use these messages; for other apps nothing changes. Full guide:
|
|
294
|
+
[ACTIONS.md](https://unpkg.com/react-native-voice-bot-sdk/docs/ACTIONS.md).
|
|
295
|
+
|
|
296
|
+
### 11a. Advertised actions (connect message)
|
|
297
|
+
|
|
298
|
+
The connect message gets an `actions` array (left out when the app has none):
|
|
299
|
+
|
|
300
|
+
```json
|
|
301
|
+
"actions": [
|
|
302
|
+
{ "name": "add_to_cart", "description": "Add a product to the cart. Products with sizes need a size.",
|
|
303
|
+
"params": { "product": { "type": "string", "required": true },
|
|
304
|
+
"size": { "type": "string", "required": false },
|
|
305
|
+
"quantity": { "type": "integer", "required": false, "min": 1, "max": 10 } },
|
|
306
|
+
"confirm": false, "idempotent": false, "timeoutMs": 15000 }
|
|
307
|
+
]
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
`type` is one of `string`, `number`, `integer`, `boolean`, `object`, `array`, `any`; `enum` lists
|
|
311
|
+
allowed values. If the list changes while connected the app sends
|
|
312
|
+
`{ "type": "actions_update", "sessionId", "actions": [...] }` (replace the stored list).
|
|
313
|
+
|
|
314
|
+
### 11b. Request (Server → App)
|
|
315
|
+
|
|
316
|
+
```json
|
|
317
|
+
{ "type": "actions", "requestId": "req_001",
|
|
318
|
+
"steps": [ { "action": "add_to_cart", "params": { "product": "t-shirt", "size": "M", "quantity": 1 } },
|
|
319
|
+
{ "navigate": "checkout" } ] }
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
- `requestId` (string or number) is required and must be unique per request; it is echoed back.
|
|
323
|
+
- `steps`: 1–20, each with exactly one of `action` (+ `params`) or `navigate` (a screen from
|
|
324
|
+
`screens`, a concrete path like `product/blue-shoes`, or `"back"`; `params` allowed). `"optional": true`
|
|
325
|
+
lets a step fail without stopping the request.
|
|
326
|
+
- Steps run in order; requests run one at a time. A failed step stops the request.
|
|
327
|
+
- Only advertised actions run; params are checked against the schema (unknown params are rejected).
|
|
328
|
+
- Actions with `"confirm": true` are only run after the user taps Confirm in the app. **Never send
|
|
329
|
+
payment as an action**; navigate to the checkout screen and let the user pay.
|
|
330
|
+
|
|
331
|
+
### 11c. Result (App → Server), exactly one per request
|
|
332
|
+
|
|
333
|
+
```json
|
|
334
|
+
{ "type": "action_result", "sessionId": "…", "requestId": "req_001", "status": "ok",
|
|
335
|
+
"results": [ { "action": "add_to_cart", "status": "ok", "data": { "added": { "name": "Basic T-shirt", "size": "M" } } },
|
|
336
|
+
{ "navigate": "checkout", "status": "opened", "screen": "checkout" } ] }
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
```json
|
|
340
|
+
{ "type": "action_result", "sessionId": "…", "requestId": "req_004", "status": "failed",
|
|
341
|
+
"results": [ { "action": "add_to_cart", "status": "failed", "error": { "code": "OUT_OF_STOCK", "message": "Hoodie is sold out in M" } },
|
|
342
|
+
{ "navigate": "checkout", "status": "skipped" } ] }
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
| Field | Values |
|
|
346
|
+
|-------|--------|
|
|
347
|
+
| `status` (request) | `ok`, `failed`, `rejected` (user declined), `cancelled`, `timeout` |
|
|
348
|
+
| action step `status` | `ok`, `failed`, `rejected`, `cancelled`, `timeout`, `skipped` |
|
|
349
|
+
| navigate step `status` | `opened`, `went_back`, `already_on_screen` (success) · `unknown_screen`, `not_supported`, `failed`, `skipped`, `cancelled` |
|
|
350
|
+
| `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`) |
|
|
351
|
+
| `error.message` | Safe to say to the user. Internal errors are never sent. |
|
|
352
|
+
|
|
353
|
+
A malformed request gets `status: "failed"` with a top-level `error` (`INVALID_REQUEST`). A request
|
|
354
|
+
without `requestId` is ignored.
|
|
355
|
+
|
|
356
|
+
Use the result for the spoken answer ("Done, the medium T-shirt is in your bag" / "Sorry, it's sold
|
|
357
|
+
out in M"). `TIMEOUT` means the app didn't answer in time; the operation may still complete.
|
|
358
|
+
|
|
359
|
+
### 11d. Repeats, cancel, acknowledgement, connection loss
|
|
360
|
+
|
|
361
|
+
- **Same `requestId` again:** not run again. Answer: `{ "type": "action_status", "requestId",
|
|
362
|
+
"state": "queued" | "running" | "completed", "result"?: <the earlier action_result> }`.
|
|
363
|
+
- **Cancel:** `{ "type": "cancel_actions", "requestId": "req_008" }` → the request ends with
|
|
364
|
+
`status: "cancelled"` (the running step's work is aborted if the app supports it).
|
|
365
|
+
- **Ack (optional):** `{ "type": "action_ack", "requestId": "req_001" }` once you stored the result.
|
|
366
|
+
- **Connection lost while running:** the app finishes the step (it doesn't run it again) and sends
|
|
367
|
+
the `action_result` after the next connect message. With a new `sessionId` unless the app sets
|
|
368
|
+
`keepSessionOnReconnect`; the `sessionId` inside the result is the one the request arrived on.
|
|
369
|
+
|
|
370
|
+
### 11e. Screen context
|
|
371
|
+
|
|
372
|
+
`screen_changed` may include `params`: small flat values about the visible screen (route params
|
|
373
|
+
and app context), e.g. `{ "slug": "basic-tee", "productName": "Basic T-shirt" }`. Use them to resolve
|
|
374
|
+
"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
|
-
|
|
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
|
|
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",
|
|
@@ -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",
|