orb-ui 0.4.0 → 0.6.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 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">Voice Agent UI Guide</a> · <a href="https://www.npmjs.com/package/orb-ui">npm</a> · <a href="https://github.com/alexanderqchen/orb-ui">GitHub</a>
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
@@ -71,7 +71,7 @@ The only difference is how the adapter obtains a provider session:
71
71
  | --------------- | ------------------------------------------------------------------------ |
72
72
  | Vapi | Pass a configured Vapi client plus `assistantId` |
73
73
  | ElevenLabs | Pass `Conversation` plus an `agentId`, signed URL, or conversation token |
74
- | LiveKit | Pass LiveKit runtime helpers plus a token source or endpoint |
74
+ | LiveKit | Provide a token endpoint and optional agent name |
75
75
  | Pipecat | Pass a configured `PipecatClient` plus its connect callback |
76
76
  | OpenAI Realtime | Return a fresh short-lived client secret from `getClientSecret` |
77
77
  | Gemini Live | Open the official Google Live session in `connect` |
@@ -117,18 +117,12 @@ function App() {
117
117
  ### With LiveKit
118
118
 
119
119
  ```jsx
120
- import { Room, TokenSource, createAudioAnalyser } from 'livekit-client'
121
120
  import { Orb } from 'orb-ui'
122
- import { createLiveKitAdapter } from 'orb-ui/adapters'
121
+ import { createLiveKitAdapter } from 'orb-ui/adapters/livekit'
123
122
 
124
123
  const adapter = createLiveKitAdapter({
125
- tokenSource: TokenSource.endpoint('/api/livekit-token'),
126
- tokenOptions: {
127
- agentName: 'your-agent-name',
128
- roomName: () => `orb-${crypto.randomUUID()}`,
129
- },
130
- createAudioAnalyser,
131
- RoomClass: Room,
124
+ tokenEndpoint: '/api/livekit-token',
125
+ agentName: 'your-agent-name',
132
126
  })
133
127
 
134
128
  function App() {
@@ -136,8 +130,9 @@ function App() {
136
130
  }
137
131
  ```
138
132
 
139
- The LiveKit adapter meters the local microphone while listening and the remote agent audio while
140
- speaking, so every audio-reactive theme follows the active side of the conversation.
133
+ The LiveKit entrypoint creates the room and token source, assigns a fresh room name, and meters both
134
+ sides of the conversation. Existing-room and custom-runtime modes remain available from the
135
+ advanced `orb-ui/adapters` entrypoint.
141
136
 
142
137
  ### With Pipecat
143
138
 
@@ -230,32 +225,51 @@ function App() {
230
225
  }
231
226
  ```
232
227
 
228
+ ### External session controls
229
+
230
+ Keep the orb as a passive visual when start and stop controls belong elsewhere in your layout.
231
+ Provider adapters already expose the matching lifecycle methods.
232
+
233
+ ```jsx
234
+ function VoiceExperience({ adapter }) {
235
+ return (
236
+ <>
237
+ <Orb adapter={adapter} theme="cloud" interactive={false} />
238
+ <button onClick={() => void adapter.start?.()}>Start conversation</button>
239
+ <button onClick={() => void adapter.stop?.()}>End conversation</button>
240
+ </>
241
+ )
242
+ }
243
+ ```
244
+
233
245
  ## Themes
234
246
 
235
247
  | Theme | Description |
236
248
  | -------- | ----------------------------------------------------------------------------- |
249
+ | `cloud` | Atmospheric sphere with inverse listening scale and faster speaking motion. |
237
250
  | `debug` | State + volume display with start/stop. Use to verify your integration works. |
238
251
  | `circle` | Pulsing circle that reacts to volume. |
239
252
  | `bars` | Five bars that animate with voice. |
240
253
 
241
- When an adapter or `onStart`/`onStop` handler is provided, `circle` and `bars` render as keyboard-accessible `<button type="button">` controls. Pass an `aria-label` when the surrounding UI does not already label the control.
254
+ 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.
242
255
 
243
256
  ## Props
244
257
 
245
- | Prop | Type | Default | Description |
246
- | ------------ | ------------------------------- | --------- | ----------------------------------------------------------- |
247
- | `theme` | `'debug' \| 'circle' \| 'bars'` | `'debug'` | Visual theme |
248
- | `signal` | `OrbSignal` | — | Rich controlled signal with state/input/output volume |
249
- | `state` | `OrbState` | `'idle'` | Conversation state (controlled mode) |
250
- | `volume` | `number` | `0` | Audio volume, 0–1. Overrides signal/adapter volume. |
251
- | `adapter` | `OrbAdapter` | — | Provider adapter (manages signal updates automatically) |
252
- | `size` | `number` | `200` | Size in pixels |
253
- | `className` | `string` | — | Optional class name for the rendered theme |
254
- | `style` | `React.CSSProperties` | — | Optional inline styles for the rendered theme |
255
- | `disabled` | `boolean` | `false` | Disables clickable themes and debug start/stop controls |
256
- | `aria-label` | `string` | generated | Accessible label for clickable `circle` and `bars` controls |
257
- | `onStart` | `() => void` | — | Custom start handler (overrides adapter.start()) |
258
- | `onStop` | `() => void` | — | Custom stop handler (overrides adapter.stop()) |
258
+ | Prop | Type | Default | Description |
259
+ | ------------- | ------------------------------------------ | --------- | ------------------------------------------------------- |
260
+ | `theme` | `'debug' \| 'circle' \| 'bars' \| 'cloud'` | `'debug'` | Visual theme |
261
+ | `signal` | `OrbSignal` | — | Rich controlled signal with state/input/output volume |
262
+ | `state` | `OrbState` | `'idle'` | Conversation state (controlled mode) |
263
+ | `volume` | `number` | `0` | Audio volume, 0–1. Overrides signal/adapter volume. |
264
+ | `adapter` | `OrbAdapter` | — | Provider adapter (manages signal updates automatically) |
265
+ | `size` | `number` | `200` | Size in pixels |
266
+ | `className` | `string` | — | Optional class name for the rendered theme |
267
+ | `style` | `React.CSSProperties` | — | Optional inline styles for the rendered theme |
268
+ | `disabled` | `boolean` | `false` | Disables clickable themes and debug start/stop controls |
269
+ | `interactive` | `boolean` | `true` | Allows the orb itself to start and stop a session |
270
+ | `aria-label` | `string` | generated | Accessible label for clickable visual themes |
271
+ | `onStart` | `() => void` | — | Custom start handler (overrides adapter.start()) |
272
+ | `onStop` | `() => void` | — | Custom stop handler (overrides adapter.stop()) |
259
273
 
260
274
  ## States
261
275
 
@@ -5,4 +5,4 @@ export { createPipecatAdapter, type PipecatAdapterOptions, type PipecatClientLik
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';
8
- export type { AdapterCallbacks, LegacyOrbAdapter, OrbAdapter, OrbSignal, OrbSignalListener, OrbState, } from './types.js';
8
+ export type { OrbAdapter, OrbSignal, OrbSignalListener, OrbState } from './types.js';
@@ -0,0 +1,44 @@
1
+ import { LiveKitOrbAdapter, LiveKitTokenOptions } from './index.js';
2
+ interface LiveKitBrowserAdapterBase extends Omit<LiveKitTokenOptions, 'agentName' | 'roomName'> {
3
+ /** Agent dispatched into the room. Required for LiveKit Cloud sandbox sessions. */
4
+ agentName?: LiveKitTokenOptions['agentName'];
5
+ /** Defaults to a fresh `orb-<uuid>` room name for every start. */
6
+ roomName?: LiveKitTokenOptions['roomName'];
7
+ /** LiveKit room.connect options passed through unchanged. */
8
+ connectOptions?: Record<string, unknown>;
9
+ /** Enable the local microphone after connecting. Defaults to true. */
10
+ enableMicrophone?: boolean;
11
+ }
12
+ export type LiveKitTokenEndpointOptions = Omit<RequestInit, 'body'>;
13
+ export interface LiveKitSandboxOptions {
14
+ /** Override LiveKit's default Cloud API base URL. */
15
+ baseUrl?: string;
16
+ }
17
+ export interface LiveKitEndpointAdapterConfig extends LiveKitBrowserAdapterBase {
18
+ /** LiveKit TokenSource endpoint returning `{ server_url, participant_token }`. */
19
+ tokenEndpoint: string;
20
+ /** Optional fetch settings such as authenticated request headers. */
21
+ tokenEndpointOptions?: LiveKitTokenEndpointOptions;
22
+ sandboxId?: never;
23
+ sandboxOptions?: never;
24
+ }
25
+ export interface LiveKitSandboxAdapterConfig extends LiveKitBrowserAdapterBase {
26
+ /** LiveKit Cloud sandbox token server ID. Sandbox mode is intended for testing only. */
27
+ sandboxId: string;
28
+ /** The agent to dispatch into the sandbox room. */
29
+ agentName: NonNullable<LiveKitTokenOptions['agentName']>;
30
+ /** Optional LiveKit sandbox host overrides. */
31
+ sandboxOptions?: LiveKitSandboxOptions;
32
+ tokenEndpoint?: never;
33
+ tokenEndpointOptions?: never;
34
+ }
35
+ export type LiveKitBrowserAdapterConfig = LiveKitEndpointAdapterConfig | LiveKitSandboxAdapterConfig;
36
+ /**
37
+ * Creates a managed LiveKit Agents adapter using the official browser SDK.
38
+ *
39
+ * This entrypoint owns the LiveKit Room, token source, microphone, playback,
40
+ * and audio analysers. Import the advanced factory from `orb-ui/adapters`
41
+ * only when your application already owns those pieces.
42
+ */
43
+ export declare function createLiveKitAdapter(config: LiveKitBrowserAdapterConfig): LiveKitOrbAdapter;
44
+ export type { LiveKitOrbAdapter } from './index.js';
@@ -37,7 +37,7 @@ interface LKRoom {
37
37
  interface LKCreateAudioAnalyser<TTrack = unknown> {
38
38
  (track: TTrack, options?: Record<string, unknown>): LKAnalyserResult;
39
39
  }
40
- type LiveKitTokenOptionValue = string | (() => string);
40
+ export type LiveKitTokenOptionValue = string | (() => string);
41
41
  export interface LiveKitConnectionDetails {
42
42
  /** LiveKit server URL, e.g. "wss://your-project.livekit.cloud". */
43
43
  serverUrl: string;
@@ -1,5 +1,5 @@
1
- import { AdapterCallbacks, LegacyOrbAdapter, OrbAdapter, OrbSignal, OrbSignalListener, OrbState } from '../components/Orb/Orb.types.js';
2
- export type { AdapterCallbacks, LegacyOrbAdapter, OrbAdapter, OrbSignal, OrbSignalListener, OrbState, };
1
+ import { OrbAdapter, OrbSignal, OrbSignalListener, OrbState } from '../components/Orb/Orb.types.js';
2
+ export type { OrbAdapter, OrbSignal, OrbSignalListener, OrbState };
3
3
  /**
4
4
  * Shared mic volume curve — rescale real-world mic range to 0–1 with pow shaping
5
5
  * for custom provider adapters that need browser-side input metering.
package/dist/adapters.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=.12;function t(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 n(n,r){let i=new Set,a=null;function o(){a||(a=n.start.bind(n),n.start=async(...e)=>(i.forEach(e=>e()),a(...e)))}function s(){i.size>0||!a||(n.start=a,a=null)}return{async start(){await n.start(r?.assistantId)},stop(){n.stop()},subscribe(r){let a={state:`idle`,volume:0,outputVolume:0},c=0;function l(t){let n=t<e?0:(t-e)/(1-e),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}=t(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 n.on(`call-start`,_),n.on(`call-end`,v),n.on(`speech-start`,y),n.on(`speech-end`,b),n.on(`volume-level`,D),n.on(`message`,O),n.on(`error`,k),i.add(m),o(),()=>{p(),E(),c=0,n.removeListener(`call-start`,_),n.removeListener(`call-end`,v),n.removeListener(`speech-start`,y),n.removeListener(`speech-end`,b),n.removeListener(`volume-level`,D),n.removeListener(`message`,O),n.removeListener(`error`,k),i.delete(m),s()}}}}function r(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())}}}function i(e){let t=Math.min(e/.5,1);return t**=1.3,t}var a=4,o=.03,s=1.5,c=.6,l=.2,u=.35;function d(e){switch(e){case`speaking`:return`speaking`;case`thinking`:return`thinking`;case`listening`:case`idle`:return`listening`;case`connecting`:case`pre-connect-buffering`:case`initializing`:return`connecting`;case`disconnected`:return`idle`;case`failed`:return`error`;default:return`idle`}}function f(e){return`RoomClass`in e}function p(e){return typeof e==`function`?e():e}function m(e){if(!e)return{};let t={},n=(e,n)=>{n!==void 0&&(t[e]=n)};return n(`roomName`,p(e.roomName)),n(`participantName`,p(e.participantName)),n(`participantIdentity`,p(e.participantIdentity)),n(`participantMetadata`,p(e.participantMetadata)),n(`participantAttributes`,typeof e.participantAttributes==`function`?e.participantAttributes():e.participantAttributes),n(`agentName`,p(e.agentName)),n(`agentMetadata`,p(e.agentMetadata)),n(`deployment`,p(e.deployment)),t}function h(e){if(!e.serverUrl||!e.participantToken)throw Error(`[orb-ui/livekit] connection details must include serverUrl and participantToken.`);return e}async function g(e){let t=m(e.tokenOptions);return typeof e.getConnectionDetails==`function`?h(await e.getConnectionDetails(t)):e.tokenSource?h(await e.tokenSource.fetch(t)):h({serverUrl:e.serverUrl,participantToken:e.participantToken})}function _(e){for(let[,t]of e.remoteParticipants)if(!t.isLocal&&(t.kind===a||t.attributes?.[`lk.agent.state`]!==void 0))return t;return null}function v(e,t,n){let r=e.off;if(r){r.call(e,t,n);return}e.removeListener?.call(e,t,n)}function y(e,t,n){e.on.call(e,t,n)}function b(e){let t=f(e),n=e.createAudioAnalyser,r={current:t?null:e.room},p=new Set,m={state:`idle`,volume:0,inputVolume:0,outputVolume:0},h=`idle`,b=null,x=null,S=null,C=null,w=null,T=null,E=null,D=0,O=null;function k(e){m=e,p.forEach(t=>t(e))}function A(e){k({...m,...e,state:e.state??m.state})}function j(e){let t=e<o?0:e,n=t>D?c:l;D+=(t-D)*n;let r=Math.min(D*s,1);return r/(r+u)}function M(){D=0,A({volume:0,outputVolume:0})}function N({emitZero:e=!0}={}){w&&=(clearInterval(w),null),C&&=(C.cleanup().catch(()=>{}),null),e&&A({volume:0,inputVolume:0})}function P(e){if(!(b===e&&C)){N({emitZero:!1}),b=e;try{C=n(e)}catch(e){console.warn(`[orb-ui/livekit] local createAudioAnalyser failed:`,e);return}w=setInterval(()=>{if(!C||h!==`listening`)return;let e=i(C.calculateVolume());A({volume:e,inputVolume:e,outputVolume:0})},33)}}function F({emitZero:e=!0}={}){E&&=(clearInterval(E),null),T&&=(T.cleanup().catch(()=>{}),null),D=0,e&&A({volume:0,outputVolume:0})}function I(e){F();try{T=n(e)}catch(e){console.warn(`[orb-ui/livekit] remote createAudioAnalyser failed:`,e);return}E=setInterval(()=>{if(!T||h!==`speaking`)return;let e=j(T.calculateVolume());A({volume:e,inputVolume:0,outputVolume:e})},33)}function L(e){h=e,A({state:e,volume:0,inputVolume:0,outputVolume:0}),e===`speaking`&&x?I(x):e!==`speaking`&&F({emitZero:!1})}function R(e){S||typeof document>`u`||(S=e.attach(),S.id=`orb-ui-livekit-agent-audio`,document.body.appendChild(S))}function z(){S&&=(S.remove(),null)}function B(e){x=e,R(e),h===`speaking`&&I(e)}function V(e){P(e)}function H(e){let t=e.getTrackPublication?.(`microphone`);t?.track&&V(t.track)}function U(e){let t=d(e);t!==h&&L(t)}function W(e){let t=e.attributes?.[`lk.agent.state`];t&&U(t);let n=e.getTrackPublication(`microphone`);n?.track&&B(n.track)}function G(e){if(O)return;let t=(e,t)=>{if(t.isLocal)return;let n=e[`lk.agent.state`];n&&U(n)},n=(e,t,n)=>{n.isLocal||!(n.kind===a||n.attributes?.[`lk.agent.state`]!==void 0)||e.mediaStreamTrack.kind!==`audio`||B(e)},r=e=>{x===e&&(x=null,z(),F())},i=e=>{e.source!==`microphone`||!e.track||V(e.track)},o=e=>{e.source===`microphone`&&(b=null,N())},s=()=>{b=null,x=null,z(),N({emitZero:!1}),F({emitZero:!1}),L(`idle`)};if(y(e,`participantAttributesChanged`,t),y(e,`trackSubscribed`,n),y(e,`trackUnsubscribed`,r),y(e,`localTrackPublished`,i),y(e,`localTrackUnpublished`,o),y(e,`disconnected`,s),O=()=>{v(e,`participantAttributesChanged`,t),v(e,`trackSubscribed`,n),v(e,`trackUnsubscribed`,r),v(e,`localTrackPublished`,i),v(e,`localTrackUnpublished`,o),v(e,`disconnected`,s)},H(e.localParticipant),e.state===`connected`){let t=_(e);t?W(t):L(`connecting`)}else L(`idle`)}function K(){O?.(),O=null,b=null,x=null,z(),N({emitZero:!1}),F({emitZero:!1}),A({volume:0,inputVolume:0,outputVolume:0})}let q=e=>{p.add(e),e(m);let t=r.current;return t&&G(t),()=>{p.delete(e),p.size===0&&K()}};return t?{subscribe:q,async start(){if(r.current)return;let t=e,n=new t.RoomClass;L(`connecting`);try{let e=await g(t);if(await n.connect(e.serverUrl,e.participantToken,t.connectOptions),r.current=n,G(n),t.enableMicrophone!==!1){let e=(await n.localParticipant.setMicrophoneEnabled(!0))?.track??n.localParticipant.getTrackPublication?.(`microphone`)?.track;e&&V(e)}}catch(e){throw console.error(`[orb-ui/livekit] connect failed:`,e),r.current===n&&K(),n.disconnect(),r.current=null,L(`error`),M(),A({error:e}),e}},async stop(){let e=r.current;if(!e){L(`idle`);return}K(),e.disconnect(),r.current=null,L(`idle`)}}:{subscribe:q}}var x={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`},S=.002,C=4,w=.8,T=.6,E=.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 O(e){if(typeof e!=`number`||!Number.isFinite(e)||e<=S)return 0;let t=Math.min(1,Math.max(0,e-S));return Math.min(1,t*C)**+w}function k(e,t){let n=O(e),r=n>t?T:E;return t+(n-t)*r}function A(e){return typeof e==`object`&&!!e&&`kind`in e&&typeof e.kind==`string`}function j(e,t={}){let n=new Set,r=new Map,i={state:D(e.state??``)??`idle`,volume:0,inputVolume:0,outputVolume:0},a=!1,o=0,s=0;function c(e){i=e,n.forEach(t=>t(e))}function l(e,t){o=0,s=0,c({state:e,volume:0,inputVolume:0,outputVolume:0,...t===void 0?{}:{error:t}})}function u(e){if(i.state!==`listening`)return;o=k(e,o);let t=o;c({...i,volume:t,inputVolume:t,outputVolume:0})}function d(e,n){if(i.state!==`speaking`)return;if(n&&typeof n==`object`){let e=n;if(e.local||t.isBotParticipant&&!t.isBotParticipant(e))return}s=k(e,s);let r=s;c({...i,volume:r,inputVolume:0,outputVolume:r})}function f(e){if(!e||typeof e!=`object`)return!0;let n=e;return n.local?!1:t.isBotParticipant?.(n)??!0}function p(e,n){if(t.playRemoteAudio===!1||!A(e)||e.kind!==`audio`||!f(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 m(e){if(!A(e))return;let t=r.get(e);t&&(t.pause(),t.srcObject=null,t.remove(),r.delete(e))}function h(){r.forEach(e=>{e.pause(),e.srcObject=null,e.remove()}),r.clear()}let g=[[x.connected,()=>l(`connecting`)],[x.botReady,()=>l(`listening`)],[x.disconnected,()=>l(`idle`)],[x.botDisconnected,()=>l(`idle`)],[x.transportStateChanged,e=>{if(typeof e!=`string`)return;let t=D(e);t&&l(t)}],[x.userStartedSpeaking,()=>l(`listening`)],[x.userStoppedSpeaking,()=>{i.state===`listening`&&l(`thinking`)}],[x.botLlmStarted,()=>l(`thinking`)],[x.botTtsStarted,()=>l(`thinking`)],[x.botStartedSpeaking,()=>l(`speaking`)],[x.botStoppedSpeaking,()=>l(`listening`)],[x.localAudioLevel,u],[x.remoteAudioLevel,d],[`trackStarted`,p],[`trackStopped`,m],[x.error,e=>l(`error`,e)],[x.messageError,e=>l(`error`,e)],[x.deviceError,e=>l(`error`,e)]];function _(){a||(a=!0,g.forEach(([t,n])=>e.on(t,n)))}function v(){a&&(a=!1,g.forEach(([t,n])=>{e.off?e.off(t,n):e.removeListener?.(t,n)}),h())}return{subscribe(e){return n.add(e),_(),e(i),()=>{n.delete(e),n.size===0&&v()}},async start(){l(`connecting`);try{await(t.connect?t.connect():e.connect())}catch(e){throw l(`error`,e),e}},async stop(){try{await(t.disconnect?t.disconnect():e.disconnect())}finally{h(),l(`idle`)}}}}var M={noiseFloor:0,gain:4,exponent:.8,attack:1,release:1};function N(e,t,n){return Math.min(n,Math.max(t,e))}function P(e,t){return typeof e==`number`&&Number.isFinite(e)?e:t}function F(e){let t=typeof e==`function`?e():e;return{noiseFloor:N(P(t?.noiseFloor,M.noiseFloor),0,1),gain:Math.max(0,P(t?.gain,M.gain)),exponent:Math.max(.01,P(t?.exponent,M.exponent)),attack:N(P(t?.attack,M.attack),0,1),release:N(P(t?.release,M.release),0,1)}}function I(e,t,n){let r=Number.isFinite(e)?N(e,0,1):0,i=F(n),a=N((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:N(t+(a-t)*o,0,1)}}var L=`https://api.openai.com/v1/realtime/calls`,R=.015,z=8,B={noiseFloor:.003,gain:4,exponent:.8,attack:.55,release:.1};function V(){let e=window.AudioContext;return e?new e:void 0}function H(e){return Math.min(1,Math.max(0,(e*4)**.8))}function U(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 W(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(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{...B,...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=H(e);p({...n,volume:t,inputVolume:t,outputVolume:0})}function g(t){let r=I(t,u,f);u=r.normalized,e.onOutputVolumeSample?.(r);let i=r.normalized;if(i>R)l=0,n.state!==`speaking`&&m(`speaking`);else if(n.state===`speaking`&&(l+=1,l>=z)){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??V,p=W(await e.getClientSecret());a=await t(e.mediaStreamConstraints??{audio:!0}),s=U(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=U(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 x=await l(e.callsUrl??L,{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 v.setRemoteDescription({type:`answer`,sdp:await x.text()})}catch(e){throw await v(!1),m(`error`,e),e}}},async stop(){await v(!0)}}}var K=16e3,q={noiseFloor:.003,gain:4,exponent:.8,attack:.3,release:.1};function J(e){let t=0;for(let n of e)t+=n*n;return Math.sqrt(t/e.length)}function Y(e){return Math.min(1,Math.max(0,(J(e)*4)**.8))}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 Z(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 Q(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 $(e){let t=e?.match(/rate=(\d+)/i);return t?Number(t[1]):24e3}function ee(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{...q,...t}}function b(e){r=e,t.forEach(t=>t(e))}function x(e,t){r.state===e&&t===void 0||(e!==`speaking`&&(h=0),b({state:e,volume:0,inputVolume:0,outputVolume:0,...t===void 0?{}:{error:t}}))}function S(){f&&=(clearTimeout(f),null)}function C(t){t>(e.speechThreshold??.04)?(!p&&v()&&i?.sendRealtimeInput({activityStart:{}}),p=!0,S(),r.state!==`listening`&&x(`listening`)):p&&!f&&(f=setTimeout(()=>{f=null,p=!1,v()&&i?.sendRealtimeInput({activityEnd:{}}),r.state===`listening`&&x(`thinking`)},e.speechEndDelayMs??500)),r.state===`listening`&&b({...r,volume:t,inputVolume:t,outputVolume:0})}function w(){n.forEach(e=>{try{e.stop()}catch{}e.disconnect()}),n.clear(),m=o?.currentTime??0}function T(){g&&n.size===0&&(g=!1,x(`listening`))}function E(e){if(!o||!u||!e.data)return;let t=Q(e.data),i=o.createBuffer(1,t.length,$(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(),T()},a.start(s),r.state!==`speaking`&&x(`speaking`)}function D(e){e.setupComplete&&x(`listening`);let t=e.serverContent;if(!t)return;if(t.interrupted){w(),g=!1,x(`listening`);return}let n=t.modelTurn?.parts?.filter(e=>e.inlineData?.data)??[];t.modelTurn&&n.length===0&&r.state!==`speaking`&&x(`thinking`),n.forEach(e=>E(e.inlineData)),t.waitingForInput&&(w(),x(`listening`)),(t.turnComplete||t.generationComplete)&&(g=!0,T())}function O(){if(!u)return;let t=new Float32Array(u.fftSize);d=setInterval(()=>{if(!u||r.state!==`speaking`)return;u.getFloatTimeDomainData(t);let n=I(J(t),h,y);h=n.normalized,e.onOutputVolumeSample?.(n);let i=n.normalized;b({...r,volume:i,inputVolume:0,outputVolume:i})},33)}function k(){!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);C(Y(n));let r=X(n,o?.sampleRate??K,e.inputSampleRate??K);i.sendRealtimeInput({audio:{data:Z(r),mimeType:`audio/pcm;rate=${e.inputSampleRate??K}`}})})}async function A(e){_=!0,S(),d&&clearInterval(d),d=null,w(),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&&x(`idle`),_=!1}return{subscribe(e){return t.add(e),e(r),()=>t.delete(e)},async start(){if(!i){x(`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),O(),i=await e.connect({onopen:()=>x(`listening`),onmessage:D,onerror:e=>x(`error`,e),onclose:()=>{_||x(`idle`)}}),k(),x(`listening`)}catch(e){throw i?.close(),await A(!1),x(`error`,e),e}}},async stop(){_=!0;try{p&&v()&&i?.sendRealtimeInput({activityEnd:{}}),i?.sendRealtimeInput({audioStreamEnd:!0})}catch{}i?.close(),await A(!0)}}}exports.DEFAULT_OUTPUT_VOLUME_CALIBRATION=M,exports.createElevenLabsAdapter=r,exports.createGeminiLiveAdapter=ee,exports.createLiveKitAdapter=b,exports.createOpenAIRealtimeAdapter=G,exports.createPipecatAdapter=j,exports.createVapiAdapter=n;
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;