orb-ui 0.8.0 → 0.9.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.
- package/README.md +33 -6
- package/dist/adapters/index.d.ts +1 -0
- package/dist/adapters/openai-live/index.d.ts +36 -0
- package/dist/adapters.cjs +1 -1
- package/dist/adapters.js +203 -52
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -1,17 +1,19 @@
|
|
|
1
1
|
# orb-ui
|
|
2
2
|
|
|
3
|
+
[](https://www.npmjs.com/package/orb-ui)
|
|
4
|
+
|
|
3
5
|
**Voice agent UI that feels alive.**
|
|
4
6
|
|
|
5
|
-
Expressive, accessible React components for realtime voice agents. Connect Vapi, ElevenLabs, LiveKit, Pipecat, OpenAI Realtime, Gemini Live, or your own voice stack through one consistent UI layer.
|
|
7
|
+
Expressive, accessible React components for realtime voice agents. Connect Vapi, ElevenLabs, LiveKit, Pipecat, OpenAI Live, OpenAI Realtime, Gemini Live, or your own voice stack through one consistent UI layer.
|
|
6
8
|
|
|
7
9
|
<p align="center">
|
|
8
10
|
<a href="https://orb-ui.com">
|
|
9
|
-
<img src="demo/public/og-image-
|
|
11
|
+
<img src="demo/public/og-image-v3.png" alt="orb-ui — Voice agent UI that feels alive" width="900" />
|
|
10
12
|
</a>
|
|
11
13
|
</p>
|
|
12
14
|
|
|
13
15
|
<p align="center">
|
|
14
|
-
<a href="https://orb-ui.com">Live demo</a> · <a href="https://orb-ui.com/docs">Documentation</a> · <a href="https://orb-ui.com/playground">Playground</a> · <a href="https://www.npmjs.com/package/orb-ui">npm</a> · <a href="https://github.com/
|
|
16
|
+
<a href="https://orb-ui.com">Live demo</a> · <a href="https://orb-ui.com/docs">Documentation</a> · <a href="https://orb-ui.com/playground">Playground</a> · <a href="https://www.npmjs.com/package/orb-ui">npm</a> · <a href="https://github.com/exprmntl/orb-ui">Star on GitHub</a>
|
|
15
17
|
</p>
|
|
16
18
|
|
|
17
19
|
```jsx
|
|
@@ -32,7 +34,7 @@ speaking motion. The adapter keeps microphone and output calibration separate.
|
|
|
32
34
|
|
|
33
35
|
## Install
|
|
34
36
|
|
|
35
|
-
Install the
|
|
37
|
+
Install the [orb-ui package from npm](https://www.npmjs.com/package/orb-ui):
|
|
36
38
|
|
|
37
39
|
```bash
|
|
38
40
|
npm install orb-ui
|
|
@@ -53,7 +55,7 @@ npm install orb-ui livekit-client
|
|
|
53
55
|
# Pipecat (choose the transport used by your agent)
|
|
54
56
|
npm install orb-ui @pipecat-ai/client-js @pipecat-ai/small-webrtc-transport
|
|
55
57
|
|
|
56
|
-
# OpenAI Realtime
|
|
58
|
+
# OpenAI Live and Realtime use browser WebRTC and need no additional client SDK
|
|
57
59
|
npm install orb-ui
|
|
58
60
|
|
|
59
61
|
# Gemini Live
|
|
@@ -78,6 +80,7 @@ The only difference is how the adapter obtains a provider session:
|
|
|
78
80
|
| [ElevenLabs guide](https://orb-ui.com/docs/adapters/elevenlabs) | Pass `Conversation` plus an `agentId`, signed URL, or conversation token |
|
|
79
81
|
| [LiveKit guide](https://orb-ui.com/docs/adapters/livekit) | Provide a token endpoint and optional agent name |
|
|
80
82
|
| [Pipecat guide](https://orb-ui.com/docs/adapters/pipecat) | Pass a configured `PipecatClient` plus its connect callback |
|
|
83
|
+
| [OpenAI Live guide](https://orb-ui.com/docs/adapters/openai-live) | Exchange an SDP offer through your server with `createSession` |
|
|
81
84
|
| [OpenAI Realtime guide](https://orb-ui.com/docs/adapters/openai-realtime) | Return a fresh short-lived client secret from `getClientSecret` |
|
|
82
85
|
| [Gemini Live guide](https://orb-ui.com/docs/adapters/gemini-live) | Open the official Google Live session in `connect` |
|
|
83
86
|
|
|
@@ -164,6 +167,29 @@ The Pipecat adapter consumes the standard RTVI event surface and meters the clie
|
|
|
164
167
|
a browser fallback, so it works with Pipecat Cloud, Daily, SmallWebRTC, and transports that emit
|
|
165
168
|
sparse audio-level events. See the [Pipecat guide](https://orb-ui.com/docs/adapters/pipecat).
|
|
166
169
|
|
|
170
|
+
### With OpenAI GPT-Live
|
|
171
|
+
|
|
172
|
+
```tsx
|
|
173
|
+
import { createOpenAILiveAdapter } from 'orb-ui/adapters'
|
|
174
|
+
|
|
175
|
+
const adapter = createOpenAILiveAdapter({
|
|
176
|
+
createSession: async (sdp, signal) => {
|
|
177
|
+
const response = await fetch('/api/openai-live-session', {
|
|
178
|
+
method: 'POST',
|
|
179
|
+
headers: { 'Content-Type': 'application/json' },
|
|
180
|
+
body: JSON.stringify({ sdp }),
|
|
181
|
+
signal,
|
|
182
|
+
})
|
|
183
|
+
if (!response.ok) throw new Error('Could not create a Live session')
|
|
184
|
+
return response.json()
|
|
185
|
+
},
|
|
186
|
+
})
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
Your server creates a `gpt-live-1` session through `/v1/live/sessions` and returns the session ID
|
|
190
|
+
and SDP answer. Live handles listening and speaking concurrently; configure backend delegation
|
|
191
|
+
on your server. See the [OpenAI Live guide](https://orb-ui.com/docs/adapters/openai-live).
|
|
192
|
+
|
|
167
193
|
### With OpenAI Realtime
|
|
168
194
|
|
|
169
195
|
```jsx
|
|
@@ -346,6 +372,7 @@ the orb with the typed style variable:
|
|
|
346
372
|
| [ElevenLabs](https://elevenlabs.io/conversational-ai) | `createElevenLabsAdapter` from `orb-ui/adapters` |
|
|
347
373
|
| [LiveKit](https://livekit.io) | `createLiveKitAdapter` from `orb-ui/adapters` |
|
|
348
374
|
| [Pipecat](https://pipecat.ai) | `createPipecatAdapter` from `orb-ui/adapters` |
|
|
375
|
+
| [OpenAI GPT-Live](https://developers.openai.com/api/docs/guides/live) | `createOpenAILiveAdapter` from `orb-ui/adapters` |
|
|
349
376
|
| [OpenAI Realtime](https://developers.openai.com/api/docs/guides/realtime) | `createOpenAIRealtimeAdapter` from `orb-ui/adapters` |
|
|
350
377
|
| [Gemini Live](https://ai.google.dev/gemini-api/docs/live-api) | `createGeminiLiveAdapter` from `orb-ui/adapters` |
|
|
351
378
|
| Custom | Use controlled mode with a directional `signal` or build an adapter |
|
|
@@ -353,7 +380,7 @@ the orb with the typed style variable:
|
|
|
353
380
|
## Development
|
|
354
381
|
|
|
355
382
|
```bash
|
|
356
|
-
git clone https://github.com/
|
|
383
|
+
git clone https://github.com/exprmntl/orb-ui.git
|
|
357
384
|
cd orb-ui
|
|
358
385
|
pnpm install
|
|
359
386
|
|
package/dist/adapters/index.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ export { createVapiAdapter, type VapiAdapterOptions } from './vapi/index.js';
|
|
|
2
2
|
export { createElevenLabsAdapter, type ElevenLabsCallbacks, type ElevenLabsConfig, type ElevenLabsConnectionType, type ElevenLabsConversation, type ElevenLabsConversationClass, type ElevenLabsMode, type ElevenLabsOrbAdapter, type ElevenLabsStartSessionOptions, type ElevenLabsStatus, } from './elevenlabs/index.js';
|
|
3
3
|
export { createLiveKitAdapter, type LiveKitAdapterConfig, type LiveKitConnectionDetails, type LiveKitOrbAdapter, type LiveKitResolvedTokenOptions, type LiveKitTokenOptions, type LiveKitTokenSource, } from './livekit/index.js';
|
|
4
4
|
export { createPipecatAdapter, type PipecatAdapterOptions, type PipecatClientLike, type PipecatOrbAdapter, type PipecatParticipantLike, type PipecatTracksLike, } from './pipecat/index.js';
|
|
5
|
+
export { createOpenAILiveAdapter, type OpenAILiveAdapterConfig, type OpenAILiveEvent, type OpenAILiveOrbAdapter, type OpenAILiveSessionResponse, } from './openai-live/index.js';
|
|
5
6
|
export { createOpenAIRealtimeAdapter, type OpenAIRealtimeAdapterConfig, type OpenAIRealtimeClientSecret, type OpenAIRealtimeOrbAdapter, } from './openai-realtime/index.js';
|
|
6
7
|
export { createGeminiLiveAdapter, type GeminiLiveAdapterConfig, type GeminiLiveCallbacks, type GeminiLiveInlineData, type GeminiLiveOrbAdapter, type GeminiLiveServerMessage, type GeminiLiveSession, } from './gemini-live/index.js';
|
|
7
8
|
export { DEFAULT_VOLUME_CALIBRATION, calibrateVolume, createVolumeNormalizer, fitVolumeCalibration, mapVolumeAmplitude, type VolumeAmplitudeCalibration, type VolumeCalibration, type VolumeCalibrationCapture, type VolumeCalibrationFit, type VolumeCalibrationMetrics, type VolumeCalibrationOverrides, type VolumeCalibrationSource, type VolumeEnvelopeCalibration, type VolumeNormalizer, type VolumeSample, } from './audio-level.js';
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { OrbAdapter } from '../types.js';
|
|
2
|
+
import { OpenAIRealtimeAdapterConfig } from '../openai-realtime/index.js';
|
|
3
|
+
/** JSON events are deliberately open-ended so apps can handle new Live events. */
|
|
4
|
+
export interface OpenAILiveEvent {
|
|
5
|
+
type: string;
|
|
6
|
+
[key: string]: unknown;
|
|
7
|
+
}
|
|
8
|
+
export interface OpenAILiveSessionResponse {
|
|
9
|
+
session: {
|
|
10
|
+
id: string;
|
|
11
|
+
};
|
|
12
|
+
transport: {
|
|
13
|
+
type: 'webrtc';
|
|
14
|
+
sdp: string;
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
export interface OpenAILiveAdapterConfig extends Pick<OpenAIRealtimeAdapterConfig, 'mediaStreamConstraints' | 'getUserMedia' | 'createPeerConnection' | 'createAudioElement' | 'createAudioContext' | 'inputVolumeCalibration' | 'outputVolumeCalibration' | 'onInputVolumeSample' | 'onOutputVolumeSample'> {
|
|
18
|
+
/** Exchange the SDP offer on your server using POST /v1/live/sessions. */
|
|
19
|
+
createSession(sdp: string, signal: AbortSignal): Promise<OpenAILiveSessionResponse>;
|
|
20
|
+
/** Receives captions, delegation, usage, errors, and final session events unchanged. */
|
|
21
|
+
onEvent?: (event: OpenAILiveEvent) => void;
|
|
22
|
+
/** Startup deadline, including microphone permission and session.started. Default: 30 seconds. */
|
|
23
|
+
startTimeoutMs?: number;
|
|
24
|
+
/** How long stop waits for session.closed. Default: 15 seconds. */
|
|
25
|
+
closeTimeoutMs?: number;
|
|
26
|
+
}
|
|
27
|
+
export interface OpenAILiveOrbAdapter extends OrbAdapter {
|
|
28
|
+
/** Resolves after SDP negotiation and session.started. */
|
|
29
|
+
start(): Promise<void>;
|
|
30
|
+
/** Finalizes the session; rejects if finalization cannot be confirmed. */
|
|
31
|
+
stop(): Promise<void>;
|
|
32
|
+
/** Send application commands after startup, subject to server-configured client permissions. */
|
|
33
|
+
send(event: OpenAILiveEvent): void;
|
|
34
|
+
}
|
|
35
|
+
/** Managed GPT-Live WebRTC. Project keys and model/delegation configuration stay on your server. */
|
|
36
|
+
export declare function createOpenAILiveAdapter(config: OpenAILiveAdapterConfig): OpenAILiveOrbAdapter;
|
package/dist/adapters.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./livekit-C36Kmz6s.cjs");var t=160;function n(e){let t=`idle`,n=null;function r(r){if(n&&=(clearTimeout(n),null),t===`speaking`&&r===`listening`){n=setTimeout(()=>{t=r,e(r),n=null},350);return}t=r,e(r)}function i(){n&&=(clearTimeout(n),null)}return{emitState:r,clearTimer:i}}function r(r,i){let a=new Set,o=new Set,s=null;function c(){s||(s=r.start.bind(r),r.start=async(...e)=>(a.forEach(e=>e()),s(...e)))}function l(){a.size>0||!s||(r.start=s,s=null)}return{async start(){await r.start(i?.assistantId)},stop(){o.forEach(e=>e()),r.stop()},subscribe(s){let u={state:`idle`,inputVolume:0,outputVolume:0},d=e.o(e.n.vapi.input,i?.inputVolumeCalibration),f=e.o(e.n.vapi.output,i?.outputVolumeCalibration);function p(e){u=e,s(e)}function m(e){p({...u,...e,state:e.state??u.state})}let{emitState:h,clearTimer:g}=n(e=>{v=e,e===`listening`?(I(),m({state:e,outputVolume:0})):m({state:e})}),_=()=>h(`connecting`),v=`idle`,y=!1,b,x,S;function C(e=!0){x?.stop().catch(()=>void 0),x=void 0,b=void 0,d.reset(),e&&u.inputVolume&&m({inputVolume:0})}function w(){let t;try{let e=r.getDailyCallObject?.()?.participants().local?.tracks?.audio;(!e?.state||e.state===`playable`)&&(t=e?.persistentTrack??e?.track)}catch{}if((t?.readyState===`ended`||t?.enabled===!1||t?.muted)&&(t=void 0),t===b||(C(),!t))return;b=t;let n=t;x=e.a(t,i?.createAudioContext??(()=>{if(!(typeof window>`u`||!window.AudioContext))return new window.AudioContext}),e=>{if(!y||b!==n)return;let t=d.sample(n.enabled&&!n.muted&&n.readyState!==`ended`?e:0);i?.onInputVolumeSample?.(t),m({inputVolume:t.normalized})})}function T(e=!0){S!==void 0&&clearInterval(S),S=void 0,C(e)}let E=()=>{y=!0,h(`listening`),r.getDailyCallObject&&(w(),S===void 0&&(S=setInterval(w,100)))},D=()=>{y=!1,v=`idle`,T(),I(),h(`idle`),m({inputVolume:0,outputVolume:0})},O=()=>{y&&(h(`speaking`),F())},k=()=>{y&&(A=0,j=0,M=0,h(`listening`))},A=0,j=0,M=0,N=0,P=e=>{if(v===`speaking`){let n=e-M<=t?j:A,r=f.sample(n,e);i?.onOutputVolumeSample?.(r),m({outputVolume:r.normalized})}N=requestAnimationFrame(P)},F=()=>{N||=requestAnimationFrame(P)},I=()=>{N&&=(cancelAnimationFrame(N),0),A=0,j=0,M=0,f.reset()},L=t=>{v===`speaking`&&(A=t,t>e.n.vapi.output.amplitude.silenceFloor&&(j=t,M=performance.now()))},R=()=>{},z=e=>{console.error(`[orb-ui/vapi] Error:`,e),y=!1,v=`error`,g(),T(),I(),m({state:`error`,inputVolume:0,outputVolume:0,error:e})};return r.on(`call-start`,E),r.on(`call-end`,D),r.on(`speech-start`,O),r.on(`speech-end`,k),r.on(`volume-level`,L),r.on(`message`,R),r.on(`error`,z),a.add(_),o.add(D),c(),()=>{g(),y=!1,T(!1),I(),r.removeListener(`call-start`,E),r.removeListener(`call-end`,D),r.removeListener(`speech-start`,O),r.removeListener(`speech-end`,k),r.removeListener(`volume-level`,L),r.removeListener(`message`,R),r.removeListener(`error`,z),a.delete(_),o.delete(D),l()}}}}function i(t,n){let{inputVolumeCalibration:r,outputVolumeCalibration:i,onInputVolumeSample:a,onOutputVolumeSample:o,...s}=n,c=null,l=0,u=null,d=null,f={state:`idle`,inputVolume:0,outputVolume:0},p=`idle`,m=e.o(e.n.elevenlabs.input,r),h=e.o(e.n.elevenlabs.output,i),g=new Set;function _(e){f=e,g.forEach(t=>t(e))}function v(e){f={...f,...e,state:e.state??f.state},_(f)}function y(e){if(p=e,e===`idle`||e===`connecting`||e===`error`){m.reset(),h.reset(),v({state:e,inputVolume:0,outputVolume:0});return}v({state:e})}function b(){d||=setInterval(()=>{if(!c)return;let e=m.sample(c.getInputVolume()),t=h.sample(c.getOutputVolume());a?.(e),o?.(t),v({inputVolume:e.normalized,outputVolume:t.normalized})},33)}function x(){d&&=(clearInterval(d),null)}function S(){x(),m.reset(),h.reset(),v({inputVolume:0,outputVolume:0})}function C(){p=`idle`,m.reset(),h.reset(),v({state:`idle`,inputVolume:0,outputVolume:0})}function w(e){return e===l}function T(e){return{onStatusChange:({status:t})=>{w(e)&&t===`connecting`&&y(`connecting`)},onConnect:()=>{w(e)&&(y(`listening`),b())},onModeChange:({mode:t})=>{w(e)&&(t===`speaking`?(y(`speaking`),b()):(y(`listening`),b()))},onDisconnect:()=>{w(e)&&(x(),c=null,C())},onError:t=>{w(e)&&(console.error(`[orb-ui/elevenlabs] Error:`,t),x(),p=`error`,v({state:`error`,inputVolume:0,outputVolume:0,error:t}),c=null)}}}return{subscribe(e){return g.add(e),e(f),c&&(p===`listening`||p===`speaking`)&&b(),()=>{g.delete(e),g.size===0&&S()}},async start(){if(c||u)return u??void 0;l+=1;let e=l;return u=(async()=>{try{let n=await t.startSession({...s,...T(e)});if(!w(e)){await n.endSession().catch(e=>{console.error(`[orb-ui/elevenlabs] stale session cleanup failed:`,e)});return}c=n}catch(t){if(!w(e))return;console.error(`[orb-ui/elevenlabs] startSession failed:`,t),y(`error`),v({inputVolume:0,outputVolume:0,error:t})}finally{u=null}})(),u},async stop(){let e=c;if(!e){u&&(l+=1,x(),C(),await u);return}let t=l;x();try{await e.endSession()}catch(e){console.error(`[orb-ui/elevenlabs] endSession failed:`,e)}c===e&&w(t)&&(c=null,C())}}}var a={connected:`connected`,disconnected:`disconnected`,transportStateChanged:`transportStateChanged`,botReady:`botReady`,botDisconnected:`botDisconnected`,error:`error`,messageError:`messageError`,deviceError:`deviceError`,localAudioLevel:`localAudioLevel`,remoteAudioLevel:`remoteAudioLevel`,botStartedSpeaking:`botStartedSpeaking`,botStoppedSpeaking:`botStoppedSpeaking`,userStartedSpeaking:`userStartedSpeaking`,userStoppedSpeaking:`userStoppedSpeaking`,botLlmStarted:`botLlmStarted`,botTtsStarted:`botTtsStarted`};function o(){if(typeof window>`u`)return;let e=window.AudioContext;return e?new e:void 0}function s(e){switch(e){case`initializing`:case`initialized`:case`authenticating`:case`authenticated`:case`connecting`:case`connected`:return`connecting`;case`ready`:return`listening`;case`disconnected`:case`disconnecting`:return`idle`;case`error`:return`error`;default:return}}function c(e){return typeof e==`object`&&!!e&&`kind`in e&&typeof e.kind==`string`}function l(t,n={}){let r=new Set,i=new Map,l={state:s(t.state??``)??`idle`,inputVolume:0,outputVolume:0},u=!1,d=null,f=null,p,m,h=e.o(e.n.pipecat.input,n.inputVolumeCalibration),g=e.o(e.n.pipecat.output,n.outputVolumeCalibration);function _(e){l=e,r.forEach(t=>t(e))}function v(e,t){let n=e===`idle`||e===`connecting`||e===`error`;n&&(h.reset(),g.reset()),_({...l,state:e,...n?{inputVolume:0,outputVolume:0}:{},...t===void 0?{}:{error:t}})}function y(e){let t=h.sample(typeof e==`number`?e:0);n.onInputVolumeSample?.(t),_({...l,inputVolume:t.normalized})}function b(e,t){if(t&&typeof t==`object`){let e=t;if(e.local||n.isBotParticipant&&!n.isBotParticipant(e))return}let r=g.sample(typeof e==`number`?e:0);n.onOutputVolumeSample?.(r),_({...l,outputVolume:r.normalized})}function x(){d=null,p?.stop(),p=void 0}function S(){f=null,m?.stop(),m=void 0}function C(){x(),S()}function w(t){d===t&&p||(x(),d=t,p=e.a(t,n.createAudioContext??o,y),p||(d=null))}function T(t){f===t&&m||(S(),f=t,m=e.a(t,n.createAudioContext??o,b),m||(f=null))}function E(){let e=t.tracks?.();e?.local?.audio&&w(e.local.audio),e?.bot?.audio&&T(e.bot.audio)}function D(e){if(!e||typeof e!=`object`)return!0;let t=e;return t.local?!1:n.isBotParticipant?.(t)??!0}function O(e,t){if(n.playRemoteAudio===!1||!c(e)||e.kind!==`audio`||!D(t))return;let r=n.createAudioElement?.()??new Audio;r.autoplay=!0,r.srcObject=new MediaStream([e]),i.set(e,r),r.play().catch(()=>void 0)}function k(e){if(!c(e))return;let t=i.get(e);t&&(t.pause(),t.srcObject=null,t.remove(),i.delete(e))}function A(e,n){if(!c(e)||e.kind!==`audio`)return;let r=t.tracks?.().local?.audio;n?.local===!0||e===r?w(e):D(n)&&T(e),O(e,n)}function j(e){e===d&&x(),e===f&&S(),k(e)}function M(){i.forEach(e=>{e.pause(),e.srcObject=null,e.remove()}),i.clear()}function N(){C(),v(`idle`)}function P(){v(`listening`),E()}function F(){l.state!==`speaking`&&v(`thinking`)}let I=[[a.connected,()=>v(`connecting`)],[a.botReady,P],[a.disconnected,N],[a.botDisconnected,N],[a.transportStateChanged,e=>{if(typeof e!=`string`)return;let t=s(e);t&&v(t)}],[a.userStartedSpeaking,()=>v(`listening`)],[a.userStoppedSpeaking,()=>{l.state===`listening`&&v(`thinking`)}],[a.botLlmStarted,F],[a.botTtsStarted,F],[a.botStartedSpeaking,()=>v(`speaking`)],[a.botStoppedSpeaking,()=>v(`listening`)],[a.localAudioLevel,e=>!p&&y(e)],[a.remoteAudioLevel,(e,t)=>!m&&b(e,t)],[`trackStarted`,A],[`trackStopped`,j],[a.error,e=>v(`error`,e)],[a.messageError,e=>v(`error`,e)],[a.deviceError,e=>v(`error`,e)]];function L(){u||(u=!0,I.forEach(([e,n])=>t.on(e,n)))}function R(){u&&(u=!1,I.forEach(([e,n])=>{t.off?t.off(e,n):t.removeListener?.(e,n)}),C(),M())}return{subscribe(e){return r.add(e),L(),e(l),()=>{r.delete(e),r.size===0&&R()}},async start(){v(`connecting`);try{await(n.connect?n.connect():t.connect())}catch(e){throw v(`error`,e),e}},async stop(){try{await(n.disconnect?n.disconnect():t.disconnect())}finally{C(),M(),v(`idle`)}}}}var u=`https://api.openai.com/v1/realtime/calls`,d=.015,f=8;function p(){let e=window.AudioContext;return e?new e:void 0}function m(e,t,n){try{let r=t();if(!r)return;let i=r.createMediaStreamSource(e),a=r.createAnalyser();a.fftSize=512,a.smoothingTimeConstant=.25,i.connect(a);let o=new Float32Array(a.fftSize),s=setInterval(()=>{a.getFloatTimeDomainData(o);let e=0;for(let t of o)e+=t*t;n(Math.sqrt(e/o.length))},33);return{async stop(){clearInterval(s),i.disconnect(),a.disconnect(),r.state!==`closed`&&await r.close()}}}catch{return}}function h(e){let t=typeof e==`string`?e:e.value;if(!t)throw Error(`[orb-ui/openai-realtime] getClientSecret returned an empty value.`);return t}function g(t){let n=new Set,r={state:`idle`,inputVolume:0,outputVolume:0},i=null,a=null,o=null,s=null,c,l,g=0,_=`unknown`,v=!1,y=!1,b=e.o(e.n.openai.input,t.inputVolumeCalibration),x=e.o(e.n.openai.output,t.outputVolumeCalibration);function S(e){r=e,n.forEach(t=>t(e))}function C(e,t){if(r.state===e&&t===void 0)return;let n=e===`idle`||e===`connecting`||e===`error`;n&&(b.reset(),x.reset()),S({...r,state:e,...n?{inputVolume:0,outputVolume:0}:{},...t===void 0?{}:{error:t}})}function w(e){let n=b.sample(e);t.onInputVolumeSample?.(n),S({...r,inputVolume:n.normalized})}function T(e){let n=x.sample(e);t.onOutputVolumeSample?.(n);let i=n.normalized;_===`unknown`&&!v&&r.state!==`idle`&&r.state!==`connecting`&&r.state!==`error`&&(i>d?(g=0,r.state!==`speaking`&&C(`speaking`)):r.state===`speaking`&&(g+=1,g>=f&&(g=0,C(`listening`)))),S({...r,outputVolume:i})}function E(e){switch(e.type){case`session.created`:case`session.updated`:C(`listening`);break;case`input_audio_buffer.speech_started`:v=!0,C(`listening`);break;case`input_audio_buffer.speech_stopped`:v=!1,C(_===`playing`?`speaking`:`thinking`);break;case`response.created`:!v&&_!==`playing`&&C(`thinking`);break;case`response.output_audio.delta`:v||C(`speaking`);break;case`output_audio_buffer.started`:_=`playing`,g=0,v||C(`speaking`);break;case`output_audio_buffer.stopped`:case`output_audio_buffer.cleared`:_=`stopped`,g=0,C(`listening`);break;case`response.done`:case`response.cancelled`:r.state!==`speaking`&&C(`listening`);break;case`error`:C(`error`,e.error??e);break}}async function D(e){y=!0,a?.close(),a=null,i?.close(),i=null,o?.getTracks().forEach(e=>e.stop()),o=null,s?.pause(),s&&(s.srcObject=null),s?.remove(),s=null,await Promise.all([c?.stop(),l?.stop()]),c=void 0,l=void 0,g=0,_=`unknown`,v=!1,b.reset(),x.reset(),e&&C(`idle`),y=!1}return{subscribe(e){return n.add(e),e(r),()=>n.delete(e)},async start(){if(!i){C(`connecting`),y=!1;try{let e=t.getUserMedia??(e=>navigator.mediaDevices.getUserMedia(e)),n=t.createPeerConnection??(()=>new RTCPeerConnection),r=t.fetch??fetch,d=t.createAudioElement??(()=>new Audio),f=t.createAudioContext??p,g=h(await t.getClientSecret());o=await e(t.mediaStreamConstraints??{audio:!0}),c=m(o,f,w);let _=n();i=_,o.getAudioTracks().forEach(e=>_.addTrack(e,o)),s=d(),s.autoplay=!0,_.ontrack=e=>{let t=e.streams[0]??new MediaStream([e.track]);s&&(s.srcObject=t),s?.play().catch(()=>void 0),l?.stop(),l=m(t,f,T)},_.onconnectionstatechange=()=>{y||(_.connectionState===`failed`?C(`error`,Error(`[orb-ui/openai-realtime] WebRTC connection failed.`)):(_.connectionState===`disconnected`||_.connectionState===`closed`)&&C(`idle`))};let v=_.createDataChannel(`oai-events`);a=v,v.onopen=()=>C(`listening`),v.onmessage=e=>{try{E(JSON.parse(String(e.data)))}catch{}},v.onerror=e=>C(`error`,e),v.onclose=()=>{y||C(`idle`)};let b=await _.createOffer();await _.setLocalDescription(b);let x=await r(t.callsUrl??u,{method:`POST`,body:b.sdp,headers:{Authorization:`Bearer ${g}`,"Content-Type":`application/sdp`}});if(!x.ok){let e=await x.text();throw Error(`[orb-ui/openai-realtime] Session negotiation failed (${x.status}): ${e}`)}await _.setRemoteDescription({type:`answer`,sdp:await x.text()})}catch(e){throw await D(!1),C(`error`,e),e}}},async stop(){await D(!0)}}}var _=16e3;function v(e){let t=0;for(let n of e)t+=n*n;return Math.sqrt(t/e.length)}function y(e,t,n){if(t===n)return e;let r=t/n,i=Math.max(1,Math.round(e.length/r)),a=new Float32Array(i);for(let t=0;t<i;t+=1){let n=t*r,i=Math.floor(n),o=Math.min(e.length-1,i+1),s=n-i;a[t]=e[i]*(1-s)+e[o]*s}return a}function b(e){let t=new Uint8Array(e.length*2),n=new DataView(t.buffer);e.forEach((e,t)=>{let r=Math.max(-1,Math.min(1,e));n.setInt16(t*2,r<0?r*32768:r*32767,!0)});let r=``;return t.forEach(e=>{r+=String.fromCharCode(e)}),btoa(r)}function x(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);let r=new DataView(n.buffer),i=new Float32Array(Math.floor(n.length/2));for(let e=0;e<i.length;e+=1)i[e]=r.getInt16(e*2,!0)/32768;return i}function S(e){let t=e?.match(/rate=(\d+)/i);return t?Number(t[1]):24e3}function C(t){let n=new Set,r=new Set,i={state:`idle`,inputVolume:0,outputVolume:0},a=null,o=null,s=null,c=null,l=null,u=null,d=null,f=null,p=null,m=!1,h=0,g=!1,C=!1,w=e.o(e.n.gemini.input,t.inputVolumeCalibration),T=e.o(e.n.gemini.output,t.outputVolumeCalibration);function E(){return t.activityDetection!==`server`}function D(e){i=e,n.forEach(t=>t(e))}function O(e,t){if(i.state===e&&t===void 0)return;let n=e===`idle`||e===`connecting`||e===`error`;n&&(w.reset(),T.reset()),D({...i,state:e,...n?{inputVolume:0,outputVolume:0}:{},...t===void 0?{}:{error:t}})}function k(){p&&=(clearTimeout(p),null)}function A(e){let n=w.sample(e);t.onInputVolumeSample?.(n);let r=n.normalized,o=t.speechThreshold??.04;n.mapped>o?(!m&&E()&&a?.sendRealtimeInput({activityStart:{}}),m=!0,k(),i.state!==`listening`&&O(`listening`)):m&&!p&&(p=setTimeout(()=>{p=null,m=!1,E()&&a?.sendRealtimeInput({activityEnd:{}}),i.state===`listening`&&O(`thinking`)},t.speechEndDelayMs??500)),D({...i,inputVolume:r})}function j(){r.forEach(e=>{try{e.stop()}catch{}e.disconnect()}),r.clear(),h=s?.currentTime??0}function M(){g&&r.size===0&&(g=!1,O(`listening`))}function N(e){if(!s||!d||!e.data)return;let t=x(e.data),n=s.createBuffer(1,t.length,S(e.mimeType));n.getChannelData(0).set(t);let a=s.createBufferSource();a.buffer=n,a.connect(d);let o=Math.max(s.currentTime,h);h=o+n.duration,r.add(a),a.onended=()=>{r.delete(a),a.disconnect(),M()},a.start(o),!m&&i.state!==`speaking`&&O(`speaking`)}function P(e){e.setupComplete&&O(`listening`);let t=e.serverContent;if(!t)return;if(t.interrupted){j(),g=!1,O(`listening`);return}let n=t.modelTurn?.parts?.filter(e=>e.inlineData?.data)??[];t.modelTurn&&n.length===0&&i.state!==`speaking`&&O(`thinking`),n.forEach(e=>N(e.inlineData)),t.waitingForInput&&(j(),O(`listening`)),(t.turnComplete||t.generationComplete)&&(g=!0,M())}function F(){if(!d)return;let e=new Float32Array(d.fftSize);f=setInterval(()=>{if(!d)return;d.getFloatTimeDomainData(e);let n=T.sample(v(e));t.onOutputVolumeSample?.(n),D({...i,outputVolume:n.normalized})},33)}function I(){!s||!o||!a||(c=s.createMediaStreamSource(o),l=s.createScriptProcessor(4096,1,1),u=s.createGain(),u.gain.value=0,c.connect(l),l.connect(u),u.connect(s.destination),l.onaudioprocess=e=>{if(!a||C)return;let n=e.inputBuffer.getChannelData(0);A(v(n));let r=y(n,s?.sampleRate??_,t.inputSampleRate??_);a.sendRealtimeInput({audio:{data:b(r),mimeType:`audio/pcm;rate=${t.inputSampleRate??_}`}})})}async function L(e){C=!0,k(),f&&clearInterval(f),f=null,j(),l?.disconnect(),c?.disconnect(),u?.disconnect(),d?.disconnect(),l=null,c=null,u=null,d=null,o?.getTracks().forEach(e=>e.stop()),o=null,s&&s.state!==`closed`&&await s.close(),s=null,a=null,m=!1,g=!1,w.reset(),T.reset(),e&&O(`idle`),C=!1}return{subscribe(e){return n.add(e),e(i),()=>n.delete(e)},async start(){if(!a){O(`connecting`),C=!1;try{let e=t.getUserMedia??(e=>navigator.mediaDevices.getUserMedia(e)),n=t.createAudioContext??(()=>new window.AudioContext);o=await e(t.mediaStreamConstraints??{audio:!0}),s=n(),s.state===`suspended`&&await s.resume(),d=s.createAnalyser(),d.fftSize=512,d.smoothingTimeConstant=.25,d.connect(s.destination),F(),a=await t.connect({onopen:()=>O(`listening`),onmessage:P,onerror:e=>O(`error`,e),onclose:()=>{C||O(`idle`)}}),I(),O(`listening`)}catch(e){throw a?.close(),await L(!1),O(`error`,e),e}}},async stop(){C=!0;try{m&&E()&&a?.sendRealtimeInput({activityEnd:{}}),a?.sendRealtimeInput({audioStreamEnd:!0})}catch{}a?.close(),await L(!0)}}}exports.DEFAULT_VOLUME_CALIBRATION=e.r,exports.PROVIDER_VOLUME_CALIBRATIONS=e.n,exports.calibrateVolume=e.i,exports.createElevenLabsAdapter=i,exports.createGeminiLiveAdapter=C,exports.createLiveKitAdapter=e.t,exports.createOpenAIRealtimeAdapter=g,exports.createPipecatAdapter=l,exports.createVapiAdapter=r,exports.createVolumeNormalizer=e.o,exports.fitVolumeCalibration=e.s,exports.mapVolumeAmplitude=e.c;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./livekit-C36Kmz6s.cjs");var t=160;function n(e){let t=`idle`,n=null;function r(r){if(n&&=(clearTimeout(n),null),t===`speaking`&&r===`listening`){n=setTimeout(()=>{t=r,e(r),n=null},350);return}t=r,e(r)}function i(){n&&=(clearTimeout(n),null)}return{emitState:r,clearTimer:i}}function r(r,i){let a=new Set,o=new Set,s=null;function c(){s||(s=r.start.bind(r),r.start=async(...e)=>(a.forEach(e=>e()),s(...e)))}function l(){a.size>0||!s||(r.start=s,s=null)}return{async start(){await r.start(i?.assistantId)},stop(){o.forEach(e=>e()),r.stop()},subscribe(s){let u={state:`idle`,inputVolume:0,outputVolume:0},d=e.o(e.n.vapi.input,i?.inputVolumeCalibration),f=e.o(e.n.vapi.output,i?.outputVolumeCalibration);function p(e){u=e,s(e)}function m(e){p({...u,...e,state:e.state??u.state})}let{emitState:h,clearTimer:g}=n(e=>{v=e,e===`listening`?(I(),m({state:e,outputVolume:0})):m({state:e})}),_=()=>h(`connecting`),v=`idle`,y=!1,b,x,S;function C(e=!0){x?.stop().catch(()=>void 0),x=void 0,b=void 0,d.reset(),e&&u.inputVolume&&m({inputVolume:0})}function w(){let t;try{let e=r.getDailyCallObject?.()?.participants().local?.tracks?.audio;(!e?.state||e.state===`playable`)&&(t=e?.persistentTrack??e?.track)}catch{}if((t?.readyState===`ended`||t?.enabled===!1||t?.muted)&&(t=void 0),t===b||(C(),!t))return;b=t;let n=t;x=e.a(t,i?.createAudioContext??(()=>{if(!(typeof window>`u`||!window.AudioContext))return new window.AudioContext}),e=>{if(!y||b!==n)return;let t=d.sample(n.enabled&&!n.muted&&n.readyState!==`ended`?e:0);i?.onInputVolumeSample?.(t),m({inputVolume:t.normalized})})}function T(e=!0){S!==void 0&&clearInterval(S),S=void 0,C(e)}let E=()=>{y=!0,h(`listening`),r.getDailyCallObject&&(w(),S===void 0&&(S=setInterval(w,100)))},D=()=>{y=!1,v=`idle`,T(),I(),h(`idle`),m({inputVolume:0,outputVolume:0})},O=()=>{y&&(h(`speaking`),F())},k=()=>{y&&(A=0,j=0,M=0,h(`listening`))},A=0,j=0,M=0,N=0,P=e=>{if(v===`speaking`){let n=e-M<=t?j:A,r=f.sample(n,e);i?.onOutputVolumeSample?.(r),m({outputVolume:r.normalized})}N=requestAnimationFrame(P)},F=()=>{N||=requestAnimationFrame(P)},I=()=>{N&&=(cancelAnimationFrame(N),0),A=0,j=0,M=0,f.reset()},L=t=>{v===`speaking`&&(A=t,t>e.n.vapi.output.amplitude.silenceFloor&&(j=t,M=performance.now()))},R=()=>{},z=e=>{console.error(`[orb-ui/vapi] Error:`,e),y=!1,v=`error`,g(),T(),I(),m({state:`error`,inputVolume:0,outputVolume:0,error:e})};return r.on(`call-start`,E),r.on(`call-end`,D),r.on(`speech-start`,O),r.on(`speech-end`,k),r.on(`volume-level`,L),r.on(`message`,R),r.on(`error`,z),a.add(_),o.add(D),c(),()=>{g(),y=!1,T(!1),I(),r.removeListener(`call-start`,E),r.removeListener(`call-end`,D),r.removeListener(`speech-start`,O),r.removeListener(`speech-end`,k),r.removeListener(`volume-level`,L),r.removeListener(`message`,R),r.removeListener(`error`,z),a.delete(_),o.delete(D),l()}}}}function i(t,n){let{inputVolumeCalibration:r,outputVolumeCalibration:i,onInputVolumeSample:a,onOutputVolumeSample:o,...s}=n,c=null,l=0,u=null,d=null,f={state:`idle`,inputVolume:0,outputVolume:0},p=`idle`,m=e.o(e.n.elevenlabs.input,r),h=e.o(e.n.elevenlabs.output,i),g=new Set;function _(e){f=e,g.forEach(t=>t(e))}function v(e){f={...f,...e,state:e.state??f.state},_(f)}function y(e){if(p=e,e===`idle`||e===`connecting`||e===`error`){m.reset(),h.reset(),v({state:e,inputVolume:0,outputVolume:0});return}v({state:e})}function b(){d||=setInterval(()=>{if(!c)return;let e=m.sample(c.getInputVolume()),t=h.sample(c.getOutputVolume());a?.(e),o?.(t),v({inputVolume:e.normalized,outputVolume:t.normalized})},33)}function x(){d&&=(clearInterval(d),null)}function S(){x(),m.reset(),h.reset(),v({inputVolume:0,outputVolume:0})}function C(){p=`idle`,m.reset(),h.reset(),v({state:`idle`,inputVolume:0,outputVolume:0})}function w(e){return e===l}function T(e){return{onStatusChange:({status:t})=>{w(e)&&t===`connecting`&&y(`connecting`)},onConnect:()=>{w(e)&&(y(`listening`),b())},onModeChange:({mode:t})=>{w(e)&&(t===`speaking`?(y(`speaking`),b()):(y(`listening`),b()))},onDisconnect:()=>{w(e)&&(x(),c=null,C())},onError:t=>{w(e)&&(console.error(`[orb-ui/elevenlabs] Error:`,t),x(),p=`error`,v({state:`error`,inputVolume:0,outputVolume:0,error:t}),c=null)}}}return{subscribe(e){return g.add(e),e(f),c&&(p===`listening`||p===`speaking`)&&b(),()=>{g.delete(e),g.size===0&&S()}},async start(){if(c||u)return u??void 0;l+=1;let e=l;return u=(async()=>{try{let n=await t.startSession({...s,...T(e)});if(!w(e)){await n.endSession().catch(e=>{console.error(`[orb-ui/elevenlabs] stale session cleanup failed:`,e)});return}c=n}catch(t){if(!w(e))return;console.error(`[orb-ui/elevenlabs] startSession failed:`,t),y(`error`),v({inputVolume:0,outputVolume:0,error:t})}finally{u=null}})(),u},async stop(){let e=c;if(!e){u&&(l+=1,x(),C(),await u);return}let t=l;x();try{await e.endSession()}catch(e){console.error(`[orb-ui/elevenlabs] endSession failed:`,e)}c===e&&w(t)&&(c=null,C())}}}var a={connected:`connected`,disconnected:`disconnected`,transportStateChanged:`transportStateChanged`,botReady:`botReady`,botDisconnected:`botDisconnected`,error:`error`,messageError:`messageError`,deviceError:`deviceError`,localAudioLevel:`localAudioLevel`,remoteAudioLevel:`remoteAudioLevel`,botStartedSpeaking:`botStartedSpeaking`,botStoppedSpeaking:`botStoppedSpeaking`,userStartedSpeaking:`userStartedSpeaking`,userStoppedSpeaking:`userStoppedSpeaking`,botLlmStarted:`botLlmStarted`,botTtsStarted:`botTtsStarted`};function o(){if(typeof window>`u`)return;let e=window.AudioContext;return e?new e:void 0}function s(e){switch(e){case`initializing`:case`initialized`:case`authenticating`:case`authenticated`:case`connecting`:case`connected`:return`connecting`;case`ready`:return`listening`;case`disconnected`:case`disconnecting`:return`idle`;case`error`:return`error`;default:return}}function c(e){return typeof e==`object`&&!!e&&`kind`in e&&typeof e.kind==`string`}function l(t,n={}){let r=new Set,i=new Map,l={state:s(t.state??``)??`idle`,inputVolume:0,outputVolume:0},u=!1,d=null,f=null,p,m,h=e.o(e.n.pipecat.input,n.inputVolumeCalibration),g=e.o(e.n.pipecat.output,n.outputVolumeCalibration);function _(e){l=e,r.forEach(t=>t(e))}function v(e,t){let n=e===`idle`||e===`connecting`||e===`error`;n&&(h.reset(),g.reset()),_({...l,state:e,...n?{inputVolume:0,outputVolume:0}:{},...t===void 0?{}:{error:t}})}function y(e){let t=h.sample(typeof e==`number`?e:0);n.onInputVolumeSample?.(t),_({...l,inputVolume:t.normalized})}function b(e,t){if(t&&typeof t==`object`){let e=t;if(e.local||n.isBotParticipant&&!n.isBotParticipant(e))return}let r=g.sample(typeof e==`number`?e:0);n.onOutputVolumeSample?.(r),_({...l,outputVolume:r.normalized})}function x(){d=null,p?.stop(),p=void 0}function S(){f=null,m?.stop(),m=void 0}function C(){x(),S()}function w(t){d===t&&p||(x(),d=t,p=e.a(t,n.createAudioContext??o,y),p||(d=null))}function T(t){f===t&&m||(S(),f=t,m=e.a(t,n.createAudioContext??o,b),m||(f=null))}function E(){let e=t.tracks?.();e?.local?.audio&&w(e.local.audio),e?.bot?.audio&&T(e.bot.audio)}function D(e){if(!e||typeof e!=`object`)return!0;let t=e;return t.local?!1:n.isBotParticipant?.(t)??!0}function O(e,t){if(n.playRemoteAudio===!1||!c(e)||e.kind!==`audio`||!D(t))return;let r=n.createAudioElement?.()??new Audio;r.autoplay=!0,r.srcObject=new MediaStream([e]),i.set(e,r),r.play().catch(()=>void 0)}function k(e){if(!c(e))return;let t=i.get(e);t&&(t.pause(),t.srcObject=null,t.remove(),i.delete(e))}function A(e,n){if(!c(e)||e.kind!==`audio`)return;let r=t.tracks?.().local?.audio;n?.local===!0||e===r?w(e):D(n)&&T(e),O(e,n)}function j(e){e===d&&x(),e===f&&S(),k(e)}function M(){i.forEach(e=>{e.pause(),e.srcObject=null,e.remove()}),i.clear()}function N(){C(),v(`idle`)}function P(){v(`listening`),E()}function F(){l.state!==`speaking`&&v(`thinking`)}let I=[[a.connected,()=>v(`connecting`)],[a.botReady,P],[a.disconnected,N],[a.botDisconnected,N],[a.transportStateChanged,e=>{if(typeof e!=`string`)return;let t=s(e);t&&v(t)}],[a.userStartedSpeaking,()=>v(`listening`)],[a.userStoppedSpeaking,()=>{l.state===`listening`&&v(`thinking`)}],[a.botLlmStarted,F],[a.botTtsStarted,F],[a.botStartedSpeaking,()=>v(`speaking`)],[a.botStoppedSpeaking,()=>v(`listening`)],[a.localAudioLevel,e=>!p&&y(e)],[a.remoteAudioLevel,(e,t)=>!m&&b(e,t)],[`trackStarted`,A],[`trackStopped`,j],[a.error,e=>v(`error`,e)],[a.messageError,e=>v(`error`,e)],[a.deviceError,e=>v(`error`,e)]];function L(){u||(u=!0,I.forEach(([e,n])=>t.on(e,n)))}function R(){u&&(u=!1,I.forEach(([e,n])=>{t.off?t.off(e,n):t.removeListener?.(e,n)}),C(),M())}return{subscribe(e){return r.add(e),L(),e(l),()=>{r.delete(e),r.size===0&&R()}},async start(){v(`connecting`);try{await(n.connect?n.connect():t.connect())}catch(e){throw v(`error`,e),e}},async stop(){try{await(n.disconnect?n.disconnect():t.disconnect())}finally{C(),M(),v(`idle`)}}}}var u=e=>Error(`[orb-ui/openai-live] ${e}`);function d(t){let n=new Set,r={state:`idle`,inputVolume:0,outputVolume:0},i,a,o,s=e.o(e.n.openai.input,t.inputVolumeCalibration),c=e.o(e.n.openai.output,t.outputVolumeCalibration);function l(e){r=e,n.forEach(t=>t(e))}function d(e,t){if(e===r.state&&t===void 0)return;let n=e===`idle`||e===`connecting`||e===`error`;n&&(s.reset(),c.reset()),l({state:e,inputVolume:n?0:r.inputVolume,outputVolume:n?0:r.outputVolume,...t===void 0?{}:{error:t}})}async function f(e){e.disposed||(e.disposed=!0,e.abort.abort(),i===e&&(i=void 0),e.channel&&(e.channel.onmessage=null,e.channel.onclose=null,e.channel.onerror=null,e.channel.close()),e.pc&&(e.pc.ontrack=null,e.pc.onconnectionstatechange=null,e.pc.close()),e.stream?.getTracks().forEach(e=>e.stop()),e.audio&&(e.audio.pause(),e.audio.srcObject=null,e.audio.remove()),await Promise.allSettled([e.inputMeter?.stop(),e.outputMeter?.stop()]))}function p(e){if(e.disposed)throw new DOMException(`Session start cancelled.`,`AbortError`)}function m(e){if(e.disposed||e.closed)return;let t=u(`Connection lost before session.closed; final usage is unconfirmed.`);e.finalized?.(t),d(`error`,t),f(e)}function h(e,n){e.disposed||(n.type===`session.started`&&!e.ready?(e.ready=!0,d(`listening`),e.started?.()):n.type===`session.closed`?(e.closed=!0,e.finalized?.(),d(`idle`),f(e)):n.type===`error`&&d(`error`,n.error??n),t.onEvent?.(n))}async function g(n){let i=await(t.getUserMedia??(e=>navigator.mediaDevices.getUserMedia(e)))(t.mediaStreamConstraints??{audio:!0});n.disposed&&(i.getTracks().forEach(e=>e.stop()),p(n)),n.stream=i;let a=(t.createPeerConnection??(()=>new RTCPeerConnection))();n.pc=a;let o=(t.createAudioElement??(()=>new Audio))();n.audio=o,o.autoplay=!0;let f=t.createAudioContext??(()=>new AudioContext),g=(i,a)=>e.a(i,f,e=>{if(n.disposed||!n.ready||r.state===`error`)return;let i=(a===`input`?s:c).sample(e);a===`input`?t.onInputVolumeSample?.(i):(t.onOutputVolumeSample?.(i),!o.paused&&!o.muted&&o.volume>0&&i.mapped>.015?(n.silenceTicks=0,d(`speaking`)):++n.silenceTicks>=8&&d(`listening`)),l({...r,[a===`input`?`inputVolume`:`outputVolume`]:i.normalized})}),_=i.getAudioTracks();_.forEach(e=>a.addTrack(e,i)),_[0]&&(n.inputMeter=g(_[0],`input`)),a.ontrack=e=>{n.disposed||e.track.kind!==`audio`||(o.srcObject=e.streams[0]??new MediaStream([e.track]),o.play().catch(e=>{n.disposed||d(`error`,e)}),n.outputMeter?.stop(),n.outputMeter=g(e.track,`output`))},a.onconnectionstatechange=()=>{(a.connectionState===`failed`||a.connectionState===`closed`||a.connectionState===`disconnected`)&&m(n)};let v=a.createDataChannel(`oai-events`);n.channel=v,v.onmessage=({data:e})=>{let t;try{t=JSON.parse(String(e))}catch{return}!t||typeof t!=`object`||!(`type`in t)||typeof t.type!=`string`||h(n,t)},v.onclose=()=>m(n),v.onerror=()=>m(n);let y=await a.createOffer();p(n),await a.setLocalDescription(y),p(n),a.iceGatheringState!==`complete`&&await new Promise((e,t)=>{let r=()=>{a.removeEventListener(`icegatheringstatechange`,i),n.abort.signal.removeEventListener(`abort`,o)},i=()=>{a.iceGatheringState===`complete`&&(r(),e())},o=()=>{r(),t(new DOMException(`Session start cancelled.`,`AbortError`))};a.addEventListener(`icegatheringstatechange`,i),n.abort.signal.addEventListener(`abort`,o,{once:!0}),i()}),p(n);let b=a.localDescription?.sdp;if(!b)throw u(`Missing local SDP offer.`);let x=await t.createSession(b,n.abort.signal);if(p(n),!x?.session?.id||x.transport?.type!==`webrtc`||!x.transport.sdp)throw u(`createSession must return a session ID and WebRTC SDP answer.`);await a.setRemoteDescription({type:`answer`,sdp:x.transport.sdp}),p(n)}return{subscribe(e){return n.add(e),e(r),()=>n.delete(e)},start(){if(o)return Promise.reject(u(`Wait for stop() before restarting.`));if(a)return a;if(i)return Promise.resolve();let e={abort:new AbortController,ready:!1,closing:!1,disposed:!1,closed:!1,silenceTicks:0};return i=e,d(`connecting`),a=(async()=>{let n,r=new Promise(t=>{e.started=t}),o=new Promise((r,i)=>{e.abort.signal.addEventListener(`abort`,()=>i(new DOMException(`Session start cancelled.`,`AbortError`)),{once:!0}),n=setTimeout(()=>i(u(`Timed out waiting for session.started.`)),t.startTimeoutMs??3e4)});try{await Promise.race([Promise.all([g(e),r]),o])}catch(t){let n=i===e;throw await f(e),n&&d(`error`,t),t}finally{clearTimeout(n),a=void 0}})(),a},stop(){if(o)return o;let e=i;return e?(e.closing=!0,o=(async()=>{try{if(e.ready&&e.channel?.readyState!==`open`)throw u(`Event channel is unavailable; final usage is unconfirmed.`);e.ready&&e.channel?.readyState===`open`&&await new Promise((n,r)=>{let i=setTimeout(()=>r(u(`Timed out waiting for session.closed; final usage is unconfirmed.`)),t.closeTimeoutMs??15e3);e.finalized=e=>{clearTimeout(i),e?r(e):n()};try{e.channel.send(JSON.stringify({type:`session.close`}))}catch(e){clearTimeout(i),r(e)}}),await f(e),d(`idle`)}catch(t){throw await f(e),d(`error`,t),t}finally{o=void 0}})(),o):(d(`idle`),Promise.resolve())},send(e){if(!i?.ready||i.closing||i.channel?.readyState!==`open`)throw u(`Session is not ready for commands.`);if(e.type===`session.start`||e.type===`session.close`)throw u(`Use start() and stop() to manage the session.`);i.channel.send(JSON.stringify(e))}}}var f=`https://api.openai.com/v1/realtime/calls`,p=.015,m=8;function h(){let e=window.AudioContext;return e?new e:void 0}function g(e,t,n){try{let r=t();if(!r)return;let i=r.createMediaStreamSource(e),a=r.createAnalyser();a.fftSize=512,a.smoothingTimeConstant=.25,i.connect(a);let o=new Float32Array(a.fftSize),s=setInterval(()=>{a.getFloatTimeDomainData(o);let e=0;for(let t of o)e+=t*t;n(Math.sqrt(e/o.length))},33);return{async stop(){clearInterval(s),i.disconnect(),a.disconnect(),r.state!==`closed`&&await r.close()}}}catch{return}}function _(e){let t=typeof e==`string`?e:e.value;if(!t)throw Error(`[orb-ui/openai-realtime] getClientSecret returned an empty value.`);return t}function v(t){let n=new Set,r={state:`idle`,inputVolume:0,outputVolume:0},i=null,a=null,o=null,s=null,c,l,u=0,d=`unknown`,v=!1,y=!1,b=e.o(e.n.openai.input,t.inputVolumeCalibration),x=e.o(e.n.openai.output,t.outputVolumeCalibration);function S(e){r=e,n.forEach(t=>t(e))}function C(e,t){if(r.state===e&&t===void 0)return;let n=e===`idle`||e===`connecting`||e===`error`;n&&(b.reset(),x.reset()),S({...r,state:e,...n?{inputVolume:0,outputVolume:0}:{},...t===void 0?{}:{error:t}})}function w(e){let n=b.sample(e);t.onInputVolumeSample?.(n),S({...r,inputVolume:n.normalized})}function T(e){let n=x.sample(e);t.onOutputVolumeSample?.(n);let i=n.normalized;d===`unknown`&&!v&&r.state!==`idle`&&r.state!==`connecting`&&r.state!==`error`&&(i>p?(u=0,r.state!==`speaking`&&C(`speaking`)):r.state===`speaking`&&(u+=1,u>=m&&(u=0,C(`listening`)))),S({...r,outputVolume:i})}function E(e){switch(e.type){case`session.created`:case`session.updated`:C(`listening`);break;case`input_audio_buffer.speech_started`:v=!0,C(`listening`);break;case`input_audio_buffer.speech_stopped`:v=!1,C(d===`playing`?`speaking`:`thinking`);break;case`response.created`:!v&&d!==`playing`&&C(`thinking`);break;case`response.output_audio.delta`:v||C(`speaking`);break;case`output_audio_buffer.started`:d=`playing`,u=0,v||C(`speaking`);break;case`output_audio_buffer.stopped`:case`output_audio_buffer.cleared`:d=`stopped`,u=0,C(`listening`);break;case`response.done`:case`response.cancelled`:r.state!==`speaking`&&C(`listening`);break;case`error`:C(`error`,e.error??e);break}}async function D(e){y=!0,a?.close(),a=null,i?.close(),i=null,o?.getTracks().forEach(e=>e.stop()),o=null,s?.pause(),s&&(s.srcObject=null),s?.remove(),s=null,await Promise.all([c?.stop(),l?.stop()]),c=void 0,l=void 0,u=0,d=`unknown`,v=!1,b.reset(),x.reset(),e&&C(`idle`),y=!1}return{subscribe(e){return n.add(e),e(r),()=>n.delete(e)},async start(){if(!i){C(`connecting`),y=!1;try{let e=t.getUserMedia??(e=>navigator.mediaDevices.getUserMedia(e)),n=t.createPeerConnection??(()=>new RTCPeerConnection),r=t.fetch??fetch,u=t.createAudioElement??(()=>new Audio),d=t.createAudioContext??h,p=_(await t.getClientSecret());o=await e(t.mediaStreamConstraints??{audio:!0}),c=g(o,d,w);let m=n();i=m,o.getAudioTracks().forEach(e=>m.addTrack(e,o)),s=u(),s.autoplay=!0,m.ontrack=e=>{let t=e.streams[0]??new MediaStream([e.track]);s&&(s.srcObject=t),s?.play().catch(()=>void 0),l?.stop(),l=g(t,d,T)},m.onconnectionstatechange=()=>{y||(m.connectionState===`failed`?C(`error`,Error(`[orb-ui/openai-realtime] WebRTC connection failed.`)):(m.connectionState===`disconnected`||m.connectionState===`closed`)&&C(`idle`))};let v=m.createDataChannel(`oai-events`);a=v,v.onopen=()=>C(`listening`),v.onmessage=e=>{try{E(JSON.parse(String(e.data)))}catch{}},v.onerror=e=>C(`error`,e),v.onclose=()=>{y||C(`idle`)};let b=await m.createOffer();await m.setLocalDescription(b);let x=await r(t.callsUrl??f,{method:`POST`,body:b.sdp,headers:{Authorization:`Bearer ${p}`,"Content-Type":`application/sdp`}});if(!x.ok){let e=await x.text();throw Error(`[orb-ui/openai-realtime] Session negotiation failed (${x.status}): ${e}`)}await m.setRemoteDescription({type:`answer`,sdp:await x.text()})}catch(e){throw await D(!1),C(`error`,e),e}}},async stop(){await D(!0)}}}var y=16e3;function b(e){let t=0;for(let n of e)t+=n*n;return Math.sqrt(t/e.length)}function x(e,t,n){if(t===n)return e;let r=t/n,i=Math.max(1,Math.round(e.length/r)),a=new Float32Array(i);for(let t=0;t<i;t+=1){let n=t*r,i=Math.floor(n),o=Math.min(e.length-1,i+1),s=n-i;a[t]=e[i]*(1-s)+e[o]*s}return a}function S(e){let t=new Uint8Array(e.length*2),n=new DataView(t.buffer);e.forEach((e,t)=>{let r=Math.max(-1,Math.min(1,e));n.setInt16(t*2,r<0?r*32768:r*32767,!0)});let r=``;return t.forEach(e=>{r+=String.fromCharCode(e)}),btoa(r)}function C(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);let r=new DataView(n.buffer),i=new Float32Array(Math.floor(n.length/2));for(let e=0;e<i.length;e+=1)i[e]=r.getInt16(e*2,!0)/32768;return i}function w(e){let t=e?.match(/rate=(\d+)/i);return t?Number(t[1]):24e3}function T(t){let n=new Set,r=new Set,i={state:`idle`,inputVolume:0,outputVolume:0},a=null,o=null,s=null,c=null,l=null,u=null,d=null,f=null,p=null,m=!1,h=0,g=!1,_=!1,v=e.o(e.n.gemini.input,t.inputVolumeCalibration),T=e.o(e.n.gemini.output,t.outputVolumeCalibration);function E(){return t.activityDetection!==`server`}function D(e){i=e,n.forEach(t=>t(e))}function O(e,t){if(i.state===e&&t===void 0)return;let n=e===`idle`||e===`connecting`||e===`error`;n&&(v.reset(),T.reset()),D({...i,state:e,...n?{inputVolume:0,outputVolume:0}:{},...t===void 0?{}:{error:t}})}function k(){p&&=(clearTimeout(p),null)}function A(e){let n=v.sample(e);t.onInputVolumeSample?.(n);let r=n.normalized,o=t.speechThreshold??.04;n.mapped>o?(!m&&E()&&a?.sendRealtimeInput({activityStart:{}}),m=!0,k(),i.state!==`listening`&&O(`listening`)):m&&!p&&(p=setTimeout(()=>{p=null,m=!1,E()&&a?.sendRealtimeInput({activityEnd:{}}),i.state===`listening`&&O(`thinking`)},t.speechEndDelayMs??500)),D({...i,inputVolume:r})}function j(){r.forEach(e=>{try{e.stop()}catch{}e.disconnect()}),r.clear(),h=s?.currentTime??0}function M(){g&&r.size===0&&(g=!1,O(`listening`))}function N(e){if(!s||!d||!e.data)return;let t=C(e.data),n=s.createBuffer(1,t.length,w(e.mimeType));n.getChannelData(0).set(t);let a=s.createBufferSource();a.buffer=n,a.connect(d);let o=Math.max(s.currentTime,h);h=o+n.duration,r.add(a),a.onended=()=>{r.delete(a),a.disconnect(),M()},a.start(o),!m&&i.state!==`speaking`&&O(`speaking`)}function P(e){e.setupComplete&&O(`listening`);let t=e.serverContent;if(!t)return;if(t.interrupted){j(),g=!1,O(`listening`);return}let n=t.modelTurn?.parts?.filter(e=>e.inlineData?.data)??[];t.modelTurn&&n.length===0&&i.state!==`speaking`&&O(`thinking`),n.forEach(e=>N(e.inlineData)),t.waitingForInput&&(j(),O(`listening`)),(t.turnComplete||t.generationComplete)&&(g=!0,M())}function F(){if(!d)return;let e=new Float32Array(d.fftSize);f=setInterval(()=>{if(!d)return;d.getFloatTimeDomainData(e);let n=T.sample(b(e));t.onOutputVolumeSample?.(n),D({...i,outputVolume:n.normalized})},33)}function I(){!s||!o||!a||(c=s.createMediaStreamSource(o),l=s.createScriptProcessor(4096,1,1),u=s.createGain(),u.gain.value=0,c.connect(l),l.connect(u),u.connect(s.destination),l.onaudioprocess=e=>{if(!a||_)return;let n=e.inputBuffer.getChannelData(0);A(b(n));let r=x(n,s?.sampleRate??y,t.inputSampleRate??y);a.sendRealtimeInput({audio:{data:S(r),mimeType:`audio/pcm;rate=${t.inputSampleRate??y}`}})})}async function L(e){_=!0,k(),f&&clearInterval(f),f=null,j(),l?.disconnect(),c?.disconnect(),u?.disconnect(),d?.disconnect(),l=null,c=null,u=null,d=null,o?.getTracks().forEach(e=>e.stop()),o=null,s&&s.state!==`closed`&&await s.close(),s=null,a=null,m=!1,g=!1,v.reset(),T.reset(),e&&O(`idle`),_=!1}return{subscribe(e){return n.add(e),e(i),()=>n.delete(e)},async start(){if(!a){O(`connecting`),_=!1;try{let e=t.getUserMedia??(e=>navigator.mediaDevices.getUserMedia(e)),n=t.createAudioContext??(()=>new window.AudioContext);o=await e(t.mediaStreamConstraints??{audio:!0}),s=n(),s.state===`suspended`&&await s.resume(),d=s.createAnalyser(),d.fftSize=512,d.smoothingTimeConstant=.25,d.connect(s.destination),F(),a=await t.connect({onopen:()=>O(`listening`),onmessage:P,onerror:e=>O(`error`,e),onclose:()=>{_||O(`idle`)}}),I(),O(`listening`)}catch(e){throw a?.close(),await L(!1),O(`error`,e),e}}},async stop(){_=!0;try{m&&E()&&a?.sendRealtimeInput({activityEnd:{}}),a?.sendRealtimeInput({audioStreamEnd:!0})}catch{}a?.close(),await L(!0)}}}exports.DEFAULT_VOLUME_CALIBRATION=e.r,exports.PROVIDER_VOLUME_CALIBRATIONS=e.n,exports.calibrateVolume=e.i,exports.createElevenLabsAdapter=i,exports.createGeminiLiveAdapter=T,exports.createLiveKitAdapter=e.t,exports.createOpenAILiveAdapter=d,exports.createOpenAIRealtimeAdapter=v,exports.createPipecatAdapter=l,exports.createVapiAdapter=r,exports.createVolumeNormalizer=e.o,exports.fitVolumeCalibration=e.s,exports.mapVolumeAmplitude=e.c;
|
package/dist/adapters.js
CHANGED
|
@@ -447,13 +447,164 @@ function g(t, n = {}) {
|
|
|
447
447
|
};
|
|
448
448
|
}
|
|
449
449
|
//#endregion
|
|
450
|
+
//#region src/adapters/openai-live/index.ts
|
|
451
|
+
var _ = (e) => /* @__PURE__ */ Error(`[orb-ui/openai-live] ${e}`);
|
|
452
|
+
function v(t) {
|
|
453
|
+
let n = /* @__PURE__ */ new Set(), a = {
|
|
454
|
+
state: "idle",
|
|
455
|
+
inputVolume: 0,
|
|
456
|
+
outputVolume: 0
|
|
457
|
+
}, o, s, c, l = i(r.openai.input, t.inputVolumeCalibration), u = i(r.openai.output, t.outputVolumeCalibration);
|
|
458
|
+
function d(e) {
|
|
459
|
+
a = e, n.forEach((t) => t(e));
|
|
460
|
+
}
|
|
461
|
+
function f(e, t) {
|
|
462
|
+
if (e === a.state && t === void 0) return;
|
|
463
|
+
let n = e === "idle" || e === "connecting" || e === "error";
|
|
464
|
+
n && (l.reset(), u.reset()), d({
|
|
465
|
+
state: e,
|
|
466
|
+
inputVolume: n ? 0 : a.inputVolume,
|
|
467
|
+
outputVolume: n ? 0 : a.outputVolume,
|
|
468
|
+
...t === void 0 ? {} : { error: t }
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
async function p(e) {
|
|
472
|
+
e.disposed || (e.disposed = !0, e.abort.abort(), o === e && (o = void 0), e.channel && (e.channel.onmessage = null, e.channel.onclose = null, e.channel.onerror = null, e.channel.close()), e.pc && (e.pc.ontrack = null, e.pc.onconnectionstatechange = null, e.pc.close()), e.stream?.getTracks().forEach((e) => e.stop()), e.audio && (e.audio.pause(), e.audio.srcObject = null, e.audio.remove()), await Promise.allSettled([e.inputMeter?.stop(), e.outputMeter?.stop()]));
|
|
473
|
+
}
|
|
474
|
+
function m(e) {
|
|
475
|
+
if (e.disposed) throw new DOMException("Session start cancelled.", "AbortError");
|
|
476
|
+
}
|
|
477
|
+
function h(e) {
|
|
478
|
+
if (e.disposed || e.closed) return;
|
|
479
|
+
let t = _("Connection lost before session.closed; final usage is unconfirmed.");
|
|
480
|
+
e.finalized?.(t), f("error", t), p(e);
|
|
481
|
+
}
|
|
482
|
+
function g(e, n) {
|
|
483
|
+
e.disposed || (n.type === "session.started" && !e.ready ? (e.ready = !0, f("listening"), e.started?.()) : n.type === "session.closed" ? (e.closed = !0, e.finalized?.(), f("idle"), p(e)) : n.type === "error" && f("error", n.error ?? n), t.onEvent?.(n));
|
|
484
|
+
}
|
|
485
|
+
async function v(n) {
|
|
486
|
+
let r = await (t.getUserMedia ?? ((e) => navigator.mediaDevices.getUserMedia(e)))(t.mediaStreamConstraints ?? { audio: !0 });
|
|
487
|
+
n.disposed && (r.getTracks().forEach((e) => e.stop()), m(n)), n.stream = r;
|
|
488
|
+
let i = (t.createPeerConnection ?? (() => new RTCPeerConnection()))();
|
|
489
|
+
n.pc = i;
|
|
490
|
+
let o = (t.createAudioElement ?? (() => new Audio()))();
|
|
491
|
+
n.audio = o, o.autoplay = !0;
|
|
492
|
+
let s = t.createAudioContext ?? (() => new AudioContext()), c = (r, i) => e(r, s, (e) => {
|
|
493
|
+
if (n.disposed || !n.ready || a.state === "error") return;
|
|
494
|
+
let r = (i === "input" ? l : u).sample(e);
|
|
495
|
+
i === "input" ? t.onInputVolumeSample?.(r) : (t.onOutputVolumeSample?.(r), !o.paused && !o.muted && o.volume > 0 && r.mapped > .015 ? (n.silenceTicks = 0, f("speaking")) : ++n.silenceTicks >= 8 && f("listening")), d({
|
|
496
|
+
...a,
|
|
497
|
+
[i === "input" ? "inputVolume" : "outputVolume"]: r.normalized
|
|
498
|
+
});
|
|
499
|
+
}), p = r.getAudioTracks();
|
|
500
|
+
p.forEach((e) => i.addTrack(e, r)), p[0] && (n.inputMeter = c(p[0], "input")), i.ontrack = (e) => {
|
|
501
|
+
n.disposed || e.track.kind !== "audio" || (o.srcObject = e.streams[0] ?? new MediaStream([e.track]), o.play().catch((e) => {
|
|
502
|
+
n.disposed || f("error", e);
|
|
503
|
+
}), n.outputMeter?.stop(), n.outputMeter = c(e.track, "output"));
|
|
504
|
+
}, i.onconnectionstatechange = () => {
|
|
505
|
+
(i.connectionState === "failed" || i.connectionState === "closed" || i.connectionState === "disconnected") && h(n);
|
|
506
|
+
};
|
|
507
|
+
let v = i.createDataChannel("oai-events");
|
|
508
|
+
n.channel = v, v.onmessage = ({ data: e }) => {
|
|
509
|
+
let t;
|
|
510
|
+
try {
|
|
511
|
+
t = JSON.parse(String(e));
|
|
512
|
+
} catch {
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
!t || typeof t != "object" || !("type" in t) || typeof t.type != "string" || g(n, t);
|
|
516
|
+
}, v.onclose = () => h(n), v.onerror = () => h(n);
|
|
517
|
+
let y = await i.createOffer();
|
|
518
|
+
m(n), await i.setLocalDescription(y), m(n), i.iceGatheringState !== "complete" && await new Promise((e, t) => {
|
|
519
|
+
let r = () => {
|
|
520
|
+
i.removeEventListener("icegatheringstatechange", a), n.abort.signal.removeEventListener("abort", o);
|
|
521
|
+
}, a = () => {
|
|
522
|
+
i.iceGatheringState === "complete" && (r(), e());
|
|
523
|
+
}, o = () => {
|
|
524
|
+
r(), t(new DOMException("Session start cancelled.", "AbortError"));
|
|
525
|
+
};
|
|
526
|
+
i.addEventListener("icegatheringstatechange", a), n.abort.signal.addEventListener("abort", o, { once: !0 }), a();
|
|
527
|
+
}), m(n);
|
|
528
|
+
let b = i.localDescription?.sdp;
|
|
529
|
+
if (!b) throw _("Missing local SDP offer.");
|
|
530
|
+
let x = await t.createSession(b, n.abort.signal);
|
|
531
|
+
if (m(n), !x?.session?.id || x.transport?.type !== "webrtc" || !x.transport.sdp) throw _("createSession must return a session ID and WebRTC SDP answer.");
|
|
532
|
+
await i.setRemoteDescription({
|
|
533
|
+
type: "answer",
|
|
534
|
+
sdp: x.transport.sdp
|
|
535
|
+
}), m(n);
|
|
536
|
+
}
|
|
537
|
+
return {
|
|
538
|
+
subscribe(e) {
|
|
539
|
+
return n.add(e), e(a), () => n.delete(e);
|
|
540
|
+
},
|
|
541
|
+
start() {
|
|
542
|
+
if (c) return Promise.reject(_("Wait for stop() before restarting."));
|
|
543
|
+
if (s) return s;
|
|
544
|
+
if (o) return Promise.resolve();
|
|
545
|
+
let e = {
|
|
546
|
+
abort: new AbortController(),
|
|
547
|
+
ready: !1,
|
|
548
|
+
closing: !1,
|
|
549
|
+
disposed: !1,
|
|
550
|
+
closed: !1,
|
|
551
|
+
silenceTicks: 0
|
|
552
|
+
};
|
|
553
|
+
return o = e, f("connecting"), s = (async () => {
|
|
554
|
+
let n, r = new Promise((t) => {
|
|
555
|
+
e.started = t;
|
|
556
|
+
}), i = new Promise((r, i) => {
|
|
557
|
+
e.abort.signal.addEventListener("abort", () => i(new DOMException("Session start cancelled.", "AbortError")), { once: !0 }), n = setTimeout(() => i(_("Timed out waiting for session.started.")), t.startTimeoutMs ?? 3e4);
|
|
558
|
+
});
|
|
559
|
+
try {
|
|
560
|
+
await Promise.race([Promise.all([v(e), r]), i]);
|
|
561
|
+
} catch (t) {
|
|
562
|
+
let n = o === e;
|
|
563
|
+
throw await p(e), n && f("error", t), t;
|
|
564
|
+
} finally {
|
|
565
|
+
clearTimeout(n), s = void 0;
|
|
566
|
+
}
|
|
567
|
+
})(), s;
|
|
568
|
+
},
|
|
569
|
+
stop() {
|
|
570
|
+
if (c) return c;
|
|
571
|
+
let e = o;
|
|
572
|
+
return e ? (e.closing = !0, c = (async () => {
|
|
573
|
+
try {
|
|
574
|
+
if (e.ready && e.channel?.readyState !== "open") throw _("Event channel is unavailable; final usage is unconfirmed.");
|
|
575
|
+
e.ready && e.channel?.readyState === "open" && await new Promise((n, r) => {
|
|
576
|
+
let i = setTimeout(() => r(_("Timed out waiting for session.closed; final usage is unconfirmed.")), t.closeTimeoutMs ?? 15e3);
|
|
577
|
+
e.finalized = (e) => {
|
|
578
|
+
clearTimeout(i), e ? r(e) : n();
|
|
579
|
+
};
|
|
580
|
+
try {
|
|
581
|
+
e.channel.send(JSON.stringify({ type: "session.close" }));
|
|
582
|
+
} catch (e) {
|
|
583
|
+
clearTimeout(i), r(e);
|
|
584
|
+
}
|
|
585
|
+
}), await p(e), f("idle");
|
|
586
|
+
} catch (t) {
|
|
587
|
+
throw await p(e), f("error", t), t;
|
|
588
|
+
} finally {
|
|
589
|
+
c = void 0;
|
|
590
|
+
}
|
|
591
|
+
})(), c) : (f("idle"), Promise.resolve());
|
|
592
|
+
},
|
|
593
|
+
send(e) {
|
|
594
|
+
if (!o?.ready || o.closing || o.channel?.readyState !== "open") throw _("Session is not ready for commands.");
|
|
595
|
+
if (e.type === "session.start" || e.type === "session.close") throw _("Use start() and stop() to manage the session.");
|
|
596
|
+
o.channel.send(JSON.stringify(e));
|
|
597
|
+
}
|
|
598
|
+
};
|
|
599
|
+
}
|
|
600
|
+
//#endregion
|
|
450
601
|
//#region src/adapters/openai-realtime/index.ts
|
|
451
|
-
var
|
|
452
|
-
function
|
|
602
|
+
var y = "https://api.openai.com/v1/realtime/calls", b = .015, x = 8;
|
|
603
|
+
function S() {
|
|
453
604
|
let e = window.AudioContext;
|
|
454
605
|
return e ? new e() : void 0;
|
|
455
606
|
}
|
|
456
|
-
function
|
|
607
|
+
function C(e, t, n) {
|
|
457
608
|
try {
|
|
458
609
|
let r = t();
|
|
459
610
|
if (!r) return;
|
|
@@ -472,24 +623,24 @@ function x(e, t, n) {
|
|
|
472
623
|
return;
|
|
473
624
|
}
|
|
474
625
|
}
|
|
475
|
-
function
|
|
626
|
+
function w(e) {
|
|
476
627
|
let t = typeof e == "string" ? e : e.value;
|
|
477
628
|
if (!t) throw Error("[orb-ui/openai-realtime] getClientSecret returned an empty value.");
|
|
478
629
|
return t;
|
|
479
630
|
}
|
|
480
|
-
function
|
|
631
|
+
function T(e) {
|
|
481
632
|
let t = /* @__PURE__ */ new Set(), n = {
|
|
482
633
|
state: "idle",
|
|
483
634
|
inputVolume: 0,
|
|
484
635
|
outputVolume: 0
|
|
485
636
|
}, a = null, o = null, s = null, c = null, l, u, d = 0, f = "unknown", p = !1, m = !1, h = i(r.openai.input, e.inputVolumeCalibration), g = i(r.openai.output, e.outputVolumeCalibration);
|
|
486
|
-
function
|
|
637
|
+
function _(e) {
|
|
487
638
|
n = e, t.forEach((t) => t(e));
|
|
488
639
|
}
|
|
489
|
-
function
|
|
640
|
+
function v(e, t) {
|
|
490
641
|
if (n.state === e && t === void 0) return;
|
|
491
642
|
let r = e === "idle" || e === "connecting" || e === "error";
|
|
492
|
-
r && (h.reset(), g.reset()),
|
|
643
|
+
r && (h.reset(), g.reset()), _({
|
|
493
644
|
...n,
|
|
494
645
|
state: e,
|
|
495
646
|
...r ? {
|
|
@@ -501,7 +652,7 @@ function C(e) {
|
|
|
501
652
|
}
|
|
502
653
|
function T(t) {
|
|
503
654
|
let r = h.sample(t);
|
|
504
|
-
e.onInputVolumeSample?.(r),
|
|
655
|
+
e.onInputVolumeSample?.(r), _({
|
|
505
656
|
...n,
|
|
506
657
|
inputVolume: r.normalized
|
|
507
658
|
});
|
|
@@ -510,7 +661,7 @@ function C(e) {
|
|
|
510
661
|
let r = g.sample(t);
|
|
511
662
|
e.onOutputVolumeSample?.(r);
|
|
512
663
|
let i = r.normalized;
|
|
513
|
-
f === "unknown" && !p && n.state !== "idle" && n.state !== "connecting" && n.state !== "error" && (i >
|
|
664
|
+
f === "unknown" && !p && n.state !== "idle" && n.state !== "connecting" && n.state !== "error" && (i > b ? (d = 0, n.state !== "speaking" && v("speaking")) : n.state === "speaking" && (d += 1, d >= x && (d = 0, v("listening")))), _({
|
|
514
665
|
...n,
|
|
515
666
|
outputVolume: i
|
|
516
667
|
});
|
|
@@ -519,38 +670,38 @@ function C(e) {
|
|
|
519
670
|
switch (e.type) {
|
|
520
671
|
case "session.created":
|
|
521
672
|
case "session.updated":
|
|
522
|
-
|
|
673
|
+
v("listening");
|
|
523
674
|
break;
|
|
524
675
|
case "input_audio_buffer.speech_started":
|
|
525
|
-
p = !0,
|
|
676
|
+
p = !0, v("listening");
|
|
526
677
|
break;
|
|
527
678
|
case "input_audio_buffer.speech_stopped":
|
|
528
|
-
p = !1,
|
|
679
|
+
p = !1, v(f === "playing" ? "speaking" : "thinking");
|
|
529
680
|
break;
|
|
530
681
|
case "response.created":
|
|
531
|
-
!p && f !== "playing" &&
|
|
682
|
+
!p && f !== "playing" && v("thinking");
|
|
532
683
|
break;
|
|
533
684
|
case "response.output_audio.delta":
|
|
534
|
-
p ||
|
|
685
|
+
p || v("speaking");
|
|
535
686
|
break;
|
|
536
687
|
case "output_audio_buffer.started":
|
|
537
|
-
f = "playing", d = 0, p ||
|
|
688
|
+
f = "playing", d = 0, p || v("speaking");
|
|
538
689
|
break;
|
|
539
690
|
case "output_audio_buffer.stopped":
|
|
540
691
|
case "output_audio_buffer.cleared":
|
|
541
|
-
f = "stopped", d = 0,
|
|
692
|
+
f = "stopped", d = 0, v("listening");
|
|
542
693
|
break;
|
|
543
694
|
case "response.done":
|
|
544
695
|
case "response.cancelled":
|
|
545
|
-
n.state !== "speaking" &&
|
|
696
|
+
n.state !== "speaking" && v("listening");
|
|
546
697
|
break;
|
|
547
698
|
case "error":
|
|
548
|
-
|
|
699
|
+
v("error", e.error ?? e);
|
|
549
700
|
break;
|
|
550
701
|
}
|
|
551
702
|
}
|
|
552
703
|
async function O(e) {
|
|
553
|
-
m = !0, o?.close(), o = null, a?.close(), a = null, s?.getTracks().forEach((e) => e.stop()), s = null, c?.pause(), c && (c.srcObject = null), c?.remove(), c = null, await Promise.all([l?.stop(), u?.stop()]), l = void 0, u = void 0, d = 0, f = "unknown", p = !1, h.reset(), g.reset(), e &&
|
|
704
|
+
m = !0, o?.close(), o = null, a?.close(), a = null, s?.getTracks().forEach((e) => e.stop()), s = null, c?.pause(), c && (c.srcObject = null), c?.remove(), c = null, await Promise.all([l?.stop(), u?.stop()]), l = void 0, u = void 0, d = 0, f = "unknown", p = !1, h.reset(), g.reset(), e && v("idle"), m = !1;
|
|
554
705
|
}
|
|
555
706
|
return {
|
|
556
707
|
subscribe(e) {
|
|
@@ -558,28 +709,28 @@ function C(e) {
|
|
|
558
709
|
},
|
|
559
710
|
async start() {
|
|
560
711
|
if (!a) {
|
|
561
|
-
|
|
712
|
+
v("connecting"), m = !1;
|
|
562
713
|
try {
|
|
563
|
-
let t = e.getUserMedia ?? ((e) => navigator.mediaDevices.getUserMedia(e)), n = e.createPeerConnection ?? (() => new RTCPeerConnection()), r = e.fetch ?? fetch, i = e.createAudioElement ?? (() => new Audio()), d = e.createAudioContext ??
|
|
564
|
-
s = await t(e.mediaStreamConstraints ?? { audio: !0 }), l =
|
|
714
|
+
let t = e.getUserMedia ?? ((e) => navigator.mediaDevices.getUserMedia(e)), n = e.createPeerConnection ?? (() => new RTCPeerConnection()), r = e.fetch ?? fetch, i = e.createAudioElement ?? (() => new Audio()), d = e.createAudioContext ?? S, f = w(await e.getClientSecret());
|
|
715
|
+
s = await t(e.mediaStreamConstraints ?? { audio: !0 }), l = C(s, d, T);
|
|
565
716
|
let p = n();
|
|
566
717
|
a = p, s.getAudioTracks().forEach((e) => p.addTrack(e, s)), c = i(), c.autoplay = !0, p.ontrack = (e) => {
|
|
567
718
|
let t = e.streams[0] ?? new MediaStream([e.track]);
|
|
568
|
-
c && (c.srcObject = t), c?.play().catch(() => void 0), u?.stop(), u =
|
|
719
|
+
c && (c.srcObject = t), c?.play().catch(() => void 0), u?.stop(), u = C(t, d, E);
|
|
569
720
|
}, p.onconnectionstatechange = () => {
|
|
570
|
-
m || (p.connectionState === "failed" ?
|
|
721
|
+
m || (p.connectionState === "failed" ? v("error", /* @__PURE__ */ Error("[orb-ui/openai-realtime] WebRTC connection failed.")) : (p.connectionState === "disconnected" || p.connectionState === "closed") && v("idle"));
|
|
571
722
|
};
|
|
572
723
|
let h = p.createDataChannel("oai-events");
|
|
573
|
-
o = h, h.onopen = () =>
|
|
724
|
+
o = h, h.onopen = () => v("listening"), h.onmessage = (e) => {
|
|
574
725
|
try {
|
|
575
726
|
D(JSON.parse(String(e.data)));
|
|
576
727
|
} catch {}
|
|
577
|
-
}, h.onerror = (e) =>
|
|
578
|
-
m ||
|
|
728
|
+
}, h.onerror = (e) => v("error", e), h.onclose = () => {
|
|
729
|
+
m || v("idle");
|
|
579
730
|
};
|
|
580
731
|
let g = await p.createOffer();
|
|
581
732
|
await p.setLocalDescription(g);
|
|
582
|
-
let
|
|
733
|
+
let _ = await r(e.callsUrl ?? y, {
|
|
583
734
|
method: "POST",
|
|
584
735
|
body: g.sdp,
|
|
585
736
|
headers: {
|
|
@@ -587,16 +738,16 @@ function C(e) {
|
|
|
587
738
|
"Content-Type": "application/sdp"
|
|
588
739
|
}
|
|
589
740
|
});
|
|
590
|
-
if (!
|
|
591
|
-
let e = await
|
|
592
|
-
throw Error(`[orb-ui/openai-realtime] Session negotiation failed (${
|
|
741
|
+
if (!_.ok) {
|
|
742
|
+
let e = await _.text();
|
|
743
|
+
throw Error(`[orb-ui/openai-realtime] Session negotiation failed (${_.status}): ${e}`);
|
|
593
744
|
}
|
|
594
745
|
await p.setRemoteDescription({
|
|
595
746
|
type: "answer",
|
|
596
|
-
sdp: await
|
|
747
|
+
sdp: await _.text()
|
|
597
748
|
});
|
|
598
749
|
} catch (e) {
|
|
599
|
-
throw await O(!1),
|
|
750
|
+
throw await O(!1), v("error", e), e;
|
|
600
751
|
}
|
|
601
752
|
}
|
|
602
753
|
},
|
|
@@ -607,13 +758,13 @@ function C(e) {
|
|
|
607
758
|
}
|
|
608
759
|
//#endregion
|
|
609
760
|
//#region src/adapters/gemini-live/index.ts
|
|
610
|
-
var
|
|
611
|
-
function
|
|
761
|
+
var E = 16e3;
|
|
762
|
+
function D(e) {
|
|
612
763
|
let t = 0;
|
|
613
764
|
for (let n of e) t += n * n;
|
|
614
765
|
return Math.sqrt(t / e.length);
|
|
615
766
|
}
|
|
616
|
-
function
|
|
767
|
+
function O(e, t, n) {
|
|
617
768
|
if (t === n) return e;
|
|
618
769
|
let r = t / n, i = Math.max(1, Math.round(e.length / r)), a = new Float32Array(i);
|
|
619
770
|
for (let t = 0; t < i; t += 1) {
|
|
@@ -622,7 +773,7 @@ function E(e, t, n) {
|
|
|
622
773
|
}
|
|
623
774
|
return a;
|
|
624
775
|
}
|
|
625
|
-
function
|
|
776
|
+
function k(e) {
|
|
626
777
|
let t = new Uint8Array(e.length * 2), n = new DataView(t.buffer);
|
|
627
778
|
e.forEach((e, t) => {
|
|
628
779
|
let r = Math.max(-1, Math.min(1, e));
|
|
@@ -633,18 +784,18 @@ function D(e) {
|
|
|
633
784
|
r += String.fromCharCode(e);
|
|
634
785
|
}), btoa(r);
|
|
635
786
|
}
|
|
636
|
-
function
|
|
787
|
+
function A(e) {
|
|
637
788
|
let t = atob(e), n = new Uint8Array(t.length);
|
|
638
789
|
for (let e = 0; e < t.length; e += 1) n[e] = t.charCodeAt(e);
|
|
639
790
|
let r = new DataView(n.buffer), i = new Float32Array(Math.floor(n.length / 2));
|
|
640
791
|
for (let e = 0; e < i.length; e += 1) i[e] = r.getInt16(e * 2, !0) / 32768;
|
|
641
792
|
return i;
|
|
642
793
|
}
|
|
643
|
-
function
|
|
794
|
+
function j(e) {
|
|
644
795
|
let t = e?.match(/rate=(\d+)/i);
|
|
645
796
|
return t ? Number(t[1]) : 24e3;
|
|
646
797
|
}
|
|
647
|
-
function
|
|
798
|
+
function M(e) {
|
|
648
799
|
let t = /* @__PURE__ */ new Set(), n = /* @__PURE__ */ new Set(), a = {
|
|
649
800
|
state: "idle",
|
|
650
801
|
inputVolume: 0,
|
|
@@ -669,14 +820,14 @@ function A(e) {
|
|
|
669
820
|
...t === void 0 ? {} : { error: t }
|
|
670
821
|
});
|
|
671
822
|
}
|
|
672
|
-
function
|
|
823
|
+
function w() {
|
|
673
824
|
m &&= (clearTimeout(m), null);
|
|
674
825
|
}
|
|
675
|
-
function
|
|
826
|
+
function T(t) {
|
|
676
827
|
let n = y.sample(t);
|
|
677
828
|
e.onInputVolumeSample?.(n);
|
|
678
829
|
let r = n.normalized, i = e.speechThreshold ?? .04;
|
|
679
|
-
n.mapped > i ? (!h && x() && o?.sendRealtimeInput({ activityStart: {} }), h = !0,
|
|
830
|
+
n.mapped > i ? (!h && x() && o?.sendRealtimeInput({ activityStart: {} }), h = !0, w(), a.state !== "listening" && C("listening")) : h && !m && (m = setTimeout(() => {
|
|
680
831
|
m = null, h = !1, x() && o?.sendRealtimeInput({ activityEnd: {} }), a.state === "listening" && C("thinking");
|
|
681
832
|
}, e.speechEndDelayMs ?? 500)), S({
|
|
682
833
|
...a,
|
|
@@ -696,7 +847,7 @@ function A(e) {
|
|
|
696
847
|
}
|
|
697
848
|
function P(e) {
|
|
698
849
|
if (!c || !f || !e.data) return;
|
|
699
|
-
let t =
|
|
850
|
+
let t = A(e.data), r = c.createBuffer(1, t.length, j(e.mimeType));
|
|
700
851
|
r.getChannelData(0).set(t);
|
|
701
852
|
let i = c.createBufferSource();
|
|
702
853
|
i.buffer = r, i.connect(f);
|
|
@@ -722,7 +873,7 @@ function A(e) {
|
|
|
722
873
|
p = setInterval(() => {
|
|
723
874
|
if (!f) return;
|
|
724
875
|
f.getFloatTimeDomainData(t);
|
|
725
|
-
let n = b.sample(
|
|
876
|
+
let n = b.sample(D(t));
|
|
726
877
|
e.onOutputVolumeSample?.(n), S({
|
|
727
878
|
...a,
|
|
728
879
|
outputVolume: n.normalized
|
|
@@ -733,16 +884,16 @@ function A(e) {
|
|
|
733
884
|
!c || !s || !o || (l = c.createMediaStreamSource(s), u = c.createScriptProcessor(4096, 1, 1), d = c.createGain(), d.gain.value = 0, l.connect(u), u.connect(d), d.connect(c.destination), u.onaudioprocess = (t) => {
|
|
734
885
|
if (!o || v) return;
|
|
735
886
|
let n = t.inputBuffer.getChannelData(0);
|
|
736
|
-
|
|
737
|
-
let r =
|
|
887
|
+
T(D(n));
|
|
888
|
+
let r = O(n, c?.sampleRate ?? E, e.inputSampleRate ?? E);
|
|
738
889
|
o.sendRealtimeInput({ audio: {
|
|
739
|
-
data:
|
|
740
|
-
mimeType: `audio/pcm;rate=${e.inputSampleRate ??
|
|
890
|
+
data: k(r),
|
|
891
|
+
mimeType: `audio/pcm;rate=${e.inputSampleRate ?? E}`
|
|
741
892
|
} });
|
|
742
893
|
});
|
|
743
894
|
}
|
|
744
895
|
async function R(e) {
|
|
745
|
-
v = !0,
|
|
896
|
+
v = !0, w(), p && clearInterval(p), p = null, M(), u?.disconnect(), l?.disconnect(), d?.disconnect(), f?.disconnect(), u = null, l = null, d = null, f = null, s?.getTracks().forEach((e) => e.stop()), s = null, c && c.state !== "closed" && await c.close(), c = null, o = null, h = !1, _ = !1, y.reset(), b.reset(), e && C("idle"), v = !1;
|
|
746
897
|
}
|
|
747
898
|
return {
|
|
748
899
|
subscribe(e) {
|
|
@@ -776,4 +927,4 @@ function A(e) {
|
|
|
776
927
|
};
|
|
777
928
|
}
|
|
778
929
|
//#endregion
|
|
779
|
-
export { a as DEFAULT_VOLUME_CALIBRATION, r as PROVIDER_VOLUME_CALIBRATIONS, n as calibrateVolume, d as createElevenLabsAdapter,
|
|
930
|
+
export { a as DEFAULT_VOLUME_CALIBRATION, r as PROVIDER_VOLUME_CALIBRATIONS, n as calibrateVolume, d as createElevenLabsAdapter, M as createGeminiLiveAdapter, s as createLiveKitAdapter, v as createOpenAILiveAdapter, T as createOpenAIRealtimeAdapter, g as createPipecatAdapter, u as createVapiAdapter, i as createVolumeNormalizer, o as fitVolumeCalibration, t as mapVolumeAmplitude };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "orb-ui",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "React voice agent UI components with audio-reactive adapters for Vapi, ElevenLabs, LiveKit, Pipecat, OpenAI Realtime, Gemini Live, and custom voice AI apps.",
|
|
3
|
+
"version": "0.9.0",
|
|
4
|
+
"description": "React voice agent UI components with audio-reactive adapters for Vapi, ElevenLabs, LiveKit, Pipecat, OpenAI Live, OpenAI Realtime, Gemini Live, and custom voice AI apps.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/orb-ui.cjs",
|
|
7
7
|
"module": "./dist/orb-ui.js",
|
|
@@ -80,6 +80,7 @@
|
|
|
80
80
|
"elevenlabs",
|
|
81
81
|
"livekit",
|
|
82
82
|
"pipecat",
|
|
83
|
+
"openai-live",
|
|
83
84
|
"openai-realtime",
|
|
84
85
|
"gemini-live"
|
|
85
86
|
],
|
|
@@ -88,7 +89,7 @@
|
|
|
88
89
|
"homepage": "https://orb-ui.com",
|
|
89
90
|
"repository": {
|
|
90
91
|
"type": "git",
|
|
91
|
-
"url": "https://github.com/
|
|
92
|
+
"url": "https://github.com/exprmntl/orb-ui.git"
|
|
92
93
|
},
|
|
93
94
|
"typesVersions": {
|
|
94
95
|
"*": {
|