@navai/voice-frontend 0.1.1 → 0.1.3

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/README.md CHANGED
@@ -1,126 +1,320 @@
1
- # @navai/voice-frontend
2
-
3
- Frontend helpers to integrate OpenAI Realtime voice without creating custom base plumbing in every app.
4
-
5
- ## What this package provides
6
-
7
- - Route resolution helpers.
8
- - Optional dynamic frontend function loader.
9
- - `useWebVoiceAgent(...)` to bootstrap voice session from React with backend + frontend tools.
10
- - `buildNavaiAgent(...)` with built-in tools:
11
- - `navigate_to`
12
- - `execute_app_function`
13
- - Optional backend function bridge:
14
- - frontend + backend functions can coexist under `execute_app_function`.
15
- - `createNavaiBackendClient(...)` to centralize calls to backend routes:
16
- - `POST /navai/realtime/client-secret`
17
- - `GET /navai/functions`
18
- - `POST /navai/functions/execute`
19
- - `resolveNavaiFrontendRuntimeConfig(...)` to read routes/functions from env.
20
-
21
- ## Install
22
-
23
- ```bash
24
- npm install @navai/voice-frontend @openai/agents zod
25
- ```
26
-
27
- Peer dependency for hooks:
28
-
29
- ```bash
30
- npm install react
31
- ```
32
-
33
- When installed from npm, this package auto-configures missing scripts in the consumer `package.json`:
34
-
35
- - `generate:module-loaders` -> `navai-generate-web-loaders`
36
- - `predev`, `prebuild`, `pretypecheck`, `prelint` -> `npm run generate:module-loaders`
37
-
38
- It only adds missing entries and never overwrites existing scripts.
39
- To disable auto-setup, set `NAVAI_SKIP_AUTO_SETUP=1` (or `NAVAI_SKIP_FRONTEND_AUTO_SETUP=1`) during install.
40
- To run setup manually later, use `npx navai-setup-voice-frontend`.
41
-
42
- ## Expected app inputs
43
-
44
- 1. Route data in `src/ai/routes.ts` (or any array compatible with `NavaiRoute[]`).
45
- 2. Optional function module loaders when you want local/frontend tools.
46
-
47
- ## Minimal usage (no bundler-specific APIs)
48
-
49
- ```ts
50
- import { buildNavaiAgent, createNavaiBackendClient } from "@navai/voice-frontend";
51
- import { NAVAI_ROUTE_ITEMS } from "./ai/routes";
52
-
53
- const backendClient = createNavaiBackendClient({
54
- apiBaseUrl: "http://localhost:3000"
55
- });
56
- const backendFunctions = await backendClient.listFunctions();
57
-
58
- const { agent } = await buildNavaiAgent({
59
- navigate: (path) => routerNavigate(path),
60
- routes: NAVAI_ROUTE_ITEMS,
61
- backendFunctions: backendFunctions.functions,
62
- executeBackendFunction: backendClient.executeFunction
63
- });
64
- ```
65
-
66
- Then use `agent` with `RealtimeSession` from `@openai/agents/realtime`.
67
-
68
- ## React hook usage
69
-
70
- ```ts
71
- import { useWebVoiceAgent } from "@navai/voice-frontend";
72
- import { NAVAI_WEB_MODULE_LOADERS } from "./ai/generated-module-loaders";
73
- import { NAVAI_ROUTE_ITEMS } from "./ai/routes";
74
-
75
- const agent = useWebVoiceAgent({
76
- navigate: (path) => routerNavigate(path),
77
- moduleLoaders: NAVAI_WEB_MODULE_LOADERS,
78
- defaultRoutes: NAVAI_ROUTE_ITEMS,
79
- env: import.meta.env as Record<string, string | undefined>
80
- });
81
- ```
82
-
83
- ## Optional dynamic frontend functions (bundler adapter)
84
-
85
- If your bundler can provide module loaders, you can add local frontend functions too.
86
-
87
- ```ts
88
- import { resolveNavaiFrontendRuntimeConfig } from "@navai/voice-frontend";
89
-
90
- // Vite adapter example (folder-scoped):
91
- const runtime = await resolveNavaiFrontendRuntimeConfig({
92
- moduleLoaders: import.meta.glob(["/src/ai/functions-modules/**/*.{ts,js}"]),
93
- defaultRoutes: NAVAI_ROUTE_ITEMS
94
- });
95
- ```
96
-
97
- Execution rule inside `execute_app_function`:
98
-
99
- - local/frontend function is attempted first.
100
- - if not found locally, backend function is attempted.
101
- - if names conflict, frontend function wins and backend one is ignored with warning.
102
-
103
- ## Runtime env keys
104
-
105
- `resolveNavaiFrontendRuntimeConfig` reads:
106
-
107
- - `NAVAI_ROUTES_FILE`
108
- - `NAVAI_FUNCTIONS_FOLDERS`
109
- - `NAVAI_REALTIME_MODEL`
110
-
111
- `createNavaiBackendClient` reads:
112
-
113
- - `NAVAI_API_URL` when you pass `env`
114
- - or `apiBaseUrl` directly (fallback `http://localhost:3000`)
115
-
116
- When `modelOverride` exists, pass it to:
117
-
118
- - backend request body: `POST /navai/realtime/client-secret`
119
- - realtime connection: `session.connect({ model })`
120
-
121
- ## `NAVAI_FUNCTIONS_FOLDERS` formats
122
-
123
- - single path: `src/ai/functions-modules`
124
- - recursive marker: `src/ai/functions-modules/...`
125
- - wildcard: `src/features/*/voice-functions`
126
- - CSV list: `src/ai/functions,src/features/account/functions`
1
+ # @navai/voice-frontend
2
+
3
+ <p>
4
+ <a href="./README.es.md"><img alt="Idioma Espanol" src="https://img.shields.io/badge/Idioma-ES-0A66C2?style=for-the-badge"></a>
5
+ <a href="./README.en.md"><img alt="Language English" src="https://img.shields.io/badge/Language-EN-1D9A6C?style=for-the-badge"></a>
6
+ </p>
7
+
8
+ Frontend package to build Navai voice agents in web applications.
9
+
10
+ It removes repeated boilerplate for:
11
+
12
+ 1. Realtime client secret requests.
13
+ 2. Route-aware navigation tools.
14
+ 3. Dynamic local function loading.
15
+ 4. Optional backend function bridging.
16
+ 5. React hook lifecycle for connect/disconnect.
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ npm install @navai/voice-frontend @openai/agents zod
22
+ npm install react
23
+ ```
24
+
25
+ ## Package Architecture
26
+
27
+ This package is intentionally split by concern:
28
+
29
+ 1. `src/backend.ts`
30
+ HTTP client for backend routes:
31
+ - `POST /navai/realtime/client-secret`
32
+ - `GET /navai/functions`
33
+ - `POST /navai/functions/execute`
34
+
35
+ 2. `src/runtime.ts`
36
+ Runtime resolver for:
37
+ - route module selection
38
+ - function module filtering by `NAVAI_FUNCTIONS_FOLDERS`
39
+ - optional model override
40
+
41
+ 3. `src/functions.ts`
42
+ Local function loader:
43
+ - imports modules from generated loaders
44
+ - converts exports into normalized callable tool definitions
45
+
46
+ 4. `src/agent.ts`
47
+ Agent builder:
48
+ - creates `RealtimeAgent`
49
+ - injects built-in tools (`navigate_to`, `execute_app_function`)
50
+ - optionally adds direct alias tools for each allowed function
51
+
52
+ 5. `src/useWebVoiceAgent.ts`
53
+ React lifecycle wrapper:
54
+ - builds runtime config
55
+ - requests client secret
56
+ - discovers backend functions
57
+ - builds agent
58
+ - opens/closes `RealtimeSession`
59
+
60
+ 6. `src/routes.ts`
61
+ Route matching helpers for natural language to path resolution.
62
+
63
+ ## End-to-End Runtime Flow
64
+
65
+ Hook-driven runtime flow (`useWebVoiceAgent`):
66
+
67
+ 1. Resolve runtime config from `moduleLoaders` + `defaultRoutes` + env/options.
68
+ 2. Create backend client with `apiBaseUrl` or `NAVAI_API_URL`.
69
+ 3. On `start()`:
70
+ - request client secret.
71
+ - fetch backend function list.
72
+ - build Navai agent with local + backend functions.
73
+ - connect `RealtimeSession`.
74
+ 4. On `stop()`:
75
+ - close session and reset state.
76
+
77
+ State machine exposed by hook:
78
+
79
+ - `idle`
80
+ - `connecting`
81
+ - `connected`
82
+ - `error`
83
+
84
+ Agent voice state exposed by the hook:
85
+
86
+ - `agentVoiceState`: `idle | speaking`
87
+ - `isAgentSpeaking`: `boolean`
88
+
89
+ `agentVoiceState` is driven by realtime events `audio_start`, `audio_stopped`, and `audio_interrupted`.
90
+
91
+ ## Public API
92
+
93
+ Main exports:
94
+
95
+ - `buildNavaiAgent(...)`
96
+ - `createNavaiBackendClient(...)`
97
+ - `resolveNavaiFrontendRuntimeConfig(...)`
98
+ - `loadNavaiFunctions(...)`
99
+ - `useWebVoiceAgent(...)`
100
+ - `resolveNavaiRoute(...)`
101
+ - `getNavaiRoutePromptLines(...)`
102
+
103
+ Useful types:
104
+
105
+ - `NavaiRoute`
106
+ - `NavaiFunctionDefinition`
107
+ - `NavaiFunctionsRegistry`
108
+ - `NavaiBackendFunctionDefinition`
109
+ - `UseWebVoiceAgentOptions`
110
+
111
+ ## Tool Model and Behavior
112
+
113
+ `buildNavaiAgent` always registers:
114
+
115
+ - `navigate_to`
116
+ - `execute_app_function`
117
+
118
+ Optional direct alias tools:
119
+
120
+ - for each allowed function name, a direct tool can be created.
121
+ - reserved names are never used as direct tools (`navigate_to`, `execute_app_function`).
122
+ - invalid tool ids are skipped (kept accessible via `execute_app_function`).
123
+
124
+ Execution precedence:
125
+
126
+ 1. Try frontend/local function first.
127
+ 2. If missing, try backend function.
128
+ 3. If both exist with same name, frontend wins and backend is ignored with warning.
129
+
130
+ ## Dynamic Function Loading Internals
131
+
132
+ `loadNavaiFunctions` supports module export shapes:
133
+
134
+ 1. Exported function.
135
+ 2. Exported class (instance methods become functions).
136
+ 3. Exported object (callable members become functions).
137
+
138
+ Name normalization rules:
139
+
140
+ - snake_case lowercase.
141
+ - invalid chars removed.
142
+ - collisions are renamed with suffixes (`_2`, `_3`, ...).
143
+
144
+ Argument mapping rules:
145
+
146
+ - `payload.args` or `payload.arguments` as direct args.
147
+ - else `payload.value` as first arg.
148
+ - else full payload as first arg.
149
+ - context appended when arity indicates one more argument.
150
+
151
+ For class methods:
152
+
153
+ - constructor args: `payload.constructorArgs`.
154
+ - method args: `payload.methodArgs`.
155
+
156
+ ## Runtime Resolution and Env Precedence
157
+
158
+ `resolveNavaiFrontendRuntimeConfig` input priority:
159
+
160
+ 1. Explicit function args.
161
+ 2. Env object keys.
162
+ 3. Package defaults.
163
+
164
+ Keys used:
165
+
166
+ - `NAVAI_ROUTES_FILE`
167
+ - `NAVAI_FUNCTIONS_FOLDERS`
168
+ - `NAVAI_REALTIME_MODEL`
169
+
170
+ Defaults:
171
+
172
+ - routes file: `src/ai/routes.ts`
173
+ - functions folder: `src/ai/functions-modules`
174
+
175
+ Path matcher formats:
176
+
177
+ - folder: `src/ai/functions-modules`
178
+ - recursive: `src/ai/functions-modules/...`
179
+ - wildcard: `src/features/*/voice-functions`
180
+ - explicit file: `src/ai/functions-modules/secret.ts`
181
+ - CSV list: `a,b,c`
182
+
183
+ Fallback behavior:
184
+
185
+ - if configured folders match no modules, warning is emitted.
186
+ - resolver falls back to default functions folder.
187
+
188
+ ## Backend Client Behavior
189
+
190
+ `createNavaiBackendClient` base URL priority:
191
+
192
+ 1. `apiBaseUrl` option.
193
+ 2. `env.NAVAI_API_URL`.
194
+ 3. fallback `http://localhost:3000`.
195
+
196
+ Methods:
197
+
198
+ - `createClientSecret(input?)`
199
+ - `listFunctions()`
200
+ - `executeFunction({ functionName, payload })`
201
+
202
+ Error handling:
203
+
204
+ - network/HTTP failures throw for create/execute.
205
+ - function listing returns warnings and empty list on failures.
206
+
207
+ ## Generated Module Loader CLI
208
+
209
+ This package ships:
210
+
211
+ - `navai-generate-web-loaders`
212
+
213
+ Default command behavior:
214
+
215
+ 1. Reads `.env` and process env.
216
+ 2. Resolves `NAVAI_FUNCTIONS_FOLDERS` and `NAVAI_ROUTES_FILE`.
217
+ 3. Selects modules only from configured function paths.
218
+ 4. Optionally includes configured route module if it differs from default route module.
219
+ 5. Writes `src/ai/generated-module-loaders.ts`.
220
+
221
+ Manual usage:
222
+
223
+ ```bash
224
+ navai-generate-web-loaders
225
+ ```
226
+
227
+ Useful flags:
228
+
229
+ - `--project-root <path>`
230
+ - `--src-root <path>`
231
+ - `--output-file <path>`
232
+ - `--env-file <path>`
233
+ - `--default-functions-folder <path>`
234
+ - `--default-routes-file <path>`
235
+ - `--type-import <module>`
236
+ - `--export-name <identifier>`
237
+
238
+ ## Auto Setup on npm Install
239
+
240
+ Postinstall script can auto-add missing scripts in consumer app:
241
+
242
+ - `generate:module-loaders` -> `navai-generate-web-loaders`
243
+ - `predev` -> `npm run generate:module-loaders`
244
+ - `prebuild` -> `npm run generate:module-loaders`
245
+ - `pretypecheck` -> `npm run generate:module-loaders`
246
+ - `prelint` -> `npm run generate:module-loaders`
247
+
248
+ Rules:
249
+
250
+ - only missing scripts are added.
251
+ - existing scripts are never overwritten.
252
+
253
+ Disable auto setup:
254
+
255
+ - `NAVAI_SKIP_AUTO_SETUP=1`
256
+ - or `NAVAI_SKIP_FRONTEND_AUTO_SETUP=1`
257
+
258
+ Manual setup runner:
259
+
260
+ ```bash
261
+ npx navai-setup-voice-frontend
262
+ ```
263
+
264
+ ## Integration Examples
265
+
266
+ Imperative integration:
267
+
268
+ ```ts
269
+ import { RealtimeSession } from "@openai/agents/realtime";
270
+ import { buildNavaiAgent, createNavaiBackendClient } from "@navai/voice-frontend";
271
+ import { NAVAI_ROUTE_ITEMS } from "./ai/routes";
272
+ import { NAVAI_WEB_MODULE_LOADERS } from "./ai/generated-module-loaders";
273
+
274
+ const backend = createNavaiBackendClient({ apiBaseUrl: "http://localhost:3000" });
275
+ const secret = await backend.createClientSecret();
276
+ const backendList = await backend.listFunctions();
277
+
278
+ const { agent, warnings } = await buildNavaiAgent({
279
+ navigate: (path) => router.navigate(path),
280
+ routes: NAVAI_ROUTE_ITEMS,
281
+ functionModuleLoaders: NAVAI_WEB_MODULE_LOADERS,
282
+ backendFunctions: backendList.functions,
283
+ executeBackendFunction: backend.executeFunction
284
+ });
285
+
286
+ warnings.forEach((w) => console.warn(w));
287
+
288
+ const session = new RealtimeSession(agent);
289
+ await session.connect({ apiKey: secret.value });
290
+ ```
291
+
292
+ React hook integration:
293
+
294
+ ```ts
295
+ import { useWebVoiceAgent } from "@navai/voice-frontend";
296
+ import { NAVAI_WEB_MODULE_LOADERS } from "./ai/generated-module-loaders";
297
+ import { NAVAI_ROUTE_ITEMS } from "./ai/routes";
298
+
299
+ const voice = useWebVoiceAgent({
300
+ navigate: (path) => router.navigate(path),
301
+ moduleLoaders: NAVAI_WEB_MODULE_LOADERS,
302
+ defaultRoutes: NAVAI_ROUTE_ITEMS,
303
+ env: import.meta.env as Record<string, string | undefined>
304
+ });
305
+ ```
306
+
307
+ ## Operational Notes
308
+
309
+ - warnings are emitted with `console.warn` from runtime, backend list, and agent builder.
310
+ - unknown function execution returns structured `ok: false` payload.
311
+ - if route module fails to load or has invalid shape, resolver falls back to default routes.
312
+
313
+ ## Related Docs
314
+
315
+ - Spanish version: `README.es.md`
316
+ - English version: `README.en.md`
317
+ - Backend package: `../voice-backend/README.md`
318
+ - Mobile package: `../voice-mobile/README.md`
319
+ - Playground Web: `../../apps/playground-web/README.md`
320
+ - Playground API: `../../apps/playground-api/README.md`
@@ -0,0 +1,6 @@
1
+ import {
2
+ Orb
3
+ } from "./chunk-KBBRQQLK.js";
4
+ export {
5
+ Orb as default
6
+ };