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
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Runs `actions` requests from the AI server: validates them, runs their steps one after another
3
+ * (registered actions via the host app's handlers, and navigation via the SDK's navigation), asks
4
+ * for confirmation where the app requires it, and reports one `action_result` per request.
5
+ *
6
+ * It has no UI or React Native dependencies; the client gives it a transport, a navigator and
7
+ * (optionally) a confirmation UI.
8
+ *
9
+ * Lifecycle of a request (by requestId):
10
+ * queued → running → completed (result sent, or kept until the socket is back) → forgotten after
11
+ * `retainMs`. A repeated request is never run twice while the SDK remembers it: the server gets an
12
+ * `action_status` (queued / running / completed with the earlier result) instead.
13
+ */
14
+ import { type ActionRegistry } from './registry.js';
15
+ import { type ActionResultMessage, type ActionStatusMessage, type ConfirmHandler, type NavigateStepResult } from './types.js';
16
+ export interface NavigateOutcome {
17
+ status: NavigateStepResult['status'];
18
+ screen?: string | null;
19
+ message?: string;
20
+ }
21
+ export interface EngineLog {
22
+ debug(m: string): void;
23
+ info(m: string): void;
24
+ warn(m: string): void;
25
+ error(m: string): void;
26
+ }
27
+ export interface ActionEngineDeps {
28
+ registry: ActionRegistry;
29
+ /** Opens a screen ("back" goes back) using the SDK's navigation, without sending navigate_result. */
30
+ navigate(target: string, params?: Record<string, unknown>): Promise<NavigateOutcome>;
31
+ /** The host's confirmation UI, if any. */
32
+ getConfirmHandler(): ConfirmHandler | undefined;
33
+ /** Sends a message; returns false when it couldn't be sent (no open socket). */
34
+ send(message: ActionResultMessage | ActionStatusMessage): boolean;
35
+ sessionId(): string;
36
+ log?: EngineLog;
37
+ /** How long a user has to answer a confirmation. Default 60 s. */
38
+ confirmTimeoutMs?: number;
39
+ /** How long finished requests are remembered (for repeats and unsent results). Default 10 min. */
40
+ retainMs?: number;
41
+ /** At most this many requests are remembered. Default 200. */
42
+ maxRetained?: number;
43
+ /** At most this many steps per request. Default 20. */
44
+ maxSteps?: number;
45
+ }
46
+ type EntryState = 'queued' | 'running' | 'completed';
47
+ export declare class ActionEngine {
48
+ private readonly deps;
49
+ private entries;
50
+ private queue;
51
+ private running;
52
+ private readonly log;
53
+ constructor(deps: ActionEngineDeps);
54
+ /** Handles an incoming `actions` message. Never throws. */
55
+ handle(message: unknown): void;
56
+ /** `cancel_actions`: stops a queued or running request. Returns false if it isn't active. */
57
+ cancel(requestId: string | number): boolean;
58
+ /** Cancels requests that haven't started (e.g. the user disconnected). Running steps finish. */
59
+ cancelQueued(reason: string): void;
60
+ /** `action_ack`: the server got the result. */
61
+ ack(requestId: string | number): void;
62
+ /** Sends results that couldn't be sent before (call when the socket is open again). */
63
+ flush(): number;
64
+ /** Where a request is in its lifecycle (for the host app and tests). */
65
+ state(requestId: string | number): {
66
+ state: EntryState | 'unknown';
67
+ delivered: boolean;
68
+ acknowledged: boolean;
69
+ };
70
+ /** True while a request is queued or running. */
71
+ get busy(): boolean;
72
+ private checkSteps;
73
+ private pump;
74
+ private run;
75
+ private runNavigate;
76
+ private runAction;
77
+ private askConfirmation;
78
+ private skipped;
79
+ private finish;
80
+ private sendStatus;
81
+ /** Forgets old finished requests, so memory stays small. Unsent results are kept until `retainMs`. */
82
+ private prune;
83
+ }
84
+ export {};
@@ -0,0 +1 @@
1
+ import{DEFAULT_ACTION_TIMEOUT_MS as e}from"./registry.js";import{validateParams as t}from"./schema.js";import{ActionError as s}from"./types.js";const n="The operation could not be completed",i=new Set(["opened","went_back","already_on_screen"]),a={debug(){},info(){},warn(){},error(){}};function o(){if("undefined"!=typeof AbortController){const e=new AbortController;return{signal:e.signal,abort:()=>e.abort()}}const e=[],t={aborted:!1,addEventListener:(t,s)=>e.push(s)};return{signal:t,abort:()=>{t.aborted||(t.aborted=!0,e.forEach((e=>e())))}}}function r(e,t,s){if(void 0!==e)try{const n=JSON.stringify(e);if(void 0===n)return;return n.length>16e3?(t.warn(`action ${s}: result data is ${n.length} characters; not sent (limit 16000)`),{truncated:!0}):JSON.parse(n)}catch{return void t.warn(`action ${s}: result data isn't JSON; not sent`)}}const c=(e,t=300)=>e.length>t?`${e.slice(0,t)}…`:e;export class ActionEngine{constructor(e){this.deps=e,this.entries=new Map,this.queue=[],this.running=!1,this.log=e.log??a}handle(e){this.prune();const t=e??{},s=t.requestId;if("string"!=typeof s&&"number"!=typeof s||""===String(s))return void this.log.warn("← actions request ignored: it has no requestId");const n=String(s),i=this.entries.get(n);if(i)return this.log.warn(`← actions ${n}: repeated request; not run again (${i.state})`),void this.sendStatus(i);const a={key:n,requestId:s,sessionId:this.deps.sessionId(),steps:[],state:"queued",at:Date.now(),delivered:!1,acknowledged:!1,cancelled:!1};this.entries.set(n,a);const o=this.checkSteps(t.steps);o?this.finish(a,"failed",[],{code:"INVALID_REQUEST",message:o}):(a.steps=t.steps,this.log.info(`← actions ${n}: ${a.steps.map((e=>e.navigate?`navigate ${e.navigate}`:e.action)).join(" → ")}`),this.queue.push(a),this.running&&this.log.info(`actions ${n}: queued behind the request that is running`),this.pump())}cancel(e){const t=this.entries.get(String(e));return!(!t||"completed"===t.state||(t.cancelled=!0,this.log.info(`actions ${t.key}: cancelled by the server`),"queued"===t.state?(this.queue=this.queue.filter((e=>e!==t)),this.finish(t,"cancelled",t.steps.map((e=>this.skipped(e,"cancelled"))),{code:"CANCELLED",message:"Cancelled before it started"})):t.abort?.(),0))}cancelQueued(e){const t=this.queue;this.queue=[];for(const s of t)s.cancelled=!0,this.finish(s,"cancelled",s.steps.map((e=>this.skipped(e,"cancelled"))),{code:"CANCELLED",message:e})}ack(e){const t=this.entries.get(String(e));t&&(t.acknowledged=!0,t.delivered=!0)}flush(){this.prune();let e=0;for(const t of this.entries.values())"completed"===t.state&&t.result&&!t.delivered&&this.deps.send(t.result)&&(t.delivered=!0,e++,this.log.info(`→ action_result ${t.key}: sent after reconnecting (${t.result.status})`));return e}state(e){const t=this.entries.get(String(e));return t?{state:t.state,delivered:t.delivered,acknowledged:t.acknowledged}:{state:"unknown",delivered:!1,acknowledged:!1}}get busy(){return this.running||this.queue.length>0}checkSteps(e){const t=this.deps.maxSteps??20;if(!Array.isArray(e)||0===e.length)return"steps must be a non-empty list";if(e.length>t)return`too many steps (${e.length}, at most ${t})`;for(let t=0;t<e.length;t++){const s=e[t];if(!s||"object"!=typeof s)return`step ${t+1} must be an object`;if(("string"==typeof s.action&&""!==s.action)==("string"==typeof s.navigate&&""!==s.navigate))return`step ${t+1} needs exactly one of "action" or "navigate"`}return null}async pump(){if(!this.running){this.running=!0;try{for(;this.queue.length;){const e=this.queue.shift();e.cancelled||await this.run(e)}}finally{this.running=!1}}}async run(e){e.state="running";const t=[];let s="ok";for(let n=0;n<e.steps.length;n++){const a=e.steps[n];if(e.cancelled){t.push(this.skipped(a,"cancelled")),s="cancelled";continue}if("ok"!==s){t.push(this.skipped(a,"skipped"));continue}const o=a.navigate?await this.runNavigate(e,a):await this.runAction(e,a,n);t.push(o);const r="navigate"in o?i.has(o.status):"ok"===o.status;r||a.optional?r||this.log.info(`actions ${e.key}: optional step ${n+1} failed; continuing`):s="timeout"===o.status||"rejected"===o.status||"cancelled"===o.status?o.status:"failed"}e.cancelled&&"ok"===s&&(s="cancelled"),this.finish(e,s,t)}async runNavigate(e,t){const s=t.navigate;try{const e=await this.deps.navigate(s,t.params),n={navigate:s,status:e.status,screen:e.screen??null};return i.has(e.status)||(n.error={code:"unknown_screen"===e.status?"UNKNOWN_SCREEN":"not_supported"===e.status?"NOT_SUPPORTED":"NAVIGATION_FAILED",message:c(e.message||`Couldn't open ${s}`)}),n}catch(t){return this.log.warn(`actions ${e.key}: navigate ${s} threw: ${t?.message??t}`),{navigate:s,status:"failed",error:{code:"NAVIGATION_FAILED",message:`Couldn't open ${s}`}}}}async runAction(i,a,l){const d=a.action,u=this.deps.registry.get(d);if(!u)return this.log.warn(`actions ${i.key}: unknown action "${d}"`),{action:d,status:"failed",error:{code:"UNKNOWN_ACTION",message:`The app has no action "${d}"`}};const h=t(u.params,a.params);if(!h.ok){const e=h.errors.map((e=>`${e.param||"params"}: ${e.message}`)).join("; ");return this.log.warn(`actions ${i.key}: ${d} invalid params (${e})`),{action:d,status:"failed",error:{code:"INVALID_PARAMS",message:c(`Invalid params: ${e}`),details:h.errors}}}const g=u.definition,p=h.params;if(g.confirm){const e=await this.askConfirmation(i,d,g,p);if("approved"!==e){const t="rejected"===e?"CONFIRMATION_REJECTED":"unavailable"===e?"CONFIRMATION_UNAVAILABLE":"CANCELLED",s="rejected"===e?"rejected":"unavailable"===e?"failed":"cancelled",n="rejected"===e?"The user declined":"unavailable"===e?"This action needs the user to confirm, but the app has no confirmation UI":"The confirmation was cancelled";return this.log.info(`actions ${i.key}: ${d} not run (${t})`),{action:d,status:s,error:{code:t,message:n}}}this.log.info(`actions ${i.key}: ${d} approved by the user`)}const f=g.timeoutMs??e,m=o();let $;i.abort=m.abort;const v=Date.now();this.log.info(`actions ${i.key}: running ${d} ${JSON.stringify(p)}`);try{const e=await new Promise((e=>{$=setTimeout((()=>{m.abort(),e({kind:"timeout"})}),f),m.signal.addEventListener?.("abort",(()=>{i.cancelled&&e({kind:"cancelled"})})),Promise.resolve().then((()=>g.run(p,{requestId:String(i.requestId),step:l,signal:m.signal}))).then((t=>e({kind:"done",value:t})),(t=>e({kind:"error",error:t})))})),t=Date.now()-v;if("timeout"===e.kind)return this.log.warn(`actions ${i.key}: ${d} timed out after ${f} ms`),{action:d,status:"timeout",error:{code:"TIMEOUT",message:`The app didn't finish within ${Math.round(f/1e3)} s; it may still complete`}};if("cancelled"===e.kind)return{action:d,status:"cancelled",error:{code:"CANCELLED",message:"Cancelled while running"}};if("error"===e.kind){const t=e.error;return t instanceof s||"ActionError"===t?.name?(this.log.warn(`actions ${i.key}: ${d} failed: ${t.code} ${t.message}`),{action:d,status:"failed",error:{code:String(t.code||"ACTION_FAILED"),message:c(String(t.message||n))},data:r(t.data,this.log,d)}):(this.log.error(`actions ${i.key}: ${d} threw: ${t?.message??String(t)}`),{action:d,status:"failed",error:{code:"ACTION_FAILED",message:n}})}const a=e.value;if(a&&"object"==typeof a&&!1===a.ok)return this.log.warn(`actions ${i.key}: ${d} returned a failure: ${a.code??"ACTION_FAILED"} ${a.message??""}`),{action:d,status:"failed",error:{code:String(a.code||"ACTION_FAILED"),message:c(String(a.message||n))},data:r(a.data,this.log,d)};const o=a&&"object"==typeof a&&!0===a.ok?a.data:void 0;this.log.info(`actions ${i.key}: ${d} ok in ${t} ms`);const u={action:d,status:"ok"},h=r(o,this.log,d);return void 0!==h&&(u.data=h),u}finally{$&&clearTimeout($),i.abort=void 0}}async askConfirmation(e,t,s,n){const i=this.deps.getConfirmHandler();if(!i)return"unavailable";const a="object"==typeof s.confirm?s.confirm:{};let r="";try{r="function"==typeof a.message?a.message(n):a.message??""}catch{r=""}const c=o();e.abort=c.abort;const l=this.deps.confirmTimeoutMs??6e4;let d;this.log.info(`actions ${e.key}: asking the user to confirm ${t}`);try{const o=await new Promise((o=>{d=setTimeout((()=>{c.abort(),o("cancelled")}),l),c.signal.addEventListener?.("abort",(()=>o("cancelled"))),Promise.resolve().then((()=>i({requestId:String(e.requestId),action:t,description:s.description,params:n,title:a.title??s.description,message:r,confirmLabel:a.confirmLabel??"Confirm",cancelLabel:a.cancelLabel??"Cancel",signal:c.signal}))).then((e=>o(!0===e||"approved"===e?"approved":"cancelled"===e?"cancelled":"rejected")),(()=>o("cancelled")))}));return c.signal.aborted&&"approved"===o?"cancelled":o}finally{d&&clearTimeout(d),e.abort=void 0}}skipped(e,t){return e.navigate?{navigate:e.navigate,status:t}:{action:e.action??"",status:t}}finish(e,t,s,n){e.state="completed",e.at=Date.now();const i={type:"action_result",sessionId:e.sessionId,requestId:e.requestId,status:t,results:s};n&&(i.error=n),e.result=i,e.delivered=this.deps.send(i);const a=`→ action_result ${e.key}: ${t} (${s.map((e=>("navigate"in e?`navigate ${e.navigate}`:e.action)+" "+e.status)).join(", ")||n?.code})`;"ok"===t?this.log.info(a):this.log.warn(a),e.delivered||this.log.warn(`action_result ${e.key}: socket not open; it will be sent after reconnecting`)}sendStatus(e){const t={type:"action_status",sessionId:this.deps.sessionId(),requestId:e.requestId,state:e.state};"completed"===e.state&&e.result&&(t.result=e.result),this.deps.send(t)}prune(){const e=this.deps.retainMs??6e5,t=this.deps.maxRetained??200,s=Date.now();for(const[t,n]of this.entries)"completed"===n.state&&s-n.at>e&&this.entries.delete(t);if(this.entries.size>t){const e=[...this.entries.values()].filter((e=>"completed"===e.state)).sort(((e,t)=>e.at-t.at));for(const s of e.slice(0,this.entries.size-t))this.entries.delete(s.key)}}}
@@ -0,0 +1,28 @@
1
+ import { type ParamSpec } from './schema.js';
2
+ import type { ActionDefinition, ActionMetadata } from './types.js';
3
+ export declare const DEFAULT_ACTION_TIMEOUT_MS = 15000;
4
+ export interface RegisteredAction {
5
+ name: string;
6
+ definition: ActionDefinition;
7
+ params: Record<string, ParamSpec>;
8
+ }
9
+ /**
10
+ * The actions the host app allows the AI server to run (the allowlist). The SDK runs nothing
11
+ * that isn't registered here.
12
+ */
13
+ export declare class ActionRegistry {
14
+ private actions;
15
+ private listeners;
16
+ /** Registers (or replaces) an action. Returns a function that removes it again. */
17
+ register(name: string, definition: ActionDefinition): () => void;
18
+ unregister(name: string): void;
19
+ /** Replaces all actions with `actions` (used by the React provider). */
20
+ replaceAll(actions: Record<string, ActionDefinition>): void;
21
+ get(name: string): RegisteredAction | undefined;
22
+ get size(): number;
23
+ /** What the server is told: names, descriptions, params. Never the handlers. */
24
+ metadata(): ActionMetadata[];
25
+ /** Called whenever the set of actions changes. */
26
+ onChange(listener: () => void): () => void;
27
+ private changed;
28
+ }
@@ -0,0 +1 @@
1
+ import{normalizeSchema as t}from"./schema.js";export const DEFAULT_ACTION_TIMEOUT_MS=15e3;const e=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;export class ActionRegistry{constructor(){this.actions=new Map,this.listeners=new Set}register(i,n){if(!e.test(i))throw new Error(`Invalid action name "${i}" (letters, digits, _ . -; up to 64)`);if(!n||"function"!=typeof n.run)throw new Error(`Action "${i}" needs a run() function`);if("string"!=typeof n.description||!n.description.trim())throw new Error(`Action "${i}" needs a description (the AI server uses it to choose actions)`);const s=t(n.params,`action "${i}" params`),r={name:i,definition:n,params:s};return this.actions.set(i,r),this.changed(),()=>{this.actions.get(i)===r&&(this.actions.delete(i),this.changed())}}unregister(t){this.actions.delete(t)&&this.changed()}replaceAll(i){const n=new Map;for(const[s,r]of Object.entries(i)){if(!e.test(s))throw new Error(`Invalid action name "${s}"`);if("function"!=typeof r?.run)throw new Error(`Action "${s}" needs a run() function`);if("string"!=typeof r.description||!r.description.trim())throw new Error(`Action "${s}" needs a description`);n.set(s,{name:s,definition:r,params:t(r.params,`action "${s}" params`)})}this.actions=n,this.changed()}get(t){return this.actions.get(t)}get size(){return this.actions.size}metadata(){return[...this.actions.values()].map((({name:t,definition:e,params:i})=>({name:t,description:e.description.trim(),params:i,confirm:!!e.confirm,idempotent:!!e.idempotent,timeoutMs:e.timeoutMs??15e3}))).sort(((t,e)=>t.name.localeCompare(e.name)))}onChange(t){return this.listeners.add(t),()=>{this.listeners.delete(t)}}changed(){this.listeners.forEach((t=>t()))}}
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Parameter schemas for registered actions, and validation of the params the server sends.
3
+ *
4
+ * A param can be written in short form or as an object:
5
+ * { query: 'string', quantity: 'integer?', size: 'S|M|L|XL', confirmed: 'boolean' }
6
+ * { quantity: { type: 'integer', min: 1, max: 99, description: 'How many' } }
7
+ *
8
+ * Short forms: `string`, `number`, `integer`, `boolean`, `object`, `array`, `any`; add `?` for
9
+ * optional (`number?`); `A|B|C` is a choice of strings (also with `?`).
10
+ */
11
+ export type ParamType = 'string' | 'number' | 'integer' | 'boolean' | 'object' | 'array' | 'any';
12
+ export interface ParamSpec {
13
+ type: ParamType;
14
+ /** Default `true`. */
15
+ required?: boolean;
16
+ /** Allowed values. */
17
+ enum?: (string | number)[];
18
+ /** Numbers: smallest / largest value. Strings and arrays: shortest / longest length. */
19
+ min?: number;
20
+ max?: number;
21
+ /** Shown to the AI server so it knows what to send. */
22
+ description?: string;
23
+ }
24
+ export type ParamsSchema = Record<string, string | ParamSpec>;
25
+ /** Turns short forms into full specs. Throws on an invalid schema (a mistake in the app's code). */
26
+ export declare function normalizeSchema(schema: ParamsSchema | undefined, where?: string): Record<string, ParamSpec>;
27
+ export interface ParamError {
28
+ param: string;
29
+ message: string;
30
+ }
31
+ export type ValidationResult = {
32
+ ok: true;
33
+ params: Record<string, unknown>;
34
+ } | {
35
+ ok: false;
36
+ errors: ParamError[];
37
+ };
38
+ /**
39
+ * Checks the server's params against the schema. Numbers and booleans sent as strings
40
+ * ("2", "true") are converted; unknown params are rejected, so the server can't pass data the app
41
+ * didn't ask for.
42
+ */
43
+ export declare function validateParams(schema: Record<string, ParamSpec>, input: unknown): ValidationResult;
@@ -0,0 +1 @@
1
+ const e=["string","number","integer","boolean","object","array","any"],a=/^[A-Za-z_][A-Za-z0-9_]{0,63}$/;export function normalizeSchema(r,s="params"){const t={};for(const[n,m]of Object.entries(r??{})){if(!a.test(n))throw new Error(`${s}: invalid param name "${n}"`);let r;if("string"==typeof m){const a=m.endsWith("?"),t=a?m.slice(0,-1).trim():m.trim();if(e.includes(t))r={type:t,required:!a};else{if(!t.includes("|"))throw new Error(`${s}.${n}: unknown type "${m}"`);r={type:"string",enum:t.split("|").map((e=>e.trim())).filter(Boolean),required:!a}}}else{if(!m||"object"!=typeof m||!e.includes(m.type))throw new Error(`${s}.${n}: a param needs a type (${e.join(", ")})`);r={...m,required:!1!==m.required}}t[n]=r}return t}export function validateParams(e,a){if(void 0!==a&&(null===a||"object"!=typeof a||Array.isArray(a)))return{ok:!1,errors:[{param:"",message:"params must be an object"}]};const r=a??{},s=[],t={};for(const a of Object.keys(r))a in e||s.push({param:a,message:"unknown param"});for(const[a,n]of Object.entries(e)){let e=r[a];if(null!=e&&""!==e){switch(n.type){case"string":if("number"!=typeof e&&"boolean"!=typeof e||(e=String(e)),"string"!=typeof e){s.push({param:a,message:"must be a string"});continue}void 0!==n.min&&e.length<n.min&&s.push({param:a,message:`must be at least ${n.min} characters`}),void 0!==n.max&&e.length>n.max&&s.push({param:a,message:`must be at most ${n.max} characters`});break;case"number":case"integer":{const r="string"==typeof e&&""!==e.trim()?Number(e):e;if("number"!=typeof r||!Number.isFinite(r)){s.push({param:a,message:"integer"===n.type?"must be a whole number":"must be a number"});continue}if("integer"===n.type&&!Number.isInteger(r)){s.push({param:a,message:"must be a whole number"});continue}void 0!==n.min&&r<n.min&&s.push({param:a,message:`must be ${n.min} or more`}),void 0!==n.max&&r>n.max&&s.push({param:a,message:`must be ${n.max} or less`}),e=r;break}case"boolean":if("true"===e?e=!0:"false"===e&&(e=!1),"boolean"!=typeof e){s.push({param:a,message:"must be true or false"});continue}break;case"object":if("object"!=typeof e||Array.isArray(e)){s.push({param:a,message:"must be an object"});continue}break;case"array":if(!Array.isArray(e)){s.push({param:a,message:"must be a list"});continue}void 0!==n.min&&e.length<n.min&&s.push({param:a,message:`must have at least ${n.min} items`}),void 0!==n.max&&e.length>n.max&&s.push({param:a,message:`must have at most ${n.max} items`})}!n.enum||n.enum.some((a=>String(a).toLowerCase()===String(e).toLowerCase()))?(n.enum&&(e=n.enum.find((a=>String(a).toLowerCase()===String(e).toLowerCase()))),t[a]=e):s.push({param:a,message:`must be one of ${n.enum.join(", ")}`})}else!1!==n.required&&s.push({param:a,message:"required"})}return s.length?{ok:!1,errors:s}:{ok:!0,params:t}}
@@ -0,0 +1,152 @@
1
+ import type { ParamsSchema, ParamSpec } from './schema.js';
2
+ /** Minimal AbortSignal shape (React Native and Node both provide AbortController). */
3
+ export interface ActionSignal {
4
+ readonly aborted: boolean;
5
+ addEventListener?(type: 'abort', listener: () => void): void;
6
+ }
7
+ /** What a handler receives besides its params. */
8
+ export interface ActionContext {
9
+ /** The server's requestId for the whole request. */
10
+ requestId: string;
11
+ /** 0-based position of this step in the request. */
12
+ step: number;
13
+ /** Aborted when the step times out or the server cancels the request. Pass it to fetch(). */
14
+ signal: ActionSignal;
15
+ }
16
+ /**
17
+ * What a handler returns. Resolving (with nothing, or `{ ok: true }`) means the operation really
18
+ * happened. Return `{ ok: false }` or throw to report a failure.
19
+ */
20
+ export type ActionHandlerResult = void | undefined | {
21
+ ok: true;
22
+ data?: unknown;
23
+ message?: string;
24
+ } | {
25
+ ok: false;
26
+ code?: string;
27
+ message?: string;
28
+ data?: unknown;
29
+ };
30
+ export interface ConfirmOptions {
31
+ /** Dialog title. Default: the action's description. */
32
+ title?: string;
33
+ /** Dialog text. A function gets the validated params, e.g. `(p) => \`Pay ${p.amount}?\``. */
34
+ message?: string | ((params: Record<string, unknown>) => string);
35
+ /** Button labels. Defaults "Confirm" / "Cancel". */
36
+ confirmLabel?: string;
37
+ cancelLabel?: string;
38
+ }
39
+ /** An action the host app lets the AI server run. The SDK never contains business actions. */
40
+ export interface ActionDefinition<P extends Record<string, any> = Record<string, any>> {
41
+ /** What it does, in a sentence. Sent to the server so its AI knows when to use it. */
42
+ description: string;
43
+ /** Parameters. See `ParamsSchema`. Params not listed here are rejected. */
44
+ params?: ParamsSchema;
45
+ /** Does the work, using the app's own APIs and state. */
46
+ run(params: P, context: ActionContext): ActionHandlerResult | Promise<ActionHandlerResult>;
47
+ /** Milliseconds before the step fails with `TIMEOUT` (the signal is aborted). Default 15000. */
48
+ timeoutMs?: number;
49
+ /**
50
+ * Ask the user before running. The server can't skip this. `true` uses the default text;
51
+ * an object sets the dialog text.
52
+ */
53
+ confirm?: boolean | ConfirmOptions;
54
+ /** Tell the server that running it twice is safe (informational). Default false. */
55
+ idempotent?: boolean;
56
+ }
57
+ /** Sent to the server in the connect message: metadata only, never the handler. */
58
+ export interface ActionMetadata {
59
+ name: string;
60
+ description: string;
61
+ params: Record<string, ParamSpec>;
62
+ confirm: boolean;
63
+ idempotent: boolean;
64
+ timeoutMs: number;
65
+ }
66
+ /** What the confirmation UI is given. */
67
+ export interface ConfirmRequest {
68
+ requestId: string;
69
+ action: string;
70
+ description: string;
71
+ params: Record<string, unknown>;
72
+ title: string;
73
+ message: string;
74
+ confirmLabel: string;
75
+ cancelLabel: string;
76
+ /** Aborted if the server cancels the request or the confirmation times out. */
77
+ signal: ActionSignal;
78
+ }
79
+ /** The host's confirmation UI. Resolve `true` / 'approved' only after an explicit user approval. */
80
+ export type ConfirmHandler = (request: ConfirmRequest) => Promise<boolean | 'approved' | 'rejected' | 'cancelled'>;
81
+ export type ActionErrorCode = 'INVALID_REQUEST' | 'UNKNOWN_ACTION' | 'INVALID_PARAMS' | 'ACTION_FAILED' | 'TIMEOUT' | 'CONFIRMATION_REJECTED' | 'CONFIRMATION_UNAVAILABLE' | 'CANCELLED' | 'NAVIGATION_FAILED' | 'UNKNOWN_SCREEN' | 'NOT_SUPPORTED' | 'NOT_CONNECTED' | (string & {});
82
+ /**
83
+ * Throw this from a handler to send the server a specific, safe error:
84
+ * throw new ActionError('OUT_OF_STOCK', 'Size M is sold out');
85
+ * Any other thrown error is reported as ACTION_FAILED with a generic message (the details stay in
86
+ * the app's logs).
87
+ */
88
+ export declare class ActionError extends Error {
89
+ readonly code: string;
90
+ readonly data?: unknown;
91
+ constructor(code: string, message: string, data?: unknown);
92
+ }
93
+ export interface StepError {
94
+ code: ActionErrorCode;
95
+ message: string;
96
+ /** For INVALID_PARAMS: which params and why. */
97
+ details?: {
98
+ param: string;
99
+ message: string;
100
+ }[];
101
+ }
102
+ export type StepStatus = 'ok' | 'failed' | 'rejected' | 'cancelled' | 'timeout' | 'skipped';
103
+ export interface ActionStepResult {
104
+ action: string;
105
+ status: StepStatus;
106
+ data?: unknown;
107
+ error?: StepError;
108
+ }
109
+ export interface NavigateStepResult {
110
+ navigate: string;
111
+ /** `opened`, `went_back`, `already_on_screen` count as success; the rest as failure. */
112
+ status: 'opened' | 'went_back' | 'already_on_screen' | 'unknown_screen' | 'not_supported' | 'failed' | 'skipped' | 'cancelled';
113
+ screen?: string | null;
114
+ error?: StepError;
115
+ }
116
+ export type StepResult = ActionStepResult | NavigateStepResult;
117
+ export type RequestStatus = 'ok' | 'failed' | 'rejected' | 'cancelled' | 'timeout';
118
+ /** App → server, once per request. */
119
+ export interface ActionResultMessage {
120
+ type: 'action_result';
121
+ sessionId: string;
122
+ requestId: string;
123
+ status: RequestStatus;
124
+ results: StepResult[];
125
+ /** Only for problems with the request itself (e.g. INVALID_REQUEST); step errors are in `results`. */
126
+ error?: StepError;
127
+ }
128
+ /** App → server: answer to a repeated request, or to `action_status` questions. Not a final result. */
129
+ export interface ActionStatusMessage {
130
+ type: 'action_status';
131
+ sessionId: string;
132
+ requestId: string;
133
+ state: 'queued' | 'running' | 'completed' | 'unknown';
134
+ /** For `completed`: the final result that was already sent. */
135
+ result?: ActionResultMessage;
136
+ }
137
+ /** Server → app. */
138
+ export interface ActionStepRequest {
139
+ /** Action name, or … */
140
+ action?: string;
141
+ params?: Record<string, unknown>;
142
+ /** … a screen to open (`"back"` goes back). Uses the normal navigation rules. */
143
+ navigate?: string;
144
+ /** If true, a failure of this step doesn't stop the request. Default false. */
145
+ optional?: boolean;
146
+ }
147
+ export interface ActionsRequestMessage {
148
+ type: 'actions';
149
+ requestId: string;
150
+ steps: ActionStepRequest[];
151
+ }
152
+ export type { ParamSpec, ParamsSchema };
@@ -0,0 +1 @@
1
+ export class ActionError extends Error{constructor(r,t,o){super(t),this.name="ActionError",this.code=r,this.data=o}}
@@ -1,6 +1,6 @@
1
1
  import { type SitemapType } from 'expo-router';
2
2
  import type { ScreenInfo } from './protocol';
3
- import type { NavigationAdapter } from './navigation/types';
3
+ import type { NavigationAdapter, NavParams } from './navigation/types';
4
4
  export interface ExpoRouterNavigationOptions {
5
5
  /** Route names to leave out (e.g. `['modal', 'settings/debug']`). */
6
6
  exclude?: string[];
@@ -11,6 +11,11 @@ export declare function routeNameFromContextKey(key: string): string;
11
11
  export declare function routePathFromName(name: string): string;
12
12
  /** Collects the screen routes (no layouts, no internal or generated routes) from the sitemap. */
13
13
  export declare function screensFromSitemap(root: SitemapType | null, exclude?: string[]): ScreenInfo[];
14
+ /**
15
+ * Turns a route name + params into an href Expo Router accepts. Uses the URL path (`/cart`,
16
+ * `/product/[slug]`); keeps the group (`/(tabs)/cart`) only when two screens share a path.
17
+ */
18
+ export declare function hrefFor(screen: ScreenInfo, screens: ScreenInfo[], params?: NavParams): any;
14
19
  /** Hook that returns a navigation adapter for Expo Router. Call it in your root `_layout.tsx`. */
15
20
  export declare function useExpoRouterNavigation(options?: ExpoRouterNavigationOptions): NavigationAdapter;
16
21
  export type { NavigationAdapter } from './navigation/types';
@@ -1 +1 @@
1
- import{useMemo as e}from"react";import{router as t,useNavigationContainerRef as r,useSitemap as o}from"expo-router";import{flattenBackStack as n}from"./navigation/state";const a=/(^|\/)_layout$/;export function routeNameFromContextKey(e){return e.replace(/^\.\//,"").replace(/(\.(ios|android|web|native))?\.[jt]sx?$/,"")}export function routePathFromName(e){return"/"+e.split("/").filter((e=>e&&"index"!==e&&!/^\(.*\)$/.test(e))).join("/")}export function screensFromSitemap(e,t=[]){const r=new Map,o=new Set(t),n=e=>{const t=routeNameFromContextKey(e.contextKey),s=t.split("/").pop()??"";!!(a.test(t)||e.isInternal||e.isGenerated||s.startsWith("+")||s.startsWith("_"))||o.has(t)||r.has(t)||r.set(t,{name:t,path:routePathFromName(t)}),e.children.forEach(n)};return e&&n(e),[...r.values()].sort(((e,t)=>e.name.localeCompare(t.name)))}function s(e,t){const r="/"+e.name.split("/").filter((e=>"index"!==e)).join("/");return t&&Object.keys(t).length?{pathname:r,params:t}:r}export function useExpoRouterNavigation(a={}){const i=r(),c=o(),u=(a.exclude??[]).join("|");return e((()=>{const e=screensFromSitemap(c,a.exclude),r=()=>{return n(i?.isReady()?(e=i.getRootState())&&1===e.routes?.length&&"__root"===e.routes[0].name?e.routes[0].state:e:void 0,!0);var e};return{kind:"expo-router",getScreens:()=>e,getCurrentScreen:()=>{const e=r();return e.length?e[e.length-1]:null},getBackStack:r,push:(e,r)=>t.push(s(e,r)),popTo:(e,r)=>t.dismissTo(s(e,r)),goBack:()=>!!t.canGoBack()&&(t.back(),!0),subscribe:e=>i.addListener("state",(()=>e()))}}),[i,c,u])}
1
+ import{useMemo as e}from"react";import{router as t,useNavigationContainerRef as r,useSitemap as n}from"expo-router";import{topGroup as o}from"./navigation/match";import{flattenBackStack as a,focusedParams as s}from"./navigation/state";const i=/(^|\/)_layout$/;export function routeNameFromContextKey(e){return e.replace(/^\.\//,"").replace(/(\.(ios|android|web|native))?\.[jt]sx?$/,"")}export function routePathFromName(e){return"/"+e.split("/").filter((e=>e&&"index"!==e&&!/^\(.*\)$/.test(e))).join("/")}export function screensFromSitemap(e,t=[]){const r=new Map,n=new Set(t),o=e=>{const t=routeNameFromContextKey(e.contextKey),a=t.split("/").pop()??"";!!(i.test(t)||e.isInternal||e.isGenerated||a.startsWith("+")||a.startsWith("_"))||n.has(t)||r.has(t)||r.set(t,{name:t,path:routePathFromName(t)}),e.children.forEach(o)};return e&&o(e),[...r.values()].sort(((e,t)=>e.name.localeCompare(t.name)))}export function hrefFor(e,t,r){const n=routePathFromName(e.name),o=t.some((t=>t.name!==e.name&&routePathFromName(t.name)===n))?"/"+e.name.split("/").filter((e=>"index"!==e)).join("/"):n;return r&&Object.keys(r).length?{pathname:o,params:r}:o}export function useExpoRouterNavigation(i={}){const m=r(),u=n(),c=(i.exclude??[]).join("|");return e((()=>{const e=screensFromSitemap(u,i.exclude),r=screensFromSitemap(u),n=()=>m?.isReady()?function(e){return e&&1===e.routes?.length&&"__root"===e.routes[0].name?e.routes[0].state:e}(m.getRootState()):void 0,c=()=>a(n(),!0);return{kind:"expo-router",getScreens:()=>e,getCurrentScreen:()=>{const e=c();return e.length?e[e.length-1]:null},getBackStack:c,getCurrentParams:()=>s(n()),push:(e,n)=>{const a=c(),s=a.length?a[a.length-1]:null,i=o(e.name);i&&o(s)===i?t.navigate(hrefFor(e,r,n)):t.push(hrefFor(e,r,n))},popTo:(e,n)=>{const a=c(),s=a.length?a[a.length-1]:null,i=o(e.name);i&&o(s)===i?t.navigate(hrefFor(e,r,n)):t.dismissTo(hrefFor(e,r,n))},navigate:(e,n)=>t.navigate(hrefFor(e,r,n)),goBack:()=>!!t.canGoBack()&&(t.back(),!0),subscribe:e=>m.addListener("state",(()=>e()))}}),[m,u,c])}
package/build/index.d.ts CHANGED
@@ -1,17 +1,26 @@
1
1
  export { VoiceBot, VoiceBotClient } from './VoiceBotClient';
2
2
  export type { ConnectOptions, VoiceBotError, VoiceBotState, VoiceBotStatus } from './VoiceBotClient';
3
- export { VoiceBotProvider } from './react/VoiceBotProvider';
3
+ export { VoiceBotProvider, alertConfirm } from './react/VoiceBotProvider';
4
4
  export type { VoiceBotProviderProps } from './react/VoiceBotProvider';
5
5
  export { VoiceBotWidget } from './react/VoiceBotWidget';
6
6
  export type { VoiceBotWidgetProps } from './react/VoiceBotWidget';
7
7
  export { useVoiceBot } from './react/useVoiceBot';
8
8
  export type { UseVoiceBot } from './react/useVoiceBot';
9
+ export { useVoiceBotAction, useVoiceBotScreenContext } from './react/useVoiceBotAction';
10
+ export { ActionError } from './actions/types';
11
+ export type { ActionDefinition, ActionContext, ActionHandlerResult, ActionMetadata, ActionErrorCode, ActionResultMessage, ActionStatusMessage, ActionsRequestMessage, ActionStepRequest, ActionStepResult, NavigateStepResult, StepResult, StepError, StepStatus, RequestStatus, ConfirmHandler, ConfirmRequest, ConfirmOptions, ActionSignal, } from './actions/types';
12
+ export type { ParamSpec, ParamsSchema, ParamType } from './actions/schema';
13
+ export { ActionRegistry } from './actions/registry';
14
+ export { ActionEngine } from './actions/engine';
9
15
  export type { NavigationAdapter, NavParams } from './navigation/types';
10
16
  export { createReactNavigationAdapter } from './navigation/reactNavigation';
11
17
  export type { NavigationRefLike, ReactNavigationAdapterOptions } from './navigation/reactNavigation';
12
18
  export { createCallbackNavigation } from './navigation/callbackNavigation';
13
19
  export type { CallbackNavigationAdapter, CallbackNavigationOptions } from './navigation/callbackNavigation';
14
20
  export { flattenBackStack } from './navigation/state';
21
+ export { matchScreen } from './navigation/match';
22
+ export { findLocalIntent } from './navigation/localIntent';
23
+ export type { VoiceShortcuts, LocalIntent } from './navigation/localIntent';
15
24
  export { isNativeAvailable } from './NativeAudio';
16
25
  export { NoiseGate, frameLevelDb } from './audio/noiseGate';
17
26
  export type { NoiseGateOptions, WhileSpeaking } from './audio/noiseGate';
package/build/index.js CHANGED
@@ -1 +1 @@
1
- export{VoiceBot,VoiceBotClient}from"./VoiceBotClient";export{VoiceBotProvider}from"./react/VoiceBotProvider";export{VoiceBotWidget}from"./react/VoiceBotWidget";export{useVoiceBot}from"./react/useVoiceBot";export{createReactNavigationAdapter}from"./navigation/reactNavigation";export{createCallbackNavigation}from"./navigation/callbackNavigation";export{flattenBackStack}from"./navigation/state";export{isNativeAvailable}from"./NativeAudio";export{NoiseGate,frameLevelDb}from"./audio/noiseGate";export{setLogLevel,getLogLevel,setLogHandler}from"./logger";export*from"./protocol";
1
+ export{VoiceBot,VoiceBotClient}from"./VoiceBotClient";export{VoiceBotProvider,alertConfirm}from"./react/VoiceBotProvider";export{VoiceBotWidget}from"./react/VoiceBotWidget";export{useVoiceBot}from"./react/useVoiceBot";export{useVoiceBotAction,useVoiceBotScreenContext}from"./react/useVoiceBotAction";export{ActionError}from"./actions/types";export{ActionRegistry}from"./actions/registry";export{ActionEngine}from"./actions/engine";export{createReactNavigationAdapter}from"./navigation/reactNavigation";export{createCallbackNavigation}from"./navigation/callbackNavigation";export{flattenBackStack}from"./navigation/state";export{matchScreen}from"./navigation/match";export{findLocalIntent}from"./navigation/localIntent";export{isNativeAvailable}from"./NativeAudio";export{NoiseGate,frameLevelDb}from"./audio/noiseGate";export{setLogLevel,getLogLevel,setLogHandler}from"./logger";export*from"./protocol";
package/build/logger.js CHANGED
@@ -1 +1 @@
1
- const e={trace:-1,debug:0,info:1,warn:2,error:3,none:4};let t="undefined"==typeof __DEV__||__DEV__?"debug":"warn",r=null;export function setLogLevel(e){t=e}export function getLogLevel(){return t}export function setLogHandler(e){r=e}function n(n,o,i){if(e[n]<e[t])return;if(r){try{r(n,o,i)}catch{}return}const c=`[VoiceBot] ${function(){const e=new Date,t=(e,t=2)=>String(e).padStart(t,"0");return`${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}.${t(e.getMilliseconds(),3)}`}()} ${n.toUpperCase().padEnd(5)} ${o}`,s="error"===n?console.error:"warn"===n?console.warn:console.log;void 0===i?s(c):s(c,i)}export const logger={trace:(e,t)=>n("trace",e,t),debug:(e,t)=>n("debug",e,t),info:(e,t)=>n("info",e,t),warn:(e,t)=>n("warn",e,t),error:(e,t)=>n("error",e,t),isEnabled:r=>e[r]>=e[t]};export function preview(e,t=1/0){let r;try{if(r="string"==typeof e?e:JSON.stringify(e,((e,t)=>"string"==typeof t&&t.length>80&&("buffer"===e||"data"===e)?`<base64 ${t.length} chars = ${Math.floor(3*t.length/4)-(t.endsWith("==")?2:t.endsWith("=")?1:0)} bytes>`:t)),"string"==typeof e&&(r.includes('"buffer"')||r.includes('"data"')))try{r=preview(JSON.parse(r),t)}catch{}}catch{r=String(e)}return r.length>t?`${r.slice(0,t)}… (${r.length} chars)`:r}
1
+ const e={trace:-1,debug:0,info:1,warn:2,error:3,none:4};let t="undefined"==typeof __DEV__||__DEV__?"debug":"warn",n=null;export function setLogLevel(e){t=e}export function getLogLevel(){return t}export function setLogHandler(e){n=e}function r(r,o,i){if(e[r]<e[t])return;if(n){try{n(r,o,i)}catch{}return}const c=`[VoiceBot] ${function(){const e=new Date,t=(e,t=2)=>String(e).padStart(t,"0");return`${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}.${t(e.getMilliseconds(),3)}`}()} ${r.toUpperCase().padEnd(5)} ${o}`,s=console.log;void 0===i?s(c):s(c,i)}export const logger={trace:(e,t)=>r("trace",e,t),debug:(e,t)=>r("debug",e,t),info:(e,t)=>r("info",e,t),warn:(e,t)=>r("warn",e,t),error:(e,t)=>r("error",e,t),isEnabled:n=>e[n]>=e[t]};export function preview(e,t=1/0){let n;try{if(n="string"==typeof e?e:JSON.stringify(e,((e,t)=>"string"==typeof t&&t.length>80&&("buffer"===e||"data"===e)?`<base64 ${t.length} chars = ${Math.floor(3*t.length/4)-(t.endsWith("==")?2:t.endsWith("=")?1:0)} bytes>`:t)),"string"==typeof e&&(n.includes('"buffer"')||n.includes('"data"')))try{n=preview(JSON.parse(n),t)}catch{}}catch{n=String(e)}return n.length>t?`${n.slice(0,t)}… (${n.length} chars)`:n}
@@ -0,0 +1,28 @@
1
+ import type { ScreenInfo } from '../protocol';
2
+ /**
3
+ * Local voice navigation: used only when the server's reply doesn't navigate.
4
+ *
5
+ * It looks at what the user said (the reply's `question`) and opens a screen when the sentence is
6
+ * clearly a request to open one: an "open"-style word ("open", "show", "go to", "take me to" …)
7
+ * followed by a word that names a screen. The words come from the app's route names
8
+ * (`(tabs)/cart` → "cart", `orders/index` → "orders" / "order", `account/addresses` →
9
+ * "addresses" / "address", `(tabs)/index` → "home"), plus any `voiceShortcuts` the app adds.
10
+ *
11
+ * Sentences about doing something with a thing ("add this to my cart", "remove from my wishlist",
12
+ * "search for shoes", "buy", "pay") never navigate.
13
+ */
14
+ export type VoiceShortcuts = Record<string, string[]>;
15
+ export type LocalIntent = {
16
+ action: 'back';
17
+ } | {
18
+ action: 'open';
19
+ screen: string;
20
+ keyword: string;
21
+ };
22
+ /** Words that name a screen, from its route name: `account/addresses` → `addresses`, `address`. */
23
+ export declare function screenKeywords(name: string): string[];
24
+ /**
25
+ * Finds a clear "open screen" request in `said`. Returns null when the sentence isn't one, when no
26
+ * screen word is found, or when two screens match equally well.
27
+ */
28
+ export declare function findLocalIntent(said: string, screens: ScreenInfo[], shortcuts?: VoiceShortcuts): LocalIntent | null;
@@ -0,0 +1 @@
1
+ const e=["open","show","show me","go to","goto","go into","take me to","bring me to","navigate to","switch to","move to","jump to","view","see","display","launch","visit","check","check my","bring up","pull up","load","i want to see","i want to go to","let me see","go","take me"],t=["add","remove","delete","clear","empty","buy","purchase","pay","cancel","return","track","search for","find","look for","save","put","move this","update","change","edit"],o=/^(please\s+)?(go\s+back|back|go\s+to\s+the\s+previous\s+(page|screen)|previous\s+(page|screen))(\s+please)?$/,s=e=>` ${e.toLowerCase().replace(/[^a-z0-9\s'-]/g," ").replace(/\s+/g," ").trim()} `,n=(e,t)=>e.includes(` ${t} `);export function screenKeywords(e){const t=e.split("/").filter((e=>e&&!/^\(.*\)$/.test(e)));if(t.some((e=>/^\[.*\]$/.test(e))))return[];const o=t.filter((e=>"index"!==e));if(!o.length)return["home","home page","home screen","main page","start"];const s=o[o.length-1].replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[-_]+/g," ").toLowerCase(),n=new Set([s]);return s.endsWith("ies")?n.add(s.slice(0,-3)+"y"):s.endsWith("sses")?n.add(s.slice(0,-2)):s.endsWith("s")&&!s.endsWith("ss")?n.add(s.slice(0,-1)):n.add(s+"s"),[...n]}export function findLocalIntent(r,c,a={}){const i=s(r),l=i.trim();if(!l)return null;if(o.test(l))return{action:"back"};if(t.some((e=>n(i,e))))return null;if(!e.some((e=>n(i,e))))return null;const u=new Set(c.map((e=>e.name))),d=[];for(const[e,t]of Object.entries(a))if(u.has(e))for(const o of t)d.push({screen:e,keyword:s(o).trim(),custom:!0});for(const e of c)for(const t of screenKeywords(e.name))d.push({screen:e.name,keyword:t,custom:!1});const m=d.filter((e=>e.keyword&&n(i,e.keyword)));if(!m.length)return null;m.sort(((e,t)=>Number(t.custom)-Number(e.custom)||t.keyword.length-e.keyword.length));const p=m[0];return m.filter((e=>e.screen!==p.screen&&e.custom===p.custom&&e.keyword.length===p.keyword.length)).length?null:{action:"open",screen:p.screen,keyword:p.keyword}}
@@ -0,0 +1,31 @@
1
+ import type { ScreenInfo } from '../protocol';
2
+ import type { NavParams } from './types';
3
+ /** `(tabs)/cart` → `(tabs)`; `account/profile` → null. The navigator group a route lives in. */
4
+ export declare function topGroup(name: string | null | undefined): string | null;
5
+ /** Param names of a dynamic route: `orders/[orderNumber]` → `['orderNumber']`. */
6
+ export declare function dynamicParams(name: string): string[];
7
+ export interface ScreenMatch {
8
+ screen: ScreenInfo;
9
+ /** Params taken from a concrete path, e.g. `product/blue-shoes` → `{ slug: 'blue-shoes' }`. */
10
+ params?: NavParams;
11
+ }
12
+ /**
13
+ * Finds the screen the server asked for. Tried in order:
14
+ * 1. exact route name or path (`(tabs)/cart`, `/cart`);
15
+ * 2. the same, ignoring case and leading/trailing slashes (`Cart`, `cart/`);
16
+ * 3. `home` or `/` → the screen whose path is `/`;
17
+ * 4. a concrete path of a dynamic route (`product/blue-shoes` → `product/[slug]` with `slug`);
18
+ * 5. the last part of the name, if exactly one screen has it (`profile` → `account/profile`,
19
+ * `orders` → `orders/index`); a trailing `Screen` is ignored (`ProfileScreen`).
20
+ */
21
+ export declare function matchScreen(screens: ScreenInfo[], query: string): ScreenMatch | null;
22
+ export type NavMove = 'already_on_screen' | 'push' | 'popTo';
23
+ /**
24
+ * How to reach `target` from the current back stack, like a user would:
25
+ * - already visible (and no new params) → nothing;
26
+ * - in the back stack → pop back to it;
27
+ * - in a group (e.g. `(tabs)`) that is lower in the stack while the user is on a pushed screen
28
+ * above it → pop back to that group and switch to the screen;
29
+ * - otherwise → push it (switching tabs inside the same group counts as a push).
30
+ */
31
+ export declare function decideMove(target: string, current: string | null, stack: string[], hasParams: boolean): NavMove;
@@ -0,0 +1 @@
1
+ const e=e=>/^\(.*\)$/.test(e),t=/^\[(?:\.\.\.)?([^\]]+)\]$/;export function topGroup(t){const n=(t??"").split("/")[0];return e(n)?n:null}export function dynamicParams(e){return e.split("/").map((e=>t.exec(e)?.[1])).filter((e=>!!e))}function n(t){return t.split("/").filter((t=>t&&"index"!==t&&!e(t)))}export function matchScreen(o,c){const s=c.trim();if(!s)return null;const i=o.find((e=>e.name===s||e.path===s));if(i)return{screen:i};const u=s.replace(/^\/+|\/+$/g,""),p=u.toLowerCase(),a=o.filter((e=>e.name.toLowerCase()===p||(e.path??"").replace(/^\/+|\/+$/g,"").toLowerCase()===p));if(1===a.length)return{screen:a[0]};if(""===p||"home"===p){const e=o.filter((e=>"/"===e.path||0===n(e.name).length));if(1===e.length)return{screen:e[0]}}const l=u.split("/").filter((t=>t&&!e(t)));for(const e of o){if(!dynamicParams(e.name).length)continue;const o=n(e.name);if(o.length!==l.length)continue;const c={};if(o.every(((e,n)=>{const o=t.exec(e);return o?(c[o[1]]=r(l[n]),!0):e.toLowerCase()===l[n].toLowerCase()})))return{screen:e,params:c}}const f=p.replace(/screen$/,""),m=o.filter((e=>{const r=n(e.name),o=(r[r.length-1]??"index").toLowerCase();return!t.test(o)&&(o===p||o.replace(/screen$/,"")===f)}));return 1===m.length?{screen:m[0]}:null}function r(e){try{return decodeURIComponent(e)}catch{return e}}export function decideMove(e,t,n,r){if(t===e&&!r)return"already_on_screen";const o=topGroup(e);if(o&&topGroup(t)===o)return"push";if(n.includes(e)&&t!==e&&!r)return"popTo";const c=topGroup(e);return c&&topGroup(t)!==c&&n.some((e=>topGroup(e)===c))?"popTo":"push"}
@@ -1 +1 @@
1
- import{flattenBackStack as e,focusedLeaf as t}from"./state";export function createReactNavigationAdapter(a,s={}){const n=new Map;for(const e of s.screens??[])"string"!=typeof e&&e.parents&&n.set(e.name,e.parents);const r=(e,t,a)=>{if(e){for(const s of e.routeNames??e.routes.map((e=>e.name)))a.has(s)||a.set(s,t);for(const s of e.routes)s.state&&Array.isArray(s.state.routes)&&r(s.state,[...t,s.name],a)}},o=()=>a.isReady()?a.getRootState():void 0;return{kind:"react-navigation",getScreens(){const e=new Set(s.exclude??[]);let t;if(s.screens)t=s.screens.map((e=>"string"==typeof e?e:e.name));else{const e=new Map;r(o(),[],e),e.forEach(((e,t)=>{n.has(t)||n.set(t,e)}));const a=new Set;e.forEach((e=>e.forEach((e=>a.add(e))))),t=[...e.keys()].filter((e=>!a.has(e)))}return[...new Set(t)].filter((t=>!e.has(t))).sort().map((e=>({name:e})))},getCurrentScreen:()=>t(o(),!1),getBackStack:()=>e(o(),!1),push(e,t){const s=n.get(e.name)??[];if(0===s.length)return void a.navigate(e.name,t);let r={screen:e.name,params:t};for(let e=s.length-1;e>0;e--)r={screen:s[e],params:r};a.navigate(s[0],r)},popTo(e,t){a.dispatch({type:"POP_TO",payload:{name:e.name,params:t}})},goBack:()=>!(!a.isReady()||!a.canGoBack()||(a.goBack(),0)),subscribe:e=>a.addListener("state",(()=>e()))}}
1
+ import{flattenBackStack as e,focusedLeaf as t,focusedParams as a}from"./state";export function createReactNavigationAdapter(s,n={}){const r=new Map;for(const e of n.screens??[])"string"!=typeof e&&e.parents&&r.set(e.name,e.parents);const o=(e,t,a)=>{if(e){for(const s of e.routeNames??e.routes.map((e=>e.name)))a.has(s)||a.set(s,t);for(const s of e.routes)s.state&&Array.isArray(s.state.routes)&&o(s.state,[...t,s.name],a)}},c=()=>s.isReady()?s.getRootState():void 0;return{kind:"react-navigation",getScreens(){const e=new Set(n.exclude??[]);let t;if(n.screens)t=n.screens.map((e=>"string"==typeof e?e:e.name));else{const e=new Map;o(c(),[],e),e.forEach(((e,t)=>{r.has(t)||r.set(t,e)}));const a=new Set;e.forEach((e=>e.forEach((e=>a.add(e))))),t=[...e.keys()].filter((e=>!a.has(e)))}return[...new Set(t)].filter((t=>!e.has(t))).sort().map((e=>({name:e})))},getCurrentScreen:()=>t(c(),!1),getBackStack:()=>e(c(),!1),getCurrentParams:()=>a(c()),push(e,t){const a=r.get(e.name)??[];if(0===a.length)return void s.navigate(e.name,t);let n={screen:e.name,params:t};for(let e=a.length-1;e>0;e--)n={screen:a[e],params:n};s.navigate(a[0],n)},popTo(e,t){s.dispatch({type:"POP_TO",payload:{name:e.name,params:t}})},goBack:()=>!(!s.isReady()||!s.canGoBack()||(s.goBack(),0)),subscribe:e=>s.addListener("state",(()=>e()))}}
@@ -4,6 +4,7 @@ export interface NavStateLike {
4
4
  index?: number;
5
5
  routes: {
6
6
  name: string;
7
+ params?: Record<string, unknown>;
7
8
  state?: NavStateLike | Partial<NavStateLike>;
8
9
  }[];
9
10
  routeNames?: string[];
@@ -18,3 +19,5 @@ export interface NavStateLike {
18
19
  export declare function flattenBackStack(state: NavStateLike | undefined, nestedNames: boolean, prefix?: string): string[];
19
20
  /** Name of the focused leaf screen. */
20
21
  export declare function focusedLeaf(state: NavStateLike | undefined, nestedNames: boolean): string | null;
22
+ /** Params of the focused leaf route (follows the focused route down through nested navigators). */
23
+ export declare function focusedParams(state: NavStateLike | undefined): Record<string, unknown> | undefined;
@@ -1 +1 @@
1
- const t=(t,e,n)=>n&&t?`${t}/${e}`:e;export function flattenBackStack(e,n,r=""){if(!e||!Array.isArray(e.routes)||0===e.routes.length)return[];const a=Math.min(e.index??e.routes.length-1,e.routes.length-1),s=[];for(let o="stack"===e.type||null==e.type?0:a;o<=a;o++){const a=e.routes[o],u=t(r,a.name,n),c=a.state;c&&Array.isArray(c.routes)&&c.routes.length>0?s.push(...flattenBackStack(c,n,u)):s.push(u)}return s}export function focusedLeaf(t,e){const n=flattenBackStack(t,e);return n.length?n[n.length-1]:null}
1
+ const t=(t,e,r)=>r&&t?`${t}/${e}`:e;export function flattenBackStack(e,r,n=""){if(!e||!Array.isArray(e.routes)||0===e.routes.length)return[];const s=Math.min(e.index??e.routes.length-1,e.routes.length-1),o=[];for(let a="stack"===e.type||null==e.type?0:s;a<=s;a++){const s=e.routes[a],u=t(n,s.name,r),l=s.state;l&&Array.isArray(l.routes)&&l.routes.length>0?o.push(...flattenBackStack(l,r,u)):o.push(u)}return o}export function focusedLeaf(t,e){const r=flattenBackStack(t,e);return r.length?r[r.length-1]:null}export function focusedParams(t){let e,r=t;for(let t=0;r&&Array.isArray(r.routes)&&r.routes.length&&t<20;t++){const t=Math.min(r.index??r.routes.length-1,r.routes.length-1),n=r.routes[t];e=n.params,r=n.state}return e}
@@ -20,8 +20,15 @@ export interface NavigationAdapter {
20
20
  push(screen: ScreenInfo, params?: NavParams): void | Promise<void>;
21
21
  /** Go back to a screen that is already in the back stack (remove the screens above it). */
22
22
  popTo(screen: ScreenInfo, params?: NavParams): void | Promise<void>;
23
+ /**
24
+ * Optional: open a screen the way a link does (switch tab, or go to an existing screen). Used
25
+ * as a fallback when `push` / `popTo` didn't change the visible screen.
26
+ */
27
+ navigate?(screen: ScreenInfo, params?: NavParams): void | Promise<void>;
23
28
  /** Like the system Back button. Resolves false when there is nothing to go back to. */
24
29
  goBack(): boolean | Promise<boolean>;
30
+ /** Optional: params of the visible screen (e.g. `{ slug: 'blue-shoes' }`), sent in `screen_changed`. */
31
+ getCurrentParams?(): Record<string, unknown> | undefined;
25
32
  /** Calls `listener` whenever the visible screen or back stack may have changed. */
26
33
  subscribe(listener: () => void): () => void;
27
34
  }
@@ -23,6 +23,11 @@ export interface ConnectMessage {
23
23
  sampleRate: number;
24
24
  /** Route names; use one of these as `screen` in a `navigate` command. Names only, never code or data. */
25
25
  screens: string[];
26
+ /**
27
+ * Actions the app lets the server run (only when the app registered some). Metadata only:
28
+ * name, description, params, confirm, idempotent, timeoutMs.
29
+ */
30
+ actions?: import('./actions/types').ActionMetadata[];
26
31
  }
27
32
  /** @deprecated Old name of {@link ConnectMessage}. */
28
33
  export type MetadataMessage = ConnectMessage;
@@ -105,4 +110,6 @@ export interface ScreenChangedMessage {
105
110
  screen: string;
106
111
  /** Bottom → top; the last item is the visible screen. */
107
112
  backStack: string[];
113
+ /** Small context for the visible screen (route params and what the app adds), when there is any. */
114
+ params?: Record<string, string | number | boolean>;
108
115
  }
@@ -1,4 +1,5 @@
1
1
  import React, { type ReactNode } from 'react';
2
+ import type { ActionDefinition, ConfirmHandler } from '../actions/types';
2
3
  import type { NavigationAdapter } from '../navigation/types';
3
4
  import type { BotReply } from '../protocol';
4
5
  import { type ConnectOptions, type VoiceBotError } from '../VoiceBotClient';
@@ -39,9 +40,22 @@ export interface VoiceBotProviderProps {
39
40
  onMessage?(message: Record<string, unknown>): void;
40
41
  /** Advanced options, the same as `VoiceBot.connect()` (noise gate, barge-in, reconnect, logs ...). */
41
42
  options?: Omit<ConnectOptions, 'url' | 'domainId' | 'onSuccess' | 'onFailure' | 'onClose' | 'onReply'>;
43
+ /**
44
+ * Actions of your app the AI server may run, by name. Each has a description, a params schema
45
+ * and a `run` function that uses your app's own APIs. See docs/ACTIONS.md. Optional: without it
46
+ * the SDK works exactly as before.
47
+ */
48
+ actions?: Record<string, ActionDefinition>;
49
+ /**
50
+ * Your confirmation UI for actions marked `confirm`. Default: a native alert with the action's
51
+ * title and message. Resolve `true` only after the user explicitly approves.
52
+ */
53
+ onConfirmAction?: ConfirmHandler;
42
54
  /** Disconnect when the provider unmounts. Default `true`. */
43
55
  disconnectOnUnmount?: boolean;
44
56
  }
57
+ /** Default confirmation: a native alert. */
58
+ export declare const alertConfirm: ConfirmHandler;
45
59
  /**
46
60
  * Wrap your app once. With `url` it connects to your voice server and shows the floating mic:
47
61
  *
@@ -49,4 +63,4 @@ export interface VoiceBotProviderProps {
49
63
  * <App />
50
64
  * </VoiceBotProvider>
51
65
  */
52
- export declare function VoiceBotProvider({ children, url, domainId, autoConnect, widget, navigation, onConnect, onError, onClose, onReply, onMessage, options, disconnectOnUnmount, }: VoiceBotProviderProps): React.JSX.Element;
66
+ export declare function VoiceBotProvider({ children, url, domainId, autoConnect, widget, navigation, onConnect, onError, onClose, onReply, onMessage, options, actions, onConfirmAction, disconnectOnUnmount, }: VoiceBotProviderProps): React.JSX.Element;