orb-ui 0.5.0 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -20
- package/dist/adapters/audio-level.d.ts +5 -0
- package/dist/adapters/index.d.ts +1 -1
- package/dist/adapters/livekit/browser.d.ts +5 -0
- package/dist/adapters/livekit/index.d.ts +9 -2
- package/dist/adapters/pipecat/index.d.ts +16 -0
- package/dist/adapters.cjs +1 -1
- package/dist/adapters.js +260 -241
- package/dist/components/Orb/Orb.d.ts +1 -1
- package/dist/components/Orb/Orb.types.d.ts +6 -1
- package/dist/livekit-CukEeYFK.js +316 -0
- package/dist/livekit-Dt-QZ6Gs.cjs +1 -0
- package/dist/livekit-adapter.cjs +1 -1
- package/dist/livekit-adapter.js +4 -2
- package/dist/orb-ui.cjs +101 -1
- package/dist/orb-ui.js +279 -34
- package/dist/themes/cloud/CloudTheme.d.ts +14 -0
- package/dist/themes/cloud/index.d.ts +1 -0
- package/dist/themes/index.d.ts +1 -0
- package/package.json +1 -1
- package/dist/livekit-Dasur3lv.js +0 -240
- package/dist/livekit-Ro6A52eb.cjs +0 -1
package/README.md
CHANGED
|
@@ -9,7 +9,7 @@ React voice agent UI components for Vapi, ElevenLabs, LiveKit, Pipecat, OpenAI R
|
|
|
9
9
|
</p>
|
|
10
10
|
|
|
11
11
|
<p align="center">
|
|
12
|
-
<a href="https://orb-ui.com">Live Demo</a> · <a href="https://orb-ui.com/docs/guides/voice-agent-ui">
|
|
12
|
+
<a href="https://orb-ui.com">Live Demo</a> · <a href="https://orb-ui.com/docs/adapters/overview">Adapter Guide</a> · <a href="https://orb-ui.com/docs/guides/signal-based-voice-agent-ui">Signal Architecture</a> · <a href="https://www.npmjs.com/package/orb-ui">npm</a> · <a href="https://github.com/alexanderqchen/orb-ui">GitHub</a>
|
|
13
13
|
</p>
|
|
14
14
|
|
|
15
15
|
```jsx
|
|
@@ -131,8 +131,8 @@ function App() {
|
|
|
131
131
|
```
|
|
132
132
|
|
|
133
133
|
The LiveKit entrypoint creates the room and token source, assigns a fresh room name, and meters both
|
|
134
|
-
sides of the conversation
|
|
135
|
-
advanced `orb-ui/adapters` entrypoint.
|
|
134
|
+
sides of the conversation with speech-oriented analyser and smoothing defaults. Existing-room and
|
|
135
|
+
custom-runtime modes remain available from the advanced `orb-ui/adapters` entrypoint.
|
|
136
136
|
|
|
137
137
|
### With Pipecat
|
|
138
138
|
|
|
@@ -152,8 +152,9 @@ function App() {
|
|
|
152
152
|
}
|
|
153
153
|
```
|
|
154
154
|
|
|
155
|
-
The Pipecat adapter consumes the standard RTVI event surface
|
|
156
|
-
|
|
155
|
+
The Pipecat adapter consumes the standard RTVI event surface and meters the client media tracks as
|
|
156
|
+
a browser fallback, so it works with Pipecat Cloud, Daily, SmallWebRTC, and transports that emit
|
|
157
|
+
sparse audio-level events. See the [Pipecat guide](https://orb-ui.com/docs/adapters/pipecat).
|
|
157
158
|
|
|
158
159
|
### With OpenAI Realtime
|
|
159
160
|
|
|
@@ -225,32 +226,51 @@ function App() {
|
|
|
225
226
|
}
|
|
226
227
|
```
|
|
227
228
|
|
|
229
|
+
### External session controls
|
|
230
|
+
|
|
231
|
+
Keep the orb as a passive visual when start and stop controls belong elsewhere in your layout.
|
|
232
|
+
Provider adapters already expose the matching lifecycle methods.
|
|
233
|
+
|
|
234
|
+
```jsx
|
|
235
|
+
function VoiceExperience({ adapter }) {
|
|
236
|
+
return (
|
|
237
|
+
<>
|
|
238
|
+
<Orb adapter={adapter} theme="cloud" interactive={false} />
|
|
239
|
+
<button onClick={() => void adapter.start?.()}>Start conversation</button>
|
|
240
|
+
<button onClick={() => void adapter.stop?.()}>End conversation</button>
|
|
241
|
+
</>
|
|
242
|
+
)
|
|
243
|
+
}
|
|
244
|
+
```
|
|
245
|
+
|
|
228
246
|
## Themes
|
|
229
247
|
|
|
230
248
|
| Theme | Description |
|
|
231
249
|
| -------- | ----------------------------------------------------------------------------- |
|
|
250
|
+
| `cloud` | Atmospheric sphere with inverse listening scale and faster speaking motion. |
|
|
232
251
|
| `debug` | State + volume display with start/stop. Use to verify your integration works. |
|
|
233
252
|
| `circle` | Pulsing circle that reacts to volume. |
|
|
234
253
|
| `bars` | Five bars that animate with voice. |
|
|
235
254
|
|
|
236
|
-
When an adapter or `onStart`/`onStop` handler is provided,
|
|
255
|
+
When an adapter or `onStart`/`onStop` handler is provided, visual themes render as keyboard-accessible `<button type="button">` controls. Pass `interactive={false}` to keep the theme passive and call `adapter.start()` or `adapter.stop()` from external controls instead.
|
|
237
256
|
|
|
238
257
|
## Props
|
|
239
258
|
|
|
240
|
-
| Prop
|
|
241
|
-
|
|
|
242
|
-
| `theme`
|
|
243
|
-
| `signal`
|
|
244
|
-
| `state`
|
|
245
|
-
| `volume`
|
|
246
|
-
| `adapter`
|
|
247
|
-
| `size`
|
|
248
|
-
| `className`
|
|
249
|
-
| `style`
|
|
250
|
-
| `disabled`
|
|
251
|
-
| `
|
|
252
|
-
| `
|
|
253
|
-
| `
|
|
259
|
+
| Prop | Type | Default | Description |
|
|
260
|
+
| ------------- | ------------------------------------------ | --------- | ------------------------------------------------------- |
|
|
261
|
+
| `theme` | `'debug' \| 'circle' \| 'bars' \| 'cloud'` | `'debug'` | Visual theme |
|
|
262
|
+
| `signal` | `OrbSignal` | — | Rich controlled signal with state/input/output volume |
|
|
263
|
+
| `state` | `OrbState` | `'idle'` | Conversation state (controlled mode) |
|
|
264
|
+
| `volume` | `number` | `0` | Audio volume, 0–1. Overrides signal/adapter volume. |
|
|
265
|
+
| `adapter` | `OrbAdapter` | — | Provider adapter (manages signal updates automatically) |
|
|
266
|
+
| `size` | `number` | `200` | Size in pixels |
|
|
267
|
+
| `className` | `string` | — | Optional class name for the rendered theme |
|
|
268
|
+
| `style` | `React.CSSProperties` | — | Optional inline styles for the rendered theme |
|
|
269
|
+
| `disabled` | `boolean` | `false` | Disables clickable themes and debug start/stop controls |
|
|
270
|
+
| `interactive` | `boolean` | `true` | Allows the orb itself to start and stop a session |
|
|
271
|
+
| `aria-label` | `string` | generated | Accessible label for clickable visual themes |
|
|
272
|
+
| `onStart` | `() => void` | — | Custom start handler (overrides adapter.start()) |
|
|
273
|
+
| `onStop` | `() => void` | — | Custom stop handler (overrides adapter.stop()) |
|
|
254
274
|
|
|
255
275
|
## States
|
|
256
276
|
|
|
@@ -19,5 +19,10 @@ export interface OutputVolumeSample {
|
|
|
19
19
|
/** Final value after attack/release smoothing. */
|
|
20
20
|
normalized: number;
|
|
21
21
|
}
|
|
22
|
+
export interface MediaStreamTrackVolumeMeter {
|
|
23
|
+
stop(): Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
export type AudioContextSource = () => AudioContext | undefined;
|
|
22
26
|
export declare const DEFAULT_OUTPUT_VOLUME_CALIBRATION: OutputVolumeCalibration;
|
|
23
27
|
export declare function calibrateOutputVolume(rawValue: number, previous: number, source?: OutputVolumeCalibrationSource): OutputVolumeSample;
|
|
28
|
+
export declare function createMediaStreamTrackVolumeMeter(track: MediaStreamTrack, createAudioContext: AudioContextSource, onVolume: (volume: number) => void): MediaStreamTrackVolumeMeter | undefined;
|
package/dist/adapters/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { createVapiAdapter } 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
|
-
export { createPipecatAdapter, type PipecatAdapterOptions, type PipecatClientLike, type PipecatOrbAdapter, type PipecatParticipantLike, } from './pipecat/index.js';
|
|
4
|
+
export { createPipecatAdapter, type PipecatAdapterOptions, type PipecatClientLike, type PipecatOrbAdapter, type PipecatParticipantLike, type PipecatTracksLike, } from './pipecat/index.js';
|
|
5
5
|
export { createOpenAIRealtimeAdapter, type OpenAIRealtimeAdapterConfig, type OpenAIRealtimeClientSecret, type OpenAIRealtimeOrbAdapter, } from './openai-realtime/index.js';
|
|
6
6
|
export { createGeminiLiveAdapter, type GeminiLiveAdapterConfig, type GeminiLiveCallbacks, type GeminiLiveInlineData, type GeminiLiveOrbAdapter, type GeminiLiveServerMessage, type GeminiLiveSession, } from './gemini-live/index.js';
|
|
7
7
|
export { DEFAULT_OUTPUT_VOLUME_CALIBRATION, type OutputVolumeCalibration, type OutputVolumeCalibrationSource, type OutputVolumeSample, } from './audio-level.js';
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { LiveKitOrbAdapter, LiveKitTokenOptions } from './index.js';
|
|
2
|
+
import { OutputVolumeCalibrationSource, OutputVolumeSample } from '../audio-level.js';
|
|
2
3
|
interface LiveKitBrowserAdapterBase extends Omit<LiveKitTokenOptions, 'agentName' | 'roomName'> {
|
|
3
4
|
/** Agent dispatched into the room. Required for LiveKit Cloud sandbox sessions. */
|
|
4
5
|
agentName?: LiveKitTokenOptions['agentName'];
|
|
@@ -8,6 +9,10 @@ interface LiveKitBrowserAdapterBase extends Omit<LiveKitTokenOptions, 'agentName
|
|
|
8
9
|
connectOptions?: Record<string, unknown>;
|
|
9
10
|
/** Enable the local microphone after connecting. Defaults to true. */
|
|
10
11
|
enableMicrophone?: boolean;
|
|
12
|
+
/** Optional live-tunable output shaping. A getter is read for every meter sample. */
|
|
13
|
+
outputVolumeCalibration?: OutputVolumeCalibrationSource;
|
|
14
|
+
/** Receives raw, shaped, and smoothed output levels for diagnostics. */
|
|
15
|
+
onOutputVolumeSample?: (sample: OutputVolumeSample) => void;
|
|
11
16
|
}
|
|
12
17
|
export type LiveKitTokenEndpointOptions = Omit<RequestInit, 'body'>;
|
|
13
18
|
export interface LiveKitSandboxOptions {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { OrbAdapter } from '../types.js';
|
|
2
|
+
import { OutputVolumeCalibrationSource, OutputVolumeSample } from '../audio-level.js';
|
|
2
3
|
interface LKAnalyserResult {
|
|
3
4
|
calculateVolume: () => number;
|
|
4
5
|
cleanup: () => Promise<void>;
|
|
@@ -67,7 +68,13 @@ export interface LiveKitTokenOptions {
|
|
|
67
68
|
export interface LiveKitTokenSource {
|
|
68
69
|
fetch(options?: LiveKitResolvedTokenOptions, force?: boolean): Promise<LiveKitConnectionDetails>;
|
|
69
70
|
}
|
|
70
|
-
interface
|
|
71
|
+
interface LiveKitVolumeConfig {
|
|
72
|
+
/** Optional live-tunable output shaping. A getter is read for every meter sample. */
|
|
73
|
+
outputVolumeCalibration?: OutputVolumeCalibrationSource;
|
|
74
|
+
/** Receives raw, shaped, and smoothed output levels for diagnostics. */
|
|
75
|
+
onOutputVolumeSample?: (sample: OutputVolumeSample) => void;
|
|
76
|
+
}
|
|
77
|
+
interface LiveKitManagedBaseConfig<TTrack = unknown> extends LiveKitVolumeConfig {
|
|
71
78
|
/** The createAudioAnalyser function from livekit-client. */
|
|
72
79
|
createAudioAnalyser: LKCreateAudioAnalyser<TTrack>;
|
|
73
80
|
/** The Room constructor from livekit-client. */
|
|
@@ -80,7 +87,7 @@ interface LiveKitManagedBaseConfig<TTrack = unknown> {
|
|
|
80
87
|
tokenOptions?: LiveKitTokenOptions;
|
|
81
88
|
}
|
|
82
89
|
/** App-managed mode: subscribe to a pre-existing Room. */
|
|
83
|
-
interface LiveKitRoomConfig<TTrack = unknown> {
|
|
90
|
+
interface LiveKitRoomConfig<TTrack = unknown> extends LiveKitVolumeConfig {
|
|
84
91
|
/** A connected Room instance from livekit-client. */
|
|
85
92
|
room: LKRoom;
|
|
86
93
|
/** The createAudioAnalyser function from livekit-client. */
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { OrbAdapter } from '../types.js';
|
|
2
|
+
import { AudioContextSource, OutputVolumeCalibrationSource, OutputVolumeSample } from '../audio-level.js';
|
|
2
3
|
type PipecatListener = (...args: unknown[]) => void;
|
|
3
4
|
/** Minimal PipecatClient surface used by orb-ui. */
|
|
4
5
|
export interface PipecatClientLike {
|
|
@@ -8,12 +9,21 @@ export interface PipecatClientLike {
|
|
|
8
9
|
connect(...args: unknown[]): Promise<unknown>;
|
|
9
10
|
disconnect(): void | Promise<void>;
|
|
10
11
|
state?: string;
|
|
12
|
+
tracks?(): PipecatTracksLike;
|
|
11
13
|
}
|
|
12
14
|
export interface PipecatParticipantLike {
|
|
13
15
|
id?: string;
|
|
14
16
|
name?: string;
|
|
15
17
|
local?: boolean;
|
|
16
18
|
}
|
|
19
|
+
export interface PipecatTracksLike {
|
|
20
|
+
local?: {
|
|
21
|
+
audio?: MediaStreamTrack;
|
|
22
|
+
};
|
|
23
|
+
bot?: {
|
|
24
|
+
audio?: MediaStreamTrack;
|
|
25
|
+
};
|
|
26
|
+
}
|
|
17
27
|
export interface PipecatAdapterOptions {
|
|
18
28
|
/**
|
|
19
29
|
* Starts and connects the Pipecat client. Override this for transport-specific
|
|
@@ -31,6 +41,12 @@ export interface PipecatAdapterOptions {
|
|
|
31
41
|
playRemoteAudio?: boolean;
|
|
32
42
|
/** Runtime override for custom audio element ownership. */
|
|
33
43
|
createAudioElement?: () => HTMLAudioElement;
|
|
44
|
+
/** Return undefined to disable browser-track volume metering. */
|
|
45
|
+
createAudioContext?: AudioContextSource;
|
|
46
|
+
/** Optional live-tunable output shaping. A getter is read for every meter sample. */
|
|
47
|
+
outputVolumeCalibration?: OutputVolumeCalibrationSource;
|
|
48
|
+
/** Receives raw, shaped, and smoothed output levels for diagnostics. */
|
|
49
|
+
onOutputVolumeSample?: (sample: OutputVolumeSample) => void;
|
|
34
50
|
}
|
|
35
51
|
export interface PipecatOrbAdapter extends OrbAdapter {
|
|
36
52
|
start(): Promise<void>;
|
package/dist/adapters.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./livekit-Ro6A52eb.cjs");var t=.12;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(e,r){let i=new Set,a=null;function o(){a||(a=e.start.bind(e),e.start=async(...e)=>(i.forEach(e=>e()),a(...e)))}function s(){i.size>0||!a||(e.start=a,a=null)}return{async start(){await e.start(r?.assistantId)},stop(){e.stop()},subscribe(r){let a={state:`idle`,volume:0,outputVolume:0},c=0;function l(e){let n=e<t?0:(e-t)/(1-t),r=n>c?.8:.5;return c+=(n-c)*r,c}function u(e){a=e,r(e)}function d(e){u({...a,...e,state:e.state??a.state})}let{emitState:f,clearTimer:p}=n(e=>d({state:e})),m=()=>f(`connecting`),h=`idle`,g=!1,_=()=>{g=!0,h=`listening`,f(`listening`),d({volume:0,outputVolume:0})},v=()=>{g=!1,h=`idle`,E(),f(`idle`),d({volume:0,outputVolume:0}),c=0},y=()=>{g&&(h=`speaking`,f(`speaking`),d({volume:0,outputVolume:0}),T())},b=()=>{g&&(E(),h=`listening`,d({volume:0,outputVolume:0}),c=0,f(`listening`))},x=0,S=0,C=0,w=()=>{h===`speaking`&&(S+=(x-S)*.1,d({volume:S,outputVolume:S})),C=requestAnimationFrame(w)},T=()=>{C||=requestAnimationFrame(w)},E=()=>{C&&=(cancelAnimationFrame(C),0),S=0,x=0},D=e=>{if(h===`speaking`){let t=l(e);x=t/(t+.3)}},O=()=>{},k=e=>{console.error(`[orb-ui/vapi] Error:`,e),g=!1,h=`error`,p(),E(),d({state:`error`,volume:0,outputVolume:0,error:e}),c=0};return e.on(`call-start`,_),e.on(`call-end`,v),e.on(`speech-start`,y),e.on(`speech-end`,b),e.on(`volume-level`,D),e.on(`message`,O),e.on(`error`,k),i.add(m),o(),()=>{p(),E(),c=0,e.removeListener(`call-start`,_),e.removeListener(`call-end`,v),e.removeListener(`speech-start`,y),e.removeListener(`speech-end`,b),e.removeListener(`volume-level`,D),e.removeListener(`message`,O),e.removeListener(`error`,k),i.delete(m),s()}}}}function i(e,t){let n=null,r=0,i=null,a=null,o={state:`idle`,volume:0,inputVolume:0,outputVolume:0},s=`idle`,c=new Set;function l(e){o=e,c.forEach(t=>t(e))}function u(e){o={...o,...e,state:e.state??o.state},l(o)}function d(e){s=e,u({state:e})}function f(){a||=setInterval(()=>{if(n){if(s===`listening`){let e=Math.min(n.getInputVolume()*2,1);u({volume:e,inputVolume:e})}else if(s===`speaking`){let e=Math.min(n.getOutputVolume()*2,1);u({volume:e,outputVolume:e})}}},33)}function p(){a&&=(clearInterval(a),null)}function m(){p(),u({volume:0,inputVolume:0,outputVolume:0})}function h(){s=`idle`,u({state:`idle`,volume:0,inputVolume:0,outputVolume:0})}function g(e){return e===r}function _(e){return{onStatusChange:({status:t})=>{g(e)&&t===`connecting`&&d(`connecting`)},onConnect:()=>{g(e)&&(d(`listening`),f())},onModeChange:({mode:t})=>{g(e)&&(t===`speaking`?(d(`speaking`),f()):(d(`listening`),f()))},onDisconnect:()=>{g(e)&&(p(),n=null,h())},onError:t=>{g(e)&&(console.error(`[orb-ui/elevenlabs] Error:`,t),p(),s=`error`,u({state:`error`,volume:0,inputVolume:0,outputVolume:0,error:t}),n=null)}}}return{subscribe(e){return c.add(e),e(o),n&&(s===`listening`||s===`speaking`)&&f(),()=>{c.delete(e),c.size===0&&m()}},async start(){if(n||i)return i??void 0;r+=1;let a=r;return i=(async()=>{try{let r=await e.startSession({...t,..._(a)});if(!g(a)){await r.endSession().catch(e=>{console.error(`[orb-ui/elevenlabs] stale session cleanup failed:`,e)});return}n=r}catch(e){if(!g(a))return;console.error(`[orb-ui/elevenlabs] startSession failed:`,e),d(`error`),u({volume:0,inputVolume:0,outputVolume:0,error:e})}finally{i=null}})(),i},async stop(){let e=n;if(!e){i&&(r+=1,p(),h(),await i);return}let t=r;p();try{await e.endSession()}catch(e){console.error(`[orb-ui/elevenlabs] endSession failed:`,e)}n===e&&g(t)&&(n=null,h())}}}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`},o=.002,s=4,c=.8,l=.6,u=.2;function d(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 f(e){if(typeof e!=`number`||!Number.isFinite(e)||e<=o)return 0;let t=Math.min(1,Math.max(0,e-o));return Math.min(1,t*s)**+c}function p(e,t){let n=f(e),r=n>t?l:u;return t+(n-t)*r}function m(e){return typeof e==`object`&&!!e&&`kind`in e&&typeof e.kind==`string`}function h(e,t={}){let n=new Set,r=new Map,i={state:d(e.state??``)??`idle`,volume:0,inputVolume:0,outputVolume:0},o=!1,s=0,c=0;function l(e){i=e,n.forEach(t=>t(e))}function u(e,t){s=0,c=0,l({state:e,volume:0,inputVolume:0,outputVolume:0,...t===void 0?{}:{error:t}})}function f(e){if(i.state!==`listening`)return;s=p(e,s);let t=s;l({...i,volume:t,inputVolume:t,outputVolume:0})}function h(e,n){if(i.state!==`speaking`)return;if(n&&typeof n==`object`){let e=n;if(e.local||t.isBotParticipant&&!t.isBotParticipant(e))return}c=p(e,c);let r=c;l({...i,volume:r,inputVolume:0,outputVolume:r})}function g(e){if(!e||typeof e!=`object`)return!0;let n=e;return n.local?!1:t.isBotParticipant?.(n)??!0}function _(e,n){if(t.playRemoteAudio===!1||!m(e)||e.kind!==`audio`||!g(n))return;let i=t.createAudioElement?.()??new Audio;i.autoplay=!0,i.srcObject=new MediaStream([e]),r.set(e,i),i.play().catch(()=>void 0)}function v(e){if(!m(e))return;let t=r.get(e);t&&(t.pause(),t.srcObject=null,t.remove(),r.delete(e))}function y(){r.forEach(e=>{e.pause(),e.srcObject=null,e.remove()}),r.clear()}let b=[[a.connected,()=>u(`connecting`)],[a.botReady,()=>u(`listening`)],[a.disconnected,()=>u(`idle`)],[a.botDisconnected,()=>u(`idle`)],[a.transportStateChanged,e=>{if(typeof e!=`string`)return;let t=d(e);t&&u(t)}],[a.userStartedSpeaking,()=>u(`listening`)],[a.userStoppedSpeaking,()=>{i.state===`listening`&&u(`thinking`)}],[a.botLlmStarted,()=>u(`thinking`)],[a.botTtsStarted,()=>u(`thinking`)],[a.botStartedSpeaking,()=>u(`speaking`)],[a.botStoppedSpeaking,()=>u(`listening`)],[a.localAudioLevel,f],[a.remoteAudioLevel,h],[`trackStarted`,_],[`trackStopped`,v],[a.error,e=>u(`error`,e)],[a.messageError,e=>u(`error`,e)],[a.deviceError,e=>u(`error`,e)]];function x(){o||(o=!0,b.forEach(([t,n])=>e.on(t,n)))}function S(){o&&(o=!1,b.forEach(([t,n])=>{e.off?e.off(t,n):e.removeListener?.(t,n)}),y())}return{subscribe(e){return n.add(e),x(),e(i),()=>{n.delete(e),n.size===0&&S()}},async start(){u(`connecting`);try{await(t.connect?t.connect():e.connect())}catch(e){throw u(`error`,e),e}},async stop(){try{await(t.disconnect?t.disconnect():e.disconnect())}finally{y(),u(`idle`)}}}}var g={noiseFloor:0,gain:4,exponent:.8,attack:1,release:1};function _(e,t,n){return Math.min(n,Math.max(t,e))}function v(e,t){return typeof e==`number`&&Number.isFinite(e)?e:t}function y(e){let t=typeof e==`function`?e():e;return{noiseFloor:_(v(t?.noiseFloor,g.noiseFloor),0,1),gain:Math.max(0,v(t?.gain,g.gain)),exponent:Math.max(.01,v(t?.exponent,g.exponent)),attack:_(v(t?.attack,g.attack),0,1),release:_(v(t?.release,g.release),0,1)}}function b(e,t,n){let r=Number.isFinite(e)?_(e,0,1):0,i=y(n),a=_((r<=i.noiseFloor?0:r-i.noiseFloor)*i.gain,0,1)**+i.exponent,o=a>t?i.attack:i.release;return{raw:r,shaped:a,normalized:_(t+(a-t)*o,0,1)}}var x=`https://api.openai.com/v1/realtime/calls`,S=.015,C=8,w={noiseFloor:.003,gain:4,exponent:.8,attack:.55,release:.1};function T(){let e=window.AudioContext;return e?new e:void 0}function E(e){return Math.min(1,Math.max(0,(e*4)**.8))}function D(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 O(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 k(e){let t=new Set,n={state:`idle`,volume:0,inputVolume:0,outputVolume:0},r=null,i=null,a=null,o=null,s,c,l=0,u=0,d=!1;function f(){let t=typeof e.outputVolumeCalibration==`function`?e.outputVolumeCalibration():e.outputVolumeCalibration;return{...w,...t}}function p(e){n=e,t.forEach(t=>t(e))}function m(e,t){n.state===e&&t===void 0||(e!==`speaking`&&(u=0),p({state:e,volume:0,inputVolume:0,outputVolume:0,...t===void 0?{}:{error:t}}))}function h(e){if(n.state!==`listening`)return;let t=E(e);p({...n,volume:t,inputVolume:t,outputVolume:0})}function g(t){let r=b(t,u,f);u=r.normalized,e.onOutputVolumeSample?.(r);let i=r.normalized;if(i>S)l=0,n.state!==`speaking`&&m(`speaking`);else if(n.state===`speaking`&&(l+=1,l>=C)){l=0,m(`listening`);return}n.state===`speaking`&&p({...n,volume:i,inputVolume:0,outputVolume:i})}function _(e){switch(e.type){case`session.created`:case`session.updated`:m(`listening`);break;case`input_audio_buffer.speech_started`:m(`listening`);break;case`input_audio_buffer.speech_stopped`:case`response.created`:m(`thinking`);break;case`response.output_audio.delta`:case`output_audio_buffer.started`:m(`speaking`);break;case`output_audio_buffer.stopped`:m(`listening`);break;case`response.done`:case`response.cancelled`:n.state!==`speaking`&&m(`listening`);break;case`error`:m(`error`,e.error??e);break}}async function v(e){d=!0,i?.close(),i=null,r?.close(),r=null,a?.getTracks().forEach(e=>e.stop()),a=null,o?.pause(),o&&(o.srcObject=null),o?.remove(),o=null,await Promise.all([s?.stop(),c?.stop()]),s=void 0,c=void 0,l=0,u=0,e&&m(`idle`),d=!1}return{subscribe(e){return t.add(e),e(n),()=>t.delete(e)},async start(){if(!r){m(`connecting`),d=!1;try{let t=e.getUserMedia??(e=>navigator.mediaDevices.getUserMedia(e)),n=e.createPeerConnection??(()=>new RTCPeerConnection),l=e.fetch??fetch,u=e.createAudioElement??(()=>new Audio),f=e.createAudioContext??T,p=O(await e.getClientSecret());a=await t(e.mediaStreamConstraints??{audio:!0}),s=D(a,f,h);let v=n();r=v,a.getAudioTracks().forEach(e=>v.addTrack(e,a)),o=u(),o.autoplay=!0,v.ontrack=e=>{let t=e.streams[0]??new MediaStream([e.track]);o&&(o.srcObject=t),o?.play().catch(()=>void 0),c?.stop(),c=D(t,f,g)},v.onconnectionstatechange=()=>{d||(v.connectionState===`failed`?m(`error`,Error(`[orb-ui/openai-realtime] WebRTC connection failed.`)):(v.connectionState===`disconnected`||v.connectionState===`closed`)&&m(`idle`))};let y=v.createDataChannel(`oai-events`);i=y,y.onopen=()=>m(`listening`),y.onmessage=e=>{try{_(JSON.parse(String(e.data)))}catch{}},y.onerror=e=>m(`error`,e),y.onclose=()=>{d||m(`idle`)};let b=await v.createOffer();await v.setLocalDescription(b);let S=await l(e.callsUrl??x,{method:`POST`,body:b.sdp,headers:{Authorization:`Bearer ${p}`,"Content-Type":`application/sdp`}});if(!S.ok){let e=await S.text();throw Error(`[orb-ui/openai-realtime] Session negotiation failed (${S.status}): ${e}`)}await v.setRemoteDescription({type:`answer`,sdp:await S.text()})}catch(e){throw await v(!1),m(`error`,e),e}}},async stop(){await v(!0)}}}var A=16e3,j={noiseFloor:.003,gain:4,exponent:.8,attack:.3,release:.1};function M(e){let t=0;for(let n of e)t+=n*n;return Math.sqrt(t/e.length)}function N(e){return Math.min(1,Math.max(0,(M(e)*4)**.8))}function P(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 F(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 I(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 L(e){let t=e?.match(/rate=(\d+)/i);return t?Number(t[1]):24e3}function R(e){let t=new Set,n=new Set,r={state:`idle`,volume:0,inputVolume:0,outputVolume:0},i=null,a=null,o=null,s=null,c=null,l=null,u=null,d=null,f=null,p=!1,m=0,h=0,g=!1,_=!1;function v(){return e.activityDetection!==`server`}function y(){let t=typeof e.outputVolumeCalibration==`function`?e.outputVolumeCalibration():e.outputVolumeCalibration;return{...j,...t}}function x(e){r=e,t.forEach(t=>t(e))}function S(e,t){r.state===e&&t===void 0||(e!==`speaking`&&(h=0),x({state:e,volume:0,inputVolume:0,outputVolume:0,...t===void 0?{}:{error:t}}))}function C(){f&&=(clearTimeout(f),null)}function w(t){t>(e.speechThreshold??.04)?(!p&&v()&&i?.sendRealtimeInput({activityStart:{}}),p=!0,C(),r.state!==`listening`&&S(`listening`)):p&&!f&&(f=setTimeout(()=>{f=null,p=!1,v()&&i?.sendRealtimeInput({activityEnd:{}}),r.state===`listening`&&S(`thinking`)},e.speechEndDelayMs??500)),r.state===`listening`&&x({...r,volume:t,inputVolume:t,outputVolume:0})}function T(){n.forEach(e=>{try{e.stop()}catch{}e.disconnect()}),n.clear(),m=o?.currentTime??0}function E(){g&&n.size===0&&(g=!1,S(`listening`))}function D(e){if(!o||!u||!e.data)return;let t=I(e.data),i=o.createBuffer(1,t.length,L(e.mimeType));i.getChannelData(0).set(t);let a=o.createBufferSource();a.buffer=i,a.connect(u);let s=Math.max(o.currentTime,m);m=s+i.duration,n.add(a),a.onended=()=>{n.delete(a),a.disconnect(),E()},a.start(s),r.state!==`speaking`&&S(`speaking`)}function O(e){e.setupComplete&&S(`listening`);let t=e.serverContent;if(!t)return;if(t.interrupted){T(),g=!1,S(`listening`);return}let n=t.modelTurn?.parts?.filter(e=>e.inlineData?.data)??[];t.modelTurn&&n.length===0&&r.state!==`speaking`&&S(`thinking`),n.forEach(e=>D(e.inlineData)),t.waitingForInput&&(T(),S(`listening`)),(t.turnComplete||t.generationComplete)&&(g=!0,E())}function k(){if(!u)return;let t=new Float32Array(u.fftSize);d=setInterval(()=>{if(!u||r.state!==`speaking`)return;u.getFloatTimeDomainData(t);let n=b(M(t),h,y);h=n.normalized,e.onOutputVolumeSample?.(n);let i=n.normalized;x({...r,volume:i,inputVolume:0,outputVolume:i})},33)}function R(){!o||!a||!i||(s=o.createMediaStreamSource(a),c=o.createScriptProcessor(4096,1,1),l=o.createGain(),l.gain.value=0,s.connect(c),c.connect(l),l.connect(o.destination),c.onaudioprocess=t=>{if(!i||_)return;let n=t.inputBuffer.getChannelData(0);w(N(n));let r=P(n,o?.sampleRate??A,e.inputSampleRate??A);i.sendRealtimeInput({audio:{data:F(r),mimeType:`audio/pcm;rate=${e.inputSampleRate??A}`}})})}async function z(e){_=!0,C(),d&&clearInterval(d),d=null,T(),c?.disconnect(),s?.disconnect(),l?.disconnect(),u?.disconnect(),c=null,s=null,l=null,u=null,a?.getTracks().forEach(e=>e.stop()),a=null,o&&o.state!==`closed`&&await o.close(),o=null,i=null,p=!1,g=!1,h=0,e&&S(`idle`),_=!1}return{subscribe(e){return t.add(e),e(r),()=>t.delete(e)},async start(){if(!i){S(`connecting`),_=!1;try{let t=e.getUserMedia??(e=>navigator.mediaDevices.getUserMedia(e)),n=e.createAudioContext??(()=>new window.AudioContext);a=await t(e.mediaStreamConstraints??{audio:!0}),o=n(),o.state===`suspended`&&await o.resume(),u=o.createAnalyser(),u.fftSize=512,u.smoothingTimeConstant=.25,u.connect(o.destination),k(),i=await e.connect({onopen:()=>S(`listening`),onmessage:O,onerror:e=>S(`error`,e),onclose:()=>{_||S(`idle`)}}),R(),S(`listening`)}catch(e){throw i?.close(),await z(!1),S(`error`,e),e}}},async stop(){_=!0;try{p&&v()&&i?.sendRealtimeInput({activityEnd:{}}),i?.sendRealtimeInput({audioStreamEnd:!0})}catch{}i?.close(),await z(!0)}}}exports.DEFAULT_OUTPUT_VOLUME_CALIBRATION=g,exports.createElevenLabsAdapter=i,exports.createGeminiLiveAdapter=R,exports.createLiveKitAdapter=e.t,exports.createOpenAIRealtimeAdapter=k,exports.createPipecatAdapter=h,exports.createVapiAdapter=r;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./livekit-Dt-QZ6Gs.cjs");var t=.12;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(e,r){let i=new Set,a=null;function o(){a||(a=e.start.bind(e),e.start=async(...e)=>(i.forEach(e=>e()),a(...e)))}function s(){i.size>0||!a||(e.start=a,a=null)}return{async start(){await e.start(r?.assistantId)},stop(){e.stop()},subscribe(r){let a={state:`idle`,volume:0,outputVolume:0},c=0;function l(e){let n=e<t?0:(e-t)/(1-t),r=n>c?.8:.5;return c+=(n-c)*r,c}function u(e){a=e,r(e)}function d(e){u({...a,...e,state:e.state??a.state})}let{emitState:f,clearTimer:p}=n(e=>d({state:e})),m=()=>f(`connecting`),h=`idle`,g=!1,_=()=>{g=!0,h=`listening`,f(`listening`),d({volume:0,outputVolume:0})},v=()=>{g=!1,h=`idle`,E(),f(`idle`),d({volume:0,outputVolume:0}),c=0},y=()=>{g&&(h=`speaking`,f(`speaking`),d({volume:0,outputVolume:0}),T())},b=()=>{g&&(E(),h=`listening`,d({volume:0,outputVolume:0}),c=0,f(`listening`))},x=0,S=0,C=0,w=()=>{h===`speaking`&&(S+=(x-S)*.1,d({volume:S,outputVolume:S})),C=requestAnimationFrame(w)},T=()=>{C||=requestAnimationFrame(w)},E=()=>{C&&=(cancelAnimationFrame(C),0),S=0,x=0},D=e=>{if(h===`speaking`){let t=l(e);x=t/(t+.3)}},O=()=>{},k=e=>{console.error(`[orb-ui/vapi] Error:`,e),g=!1,h=`error`,p(),E(),d({state:`error`,volume:0,outputVolume:0,error:e}),c=0};return e.on(`call-start`,_),e.on(`call-end`,v),e.on(`speech-start`,y),e.on(`speech-end`,b),e.on(`volume-level`,D),e.on(`message`,O),e.on(`error`,k),i.add(m),o(),()=>{p(),E(),c=0,e.removeListener(`call-start`,_),e.removeListener(`call-end`,v),e.removeListener(`speech-start`,y),e.removeListener(`speech-end`,b),e.removeListener(`volume-level`,D),e.removeListener(`message`,O),e.removeListener(`error`,k),i.delete(m),s()}}}}function i(e,t){let n=null,r=0,i=null,a=null,o={state:`idle`,volume:0,inputVolume:0,outputVolume:0},s=`idle`,c=new Set;function l(e){o=e,c.forEach(t=>t(e))}function u(e){o={...o,...e,state:e.state??o.state},l(o)}function d(e){s=e,u({state:e})}function f(){a||=setInterval(()=>{if(n){if(s===`listening`){let e=Math.min(n.getInputVolume()*2,1);u({volume:e,inputVolume:e})}else if(s===`speaking`){let e=Math.min(n.getOutputVolume()*2,1);u({volume:e,outputVolume:e})}}},33)}function p(){a&&=(clearInterval(a),null)}function m(){p(),u({volume:0,inputVolume:0,outputVolume:0})}function h(){s=`idle`,u({state:`idle`,volume:0,inputVolume:0,outputVolume:0})}function g(e){return e===r}function _(e){return{onStatusChange:({status:t})=>{g(e)&&t===`connecting`&&d(`connecting`)},onConnect:()=>{g(e)&&(d(`listening`),f())},onModeChange:({mode:t})=>{g(e)&&(t===`speaking`?(d(`speaking`),f()):(d(`listening`),f()))},onDisconnect:()=>{g(e)&&(p(),n=null,h())},onError:t=>{g(e)&&(console.error(`[orb-ui/elevenlabs] Error:`,t),p(),s=`error`,u({state:`error`,volume:0,inputVolume:0,outputVolume:0,error:t}),n=null)}}}return{subscribe(e){return c.add(e),e(o),n&&(s===`listening`||s===`speaking`)&&f(),()=>{c.delete(e),c.size===0&&m()}},async start(){if(n||i)return i??void 0;r+=1;let a=r;return i=(async()=>{try{let r=await e.startSession({...t,..._(a)});if(!g(a)){await r.endSession().catch(e=>{console.error(`[orb-ui/elevenlabs] stale session cleanup failed:`,e)});return}n=r}catch(e){if(!g(a))return;console.error(`[orb-ui/elevenlabs] startSession failed:`,e),d(`error`),u({volume:0,inputVolume:0,outputVolume:0,error:e})}finally{i=null}})(),i},async stop(){let e=n;if(!e){i&&(r+=1,p(),h(),await i);return}let t=r;p();try{await e.endSession()}catch(e){console.error(`[orb-ui/elevenlabs] endSession failed:`,e)}n===e&&g(t)&&(n=null,h())}}}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`},o=.002,s=4,c=.8,l=.6,u=.2,d={noiseFloor:.002,gain:5.1,exponent:.8,attack:.5,release:.22};function f(){if(typeof window>`u`)return;let e=window.AudioContext;return e?new e:void 0}function p(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 m(e){if(typeof e!=`number`||!Number.isFinite(e)||e<=o)return 0;let t=Math.min(1,Math.max(0,e-o));return Math.min(1,t*s)**+c}function h(e,t){let n=m(e),r=n>t?l:u;return t+(n-t)*r}function g(e){return typeof e==`object`&&!!e&&`kind`in e&&typeof e.kind==`string`}function _(t,n={}){let r=new Set,i=new Map,o={state:p(t.state??``)??`idle`,volume:0,inputVolume:0,outputVolume:0},s=!1,c=0,l=0,u=null,m=null,_,v;function y(){let e=typeof n.outputVolumeCalibration==`function`?n.outputVolumeCalibration():n.outputVolumeCalibration;return{...d,...e}}function b(e){o=e,r.forEach(t=>t(e))}function x(e,t){c=0,l=0,b({state:e,volume:0,inputVolume:0,outputVolume:0,...t===void 0?{}:{error:t}})}function S(e){if(o.state!==`listening`)return;c=h(e,c);let t=c;b({...o,volume:t,inputVolume:t,outputVolume:0})}function C(t,r){if(o.state!==`speaking`)return;if(r&&typeof r==`object`){let e=r;if(e.local||n.isBotParticipant&&!n.isBotParticipant(e))return}let i=e.r(typeof t==`number`?t:0,l,y);l=i.normalized,n.onOutputVolumeSample?.(i);let a=i.normalized;b({...o,volume:a,inputVolume:0,outputVolume:a})}function w(){u=null,_?.stop(),_=void 0}function T(){m=null,v?.stop(),v=void 0}function E(){w(),T()}function D(t){u===t&&_||(w(),u=t,_=e.i(t,n.createAudioContext??f,S),_||(u=null))}function O(t){m===t&&v||(T(),m=t,v=e.i(t,n.createAudioContext??f,C),v||(m=null))}function k(){let e=t.tracks?.();e?.local?.audio&&D(e.local.audio),e?.bot?.audio&&O(e.bot.audio)}function A(e){if(!e||typeof e!=`object`)return!0;let t=e;return t.local?!1:n.isBotParticipant?.(t)??!0}function j(e,t){if(n.playRemoteAudio===!1||!g(e)||e.kind!==`audio`||!A(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 M(e){if(!g(e))return;let t=i.get(e);t&&(t.pause(),t.srcObject=null,t.remove(),i.delete(e))}function N(e,n){if(!g(e)||e.kind!==`audio`)return;let r=t.tracks?.().local?.audio;n?.local===!0||e===r?D(e):A(n)&&O(e),j(e,n)}function P(e){e===u&&w(),e===m&&T(),M(e)}function F(){i.forEach(e=>{e.pause(),e.srcObject=null,e.remove()}),i.clear()}function I(){E(),x(`idle`)}function L(){x(`listening`),k()}let R=[[a.connected,()=>x(`connecting`)],[a.botReady,L],[a.disconnected,I],[a.botDisconnected,I],[a.transportStateChanged,e=>{if(typeof e!=`string`)return;let t=p(e);t&&x(t)}],[a.userStartedSpeaking,()=>x(`listening`)],[a.userStoppedSpeaking,()=>{o.state===`listening`&&x(`thinking`)}],[a.botLlmStarted,()=>x(`thinking`)],[a.botTtsStarted,()=>x(`thinking`)],[a.botStartedSpeaking,()=>x(`speaking`)],[a.botStoppedSpeaking,()=>x(`listening`)],[a.localAudioLevel,e=>!_&&S(e)],[a.remoteAudioLevel,(e,t)=>!v&&C(e,t)],[`trackStarted`,N],[`trackStopped`,P],[a.error,e=>x(`error`,e)],[a.messageError,e=>x(`error`,e)],[a.deviceError,e=>x(`error`,e)]];function z(){s||(s=!0,R.forEach(([e,n])=>t.on(e,n)))}function B(){s&&(s=!1,R.forEach(([e,n])=>{t.off?t.off(e,n):t.removeListener?.(e,n)}),E(),F())}return{subscribe(e){return r.add(e),z(),e(o),()=>{r.delete(e),r.size===0&&B()}},async start(){x(`connecting`);try{await(n.connect?n.connect():t.connect())}catch(e){throw x(`error`,e),e}},async stop(){try{await(n.disconnect?n.disconnect():t.disconnect())}finally{E(),F(),x(`idle`)}}}}var v=`https://api.openai.com/v1/realtime/calls`,y=.015,b=8,x={noiseFloor:.003,gain:4,exponent:.8,attack:.55,release:.1};function S(){let e=window.AudioContext;return e?new e:void 0}function C(e){return Math.min(1,Math.max(0,(e*4)**.8))}function w(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 T(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 E(t){let n=new Set,r={state:`idle`,volume:0,inputVolume:0,outputVolume:0},i=null,a=null,o=null,s=null,c,l,u=0,d=0,f=!1;function p(){let e=typeof t.outputVolumeCalibration==`function`?t.outputVolumeCalibration():t.outputVolumeCalibration;return{...x,...e}}function m(e){r=e,n.forEach(t=>t(e))}function h(e,t){r.state===e&&t===void 0||(e!==`speaking`&&(d=0),m({state:e,volume:0,inputVolume:0,outputVolume:0,...t===void 0?{}:{error:t}}))}function g(e){if(r.state!==`listening`)return;let t=C(e);m({...r,volume:t,inputVolume:t,outputVolume:0})}function _(n){let i=e.r(n,d,p);d=i.normalized,t.onOutputVolumeSample?.(i);let a=i.normalized;if(a>y)u=0,r.state!==`speaking`&&h(`speaking`);else if(r.state===`speaking`&&(u+=1,u>=b)){u=0,h(`listening`);return}r.state===`speaking`&&m({...r,volume:a,inputVolume:0,outputVolume:a})}function E(e){switch(e.type){case`session.created`:case`session.updated`:h(`listening`);break;case`input_audio_buffer.speech_started`:h(`listening`);break;case`input_audio_buffer.speech_stopped`:case`response.created`:h(`thinking`);break;case`response.output_audio.delta`:case`output_audio_buffer.started`:h(`speaking`);break;case`output_audio_buffer.stopped`:h(`listening`);break;case`response.done`:case`response.cancelled`:r.state!==`speaking`&&h(`listening`);break;case`error`:h(`error`,e.error??e);break}}async function D(e){f=!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=0,e&&h(`idle`),f=!1}return{subscribe(e){return n.add(e),e(r),()=>n.delete(e)},async start(){if(!i){h(`connecting`),f=!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??S,p=T(await t.getClientSecret());o=await e(t.mediaStreamConstraints??{audio:!0}),c=w(o,d,g);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=w(t,d,_)},m.onconnectionstatechange=()=>{f||(m.connectionState===`failed`?h(`error`,Error(`[orb-ui/openai-realtime] WebRTC connection failed.`)):(m.connectionState===`disconnected`||m.connectionState===`closed`)&&h(`idle`))};let y=m.createDataChannel(`oai-events`);a=y,y.onopen=()=>h(`listening`),y.onmessage=e=>{try{E(JSON.parse(String(e.data)))}catch{}},y.onerror=e=>h(`error`,e),y.onclose=()=>{f||h(`idle`)};let b=await m.createOffer();await m.setLocalDescription(b);let x=await r(t.callsUrl??v,{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),h(`error`,e),e}}},async stop(){await D(!0)}}}var D=16e3,O={noiseFloor:.003,gain:4,exponent:.8,attack:.3,release:.1};function k(e){let t=0;for(let n of e)t+=n*n;return Math.sqrt(t/e.length)}function A(e){return Math.min(1,Math.max(0,(k(e)*4)**.8))}function j(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 M(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 N(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 P(e){let t=e?.match(/rate=(\d+)/i);return t?Number(t[1]):24e3}function F(t){let n=new Set,r=new Set,i={state:`idle`,volume:0,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=0,_=!1,v=!1;function y(){return t.activityDetection!==`server`}function b(){let e=typeof t.outputVolumeCalibration==`function`?t.outputVolumeCalibration():t.outputVolumeCalibration;return{...O,...e}}function x(e){i=e,n.forEach(t=>t(e))}function S(e,t){i.state===e&&t===void 0||(e!==`speaking`&&(g=0),x({state:e,volume:0,inputVolume:0,outputVolume:0,...t===void 0?{}:{error:t}}))}function C(){p&&=(clearTimeout(p),null)}function w(e){e>(t.speechThreshold??.04)?(!m&&y()&&a?.sendRealtimeInput({activityStart:{}}),m=!0,C(),i.state!==`listening`&&S(`listening`)):m&&!p&&(p=setTimeout(()=>{p=null,m=!1,y()&&a?.sendRealtimeInput({activityEnd:{}}),i.state===`listening`&&S(`thinking`)},t.speechEndDelayMs??500)),i.state===`listening`&&x({...i,volume:e,inputVolume:e,outputVolume:0})}function T(){r.forEach(e=>{try{e.stop()}catch{}e.disconnect()}),r.clear(),h=s?.currentTime??0}function E(){_&&r.size===0&&(_=!1,S(`listening`))}function F(e){if(!s||!d||!e.data)return;let t=N(e.data),n=s.createBuffer(1,t.length,P(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(),E()},a.start(o),i.state!==`speaking`&&S(`speaking`)}function I(e){e.setupComplete&&S(`listening`);let t=e.serverContent;if(!t)return;if(t.interrupted){T(),_=!1,S(`listening`);return}let n=t.modelTurn?.parts?.filter(e=>e.inlineData?.data)??[];t.modelTurn&&n.length===0&&i.state!==`speaking`&&S(`thinking`),n.forEach(e=>F(e.inlineData)),t.waitingForInput&&(T(),S(`listening`)),(t.turnComplete||t.generationComplete)&&(_=!0,E())}function L(){if(!d)return;let n=new Float32Array(d.fftSize);f=setInterval(()=>{if(!d||i.state!==`speaking`)return;d.getFloatTimeDomainData(n);let r=e.r(k(n),g,b);g=r.normalized,t.onOutputVolumeSample?.(r);let a=r.normalized;x({...i,volume:a,inputVolume:0,outputVolume:a})},33)}function R(){!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||v)return;let n=e.inputBuffer.getChannelData(0);w(A(n));let r=j(n,s?.sampleRate??D,t.inputSampleRate??D);a.sendRealtimeInput({audio:{data:M(r),mimeType:`audio/pcm;rate=${t.inputSampleRate??D}`}})})}async function z(e){v=!0,C(),f&&clearInterval(f),f=null,T(),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,_=!1,g=0,e&&S(`idle`),v=!1}return{subscribe(e){return n.add(e),e(i),()=>n.delete(e)},async start(){if(!a){S(`connecting`),v=!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),L(),a=await t.connect({onopen:()=>S(`listening`),onmessage:I,onerror:e=>S(`error`,e),onclose:()=>{v||S(`idle`)}}),R(),S(`listening`)}catch(e){throw a?.close(),await z(!1),S(`error`,e),e}}},async stop(){v=!0;try{m&&y()&&a?.sendRealtimeInput({activityEnd:{}}),a?.sendRealtimeInput({audioStreamEnd:!0})}catch{}a?.close(),await z(!0)}}}exports.DEFAULT_OUTPUT_VOLUME_CALIBRATION=e.n,exports.createElevenLabsAdapter=i,exports.createGeminiLiveAdapter=F,exports.createLiveKitAdapter=e.t,exports.createOpenAIRealtimeAdapter=E,exports.createPipecatAdapter=_,exports.createVapiAdapter=r;
|