orb-ui 0.2.4 → 0.4.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
@@ -1,6 +1,6 @@
1
1
  # orb-ui
2
2
 
3
- React voice agent UI components for Vapi, ElevenLabs, and custom realtime voice AI apps. orb-ui gives you animated voice orbs, audio-reactive themes, accessible clickable controls, and provider adapters for building polished voice agent interfaces in React.
3
+ React voice agent UI components for Vapi, ElevenLabs, LiveKit, Pipecat, OpenAI Realtime, Gemini Live, and custom realtime voice AI apps. orb-ui gives you animated voice orbs, audio-reactive themes, accessible clickable controls, and provider adapters for building polished voice agent interfaces in React.
4
4
 
5
5
  <p align="center">
6
6
  <a href="https://orb-ui.com">
@@ -41,13 +41,49 @@ npm install orb-ui @vapi-ai/web
41
41
 
42
42
  # ElevenLabs Conversational AI
43
43
  npm install orb-ui @elevenlabs/client
44
+
45
+ # LiveKit Agents
46
+ npm install orb-ui livekit-client
47
+
48
+ # Pipecat (choose the transport used by your agent)
49
+ npm install orb-ui @pipecat-ai/client-js @pipecat-ai/small-webrtc-transport
50
+
51
+ # OpenAI Realtime uses browser WebRTC and has no additional client SDK
52
+ npm install orb-ui
53
+
54
+ # Gemini Live
55
+ npm install orb-ui @google/genai
44
56
  ```
45
57
 
46
58
  > **Note:** Orb uses React hooks internally — in Next.js App Router, use it in a `'use client'` component.
47
59
 
60
+ ## How provider adapters are created
61
+
62
+ Every provider ends at the same React API:
63
+
64
+ ```jsx
65
+ <Orb adapter={adapter} theme="circle" aria-label="Start voice assistant" />
66
+ ```
67
+
68
+ The only difference is how the adapter obtains a provider session:
69
+
70
+ | Provider | Required browser setup |
71
+ | --------------- | ------------------------------------------------------------------------ |
72
+ | Vapi | Pass a configured Vapi client plus `assistantId` |
73
+ | ElevenLabs | Pass `Conversation` plus an `agentId`, signed URL, or conversation token |
74
+ | LiveKit | Pass LiveKit runtime helpers plus a token source or endpoint |
75
+ | Pipecat | Pass a configured `PipecatClient` plus its connect callback |
76
+ | OpenAI Realtime | Return a fresh short-lived client secret from `getClientSecret` |
77
+ | Gemini Live | Open the official Google Live session in `connect` |
78
+
79
+ The adapter owns provider event mapping and emits one consistent `OrbSignal`. OpenAI and Gemini
80
+ standard API keys, and LiveKit participant-token signing, stay on your server. See the
81
+ [adapter overview](https://orb-ui.com/docs/adapters/overview) for the responsibility boundary and
82
+ advanced setup shapes.
83
+
48
84
  ## Quick Start
49
85
 
50
- Use orb-ui as a React voice AI component when you need a Vapi voice UI, an ElevenLabs voice UI, or a custom animated voice orb for another realtime voice agent stack.
86
+ Use orb-ui as a React voice AI component when you need a first-party provider voice UI or a custom animated voice orb for another realtime voice agent stack.
51
87
 
52
88
  ### With Vapi
53
89
 
@@ -78,6 +114,98 @@ function App() {
78
114
  }
79
115
  ```
80
116
 
117
+ ### With LiveKit
118
+
119
+ ```jsx
120
+ import { Room, TokenSource, createAudioAnalyser } from 'livekit-client'
121
+ import { Orb } from 'orb-ui'
122
+ import { createLiveKitAdapter } from 'orb-ui/adapters'
123
+
124
+ 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,
132
+ })
133
+
134
+ function App() {
135
+ return <Orb adapter={adapter} theme="circle" aria-label="Start LiveKit assistant" />
136
+ }
137
+ ```
138
+
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.
141
+
142
+ ### With Pipecat
143
+
144
+ ```jsx
145
+ import { PipecatClient } from '@pipecat-ai/client-js'
146
+ import { SmallWebRTCTransport } from '@pipecat-ai/small-webrtc-transport'
147
+ import { Orb } from 'orb-ui'
148
+ import { createPipecatAdapter } from 'orb-ui/adapters'
149
+
150
+ const client = new PipecatClient({ transport: new SmallWebRTCTransport(), enableMic: true })
151
+ const adapter = createPipecatAdapter(client, {
152
+ connect: () => client.connect({ webrtcUrl: 'https://agent.example.com/api/offer' }),
153
+ })
154
+
155
+ function App() {
156
+ return <Orb adapter={adapter} theme="circle" aria-label="Start Pipecat assistant" />
157
+ }
158
+ ```
159
+
160
+ The Pipecat adapter consumes the standard RTVI event surface, so it also works with Pipecat Cloud,
161
+ Daily, and other Pipecat transports. See the [Pipecat guide](https://orb-ui.com/docs/adapters/pipecat).
162
+
163
+ ### With OpenAI Realtime
164
+
165
+ ```jsx
166
+ import { Orb } from 'orb-ui'
167
+ import { createOpenAIRealtimeAdapter } from 'orb-ui/adapters'
168
+
169
+ const adapter = createOpenAIRealtimeAdapter({
170
+ getClientSecret: async () => {
171
+ const response = await fetch('/api/openai-realtime-token', { method: 'POST' })
172
+ return (await response.json()).value
173
+ },
174
+ })
175
+ ```
176
+
177
+ Create client secrets with a standard OpenAI API key on your server. See the
178
+ [OpenAI Realtime guide](https://orb-ui.com/docs/adapters/openai-realtime).
179
+
180
+ ### With Gemini Live
181
+
182
+ ```jsx
183
+ import { GoogleGenAI } from '@google/genai'
184
+ import { Orb } from 'orb-ui'
185
+ import { createGeminiLiveAdapter } from 'orb-ui/adapters'
186
+
187
+ const adapter = createGeminiLiveAdapter({
188
+ connect: async (callbacks) => {
189
+ const token = await fetch('/api/gemini-live-token', { method: 'POST' }).then((res) =>
190
+ res.json(),
191
+ )
192
+ const client = new GoogleGenAI({
193
+ apiKey: token.value,
194
+ httpOptions: { apiVersion: 'v1alpha' },
195
+ })
196
+ return client.live.connect({ model: token.model, config: token.config, callbacks })
197
+ },
198
+ })
199
+ ```
200
+
201
+ Mint one-use Gemini Live tokens on your server. See the
202
+ [Gemini Live guide](https://orb-ui.com/docs/adapters/gemini-live) for the matching server config that
203
+ disables automatic activity detection. The adapter handles client-side turn detection by default.
204
+
205
+ The examples above show the intended happy paths. Transport overrides, custom browser runtimes,
206
+ existing-session modes, and audio calibration hooks are optional and documented in the individual
207
+ adapter guides.
208
+
81
209
  ### Controlled mode (custom integration)
82
210
 
83
211
  ```jsx
@@ -92,6 +220,16 @@ function App() {
92
220
  }
93
221
  ```
94
222
 
223
+ Use `signal` when your integration has separate input and output levels:
224
+
225
+ ```jsx
226
+ import { Orb } from 'orb-ui'
227
+
228
+ function App() {
229
+ return <Orb signal={{ state: 'speaking', outputVolume: 0.7 }} theme="circle" />
230
+ }
231
+ ```
232
+
95
233
  ## Themes
96
234
 
97
235
  | Theme | Description |
@@ -107,9 +245,10 @@ When an adapter or `onStart`/`onStop` handler is provided, `circle` and `bars` r
107
245
  | Prop | Type | Default | Description |
108
246
  | ------------ | ------------------------------- | --------- | ----------------------------------------------------------- |
109
247
  | `theme` | `'debug' \| 'circle' \| 'bars'` | `'debug'` | Visual theme |
248
+ | `signal` | `OrbSignal` | — | Rich controlled signal with state/input/output volume |
110
249
  | `state` | `OrbState` | `'idle'` | Conversation state (controlled mode) |
111
- | `volume` | `number` | `0` | Audio volume, 0–1 (controlled mode) |
112
- | `adapter` | `OrbAdapter` | — | Provider adapter (manages state + volume automatically) |
250
+ | `volume` | `number` | `0` | Audio volume, 0–1. Overrides signal/adapter volume. |
251
+ | `adapter` | `OrbAdapter` | — | Provider adapter (manages signal updates automatically) |
113
252
  | `size` | `number` | `200` | Size in pixels |
114
253
  | `className` | `string` | — | Optional class name for the rendered theme |
115
254
  | `style` | `React.CSSProperties` | — | Optional inline styles for the rendered theme |
@@ -120,15 +259,19 @@ When an adapter or `onStart`/`onStop` handler is provided, `circle` and `bars` r
120
259
 
121
260
  ## States
122
261
 
123
- `idle` · `connecting` · `listening` · `speaking` · `error`
262
+ `idle` · `connecting` · `listening` · `thinking` · `speaking` · `error`
124
263
 
125
264
  ## Supported Providers
126
265
 
127
- | Provider | Adapter |
128
- | ----------------------------------------------------- | -------------------------------------------------------- |
129
- | [Vapi](https://vapi.ai) | `createVapiAdapter` from `orb-ui/adapters` |
130
- | [ElevenLabs](https://elevenlabs.io/conversational-ai) | `createElevenLabsAdapter` from `orb-ui/adapters` |
131
- | Custom | Use controlled mode — pass `state` and `volume` directly |
266
+ | Provider | Adapter |
267
+ | ------------------------------------------------------------------------- | --------------------------------------------------------------------- |
268
+ | [Vapi](https://vapi.ai) | `createVapiAdapter` from `orb-ui/adapters` |
269
+ | [ElevenLabs](https://elevenlabs.io/conversational-ai) | `createElevenLabsAdapter` from `orb-ui/adapters` |
270
+ | [LiveKit](https://livekit.io) | `createLiveKitAdapter` from `orb-ui/adapters` |
271
+ | [Pipecat](https://pipecat.ai) | `createPipecatAdapter` from `orb-ui/adapters` |
272
+ | [OpenAI Realtime](https://developers.openai.com/api/docs/guides/realtime) | `createOpenAIRealtimeAdapter` from `orb-ui/adapters` |
273
+ | [Gemini Live](https://ai.google.dev/gemini-api/docs/live-api) | `createGeminiLiveAdapter` from `orb-ui/adapters` |
274
+ | Custom | Use controlled mode — pass `signal`, or `state` and `volume` directly |
132
275
 
133
276
  ## Development
134
277
 
@@ -0,0 +1,23 @@
1
+ export interface OutputVolumeCalibration {
2
+ /** Raw RMS values at or below this level are treated as silence. */
3
+ noiseFloor: number;
4
+ /** Multiplier applied after the noise floor. */
5
+ gain: number;
6
+ /** Power curve applied after gain. Values below 1 lift quieter speech. */
7
+ exponent: number;
8
+ /** EMA rate used while the volume is rising. */
9
+ attack: number;
10
+ /** EMA rate used while the volume is falling. */
11
+ release: number;
12
+ }
13
+ export type OutputVolumeCalibrationSource = Partial<OutputVolumeCalibration> | (() => Partial<OutputVolumeCalibration>);
14
+ export interface OutputVolumeSample {
15
+ /** Unmodified RMS value measured from the provider audio stream. */
16
+ raw: number;
17
+ /** Value after noise floor, gain, and power-curve shaping. */
18
+ shaped: number;
19
+ /** Final value after attack/release smoothing. */
20
+ normalized: number;
21
+ }
22
+ export declare const DEFAULT_OUTPUT_VOLUME_CALIBRATION: OutputVolumeCalibration;
23
+ export declare function calibrateOutputVolume(rawValue: number, previous: number, source?: OutputVolumeCalibrationSource): OutputVolumeSample;
@@ -0,0 +1,70 @@
1
+ import { OrbAdapter } from '../types.js';
2
+ import { OutputVolumeCalibrationSource, OutputVolumeSample } from '../audio-level.js';
3
+ export interface GeminiLiveInlineData {
4
+ data?: string;
5
+ mimeType?: string;
6
+ }
7
+ export interface GeminiLiveServerMessage {
8
+ setupComplete?: unknown;
9
+ serverContent?: {
10
+ modelTurn?: {
11
+ parts?: Array<{
12
+ inlineData?: GeminiLiveInlineData;
13
+ }>;
14
+ };
15
+ turnComplete?: boolean;
16
+ generationComplete?: boolean;
17
+ interrupted?: boolean;
18
+ waitingForInput?: boolean;
19
+ };
20
+ }
21
+ export interface GeminiLiveCallbacks {
22
+ onopen?: () => void;
23
+ onmessage: (message: GeminiLiveServerMessage) => void;
24
+ onerror?: (error: unknown) => void;
25
+ onclose?: (event: unknown) => void;
26
+ }
27
+ export interface GeminiLiveSession {
28
+ sendRealtimeInput(input: {
29
+ audio?: {
30
+ data: string;
31
+ mimeType: string;
32
+ };
33
+ audioStreamEnd?: boolean;
34
+ activityStart?: Record<string, never>;
35
+ activityEnd?: Record<string, never>;
36
+ }): void;
37
+ close(): void;
38
+ }
39
+ export interface GeminiLiveAdapterConfig {
40
+ /** Connects an official Google GenAI Live session using the supplied callbacks. */
41
+ connect(callbacks: GeminiLiveCallbacks): Promise<GeminiLiveSession>;
42
+ /** Defaults to `{ audio: true }`. */
43
+ mediaStreamConstraints?: MediaStreamConstraints;
44
+ /** Defaults to 16 kHz PCM input, as recommended by Gemini Live. */
45
+ inputSampleRate?: number;
46
+ /** Defaults to 0.04 normalized input volume. */
47
+ speechThreshold?: number;
48
+ /** Defaults to 500 ms before listening transitions to thinking. */
49
+ speechEndDelayMs?: number;
50
+ /** Defaults to client-side detection. Use `server` with Gemini automatic activity detection. */
51
+ activityDetection?: 'client' | 'server';
52
+ /** Runtime override for tests or custom browser wrappers. */
53
+ getUserMedia?: (constraints: MediaStreamConstraints) => Promise<MediaStream>;
54
+ /** Runtime override for tests or custom browser wrappers. */
55
+ createAudioContext?: () => AudioContext;
56
+ /** Optional live-tunable output shaping. A getter is read for every meter sample. */
57
+ outputVolumeCalibration?: OutputVolumeCalibrationSource;
58
+ /** Receives raw, shaped, and smoothed output levels for diagnostics. */
59
+ onOutputVolumeSample?: (sample: OutputVolumeSample) => void;
60
+ }
61
+ export interface GeminiLiveOrbAdapter extends OrbAdapter {
62
+ start(): Promise<void>;
63
+ stop(): Promise<void>;
64
+ }
65
+ /**
66
+ * Creates a managed browser-audio adapter for Gemini Live. The app owns token
67
+ * creation and the official GenAI client; orb-ui owns microphone streaming,
68
+ * PCM playback, volume metering, and normalized voice state.
69
+ */
70
+ export declare function createGeminiLiveAdapter(config: GeminiLiveAdapterConfig): GeminiLiveOrbAdapter;
@@ -1,3 +1,8 @@
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
- export type { OrbAdapter, OrbState, AdapterCallbacks } from './types.js';
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';
5
+ export { createOpenAIRealtimeAdapter, type OpenAIRealtimeAdapterConfig, type OpenAIRealtimeClientSecret, type OpenAIRealtimeOrbAdapter, } from './openai-realtime/index.js';
6
+ export { createGeminiLiveAdapter, type GeminiLiveAdapterConfig, type GeminiLiveCallbacks, type GeminiLiveInlineData, type GeminiLiveOrbAdapter, type GeminiLiveServerMessage, type GeminiLiveSession, } from './gemini-live/index.js';
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';
@@ -0,0 +1,129 @@
1
+ import { OrbAdapter } from '../types.js';
2
+ interface LKAnalyserResult {
3
+ calculateVolume: () => number;
4
+ cleanup: () => Promise<void>;
5
+ }
6
+ interface LKAudioTrack {
7
+ mediaStreamTrack: MediaStreamTrack;
8
+ }
9
+ interface LKRemoteAudioTrack extends LKAudioTrack {
10
+ attach(): HTMLMediaElement;
11
+ detach(): HTMLMediaElement[];
12
+ }
13
+ interface LKTrackPublication<TTrack extends LKAudioTrack = LKRemoteAudioTrack> {
14
+ track?: TTrack;
15
+ source: string;
16
+ }
17
+ interface LKParticipant {
18
+ isLocal: boolean;
19
+ attributes?: Record<string, string>;
20
+ getTrackPublication(source: string): LKTrackPublication | undefined;
21
+ kind?: number;
22
+ }
23
+ interface LKLocalParticipant {
24
+ setMicrophoneEnabled(enabled: boolean): Promise<LKTrackPublication<LKAudioTrack> | undefined>;
25
+ getTrackPublication?(source: string): LKTrackPublication<LKAudioTrack> | undefined;
26
+ }
27
+ interface LKRoom {
28
+ connect(serverUrl: string, token: string, options?: Record<string, unknown>): Promise<void>;
29
+ disconnect(): void;
30
+ on: unknown;
31
+ off?: unknown;
32
+ removeListener?: unknown;
33
+ remoteParticipants: Map<string, LKParticipant>;
34
+ localParticipant: LKLocalParticipant;
35
+ state: string;
36
+ }
37
+ interface LKCreateAudioAnalyser<TTrack = unknown> {
38
+ (track: TTrack, options?: Record<string, unknown>): LKAnalyserResult;
39
+ }
40
+ type LiveKitTokenOptionValue = string | (() => string);
41
+ export interface LiveKitConnectionDetails {
42
+ /** LiveKit server URL, e.g. "wss://your-project.livekit.cloud". */
43
+ serverUrl: string;
44
+ /** Short-lived participant token generated by LiveKit or your token endpoint. */
45
+ participantToken: string;
46
+ }
47
+ export interface LiveKitResolvedTokenOptions {
48
+ roomName?: string;
49
+ participantName?: string;
50
+ participantIdentity?: string;
51
+ participantMetadata?: string;
52
+ participantAttributes?: Record<string, string>;
53
+ agentName?: string;
54
+ agentMetadata?: string;
55
+ deployment?: string;
56
+ }
57
+ export interface LiveKitTokenOptions {
58
+ roomName?: LiveKitTokenOptionValue;
59
+ participantName?: LiveKitTokenOptionValue;
60
+ participantIdentity?: LiveKitTokenOptionValue;
61
+ participantMetadata?: LiveKitTokenOptionValue;
62
+ participantAttributes?: Record<string, string> | (() => Record<string, string>);
63
+ agentName?: LiveKitTokenOptionValue;
64
+ agentMetadata?: LiveKitTokenOptionValue;
65
+ deployment?: LiveKitTokenOptionValue;
66
+ }
67
+ export interface LiveKitTokenSource {
68
+ fetch(options?: LiveKitResolvedTokenOptions, force?: boolean): Promise<LiveKitConnectionDetails>;
69
+ }
70
+ interface LiveKitManagedBaseConfig<TTrack = unknown> {
71
+ /** The createAudioAnalyser function from livekit-client. */
72
+ createAudioAnalyser: LKCreateAudioAnalyser<TTrack>;
73
+ /** The Room constructor from livekit-client. */
74
+ RoomClass: new (...args: never[]) => LKRoom;
75
+ /** LiveKit room.connect options passed through unchanged. */
76
+ connectOptions?: Record<string, unknown>;
77
+ /** Enable the local microphone after connecting. Defaults to true. */
78
+ enableMicrophone?: boolean;
79
+ /** Options passed to token sources or getConnectionDetails. Values may be resolved per start. */
80
+ tokenOptions?: LiveKitTokenOptions;
81
+ }
82
+ /** App-managed mode: subscribe to a pre-existing Room. */
83
+ interface LiveKitRoomConfig<TTrack = unknown> {
84
+ /** A connected Room instance from livekit-client. */
85
+ room: LKRoom;
86
+ /** The createAudioAnalyser function from livekit-client. */
87
+ createAudioAnalyser: LKCreateAudioAnalyser<TTrack>;
88
+ }
89
+ /** Recommended mode: fetch connection details when the orb starts. */
90
+ interface LiveKitConnectionDetailsConfig<TTrack = unknown> extends LiveKitManagedBaseConfig<TTrack> {
91
+ getConnectionDetails(options: LiveKitResolvedTokenOptions): Promise<LiveKitConnectionDetails>;
92
+ tokenSource?: never;
93
+ serverUrl?: never;
94
+ participantToken?: never;
95
+ }
96
+ /** Convenience mode: use a LiveKit TokenSource such as TokenSource.endpoint or sandboxTokenServer. */
97
+ interface LiveKitTokenSourceConfig<TTrack = unknown> extends LiveKitManagedBaseConfig<TTrack> {
98
+ tokenSource: LiveKitTokenSource;
99
+ getConnectionDetails?: never;
100
+ serverUrl?: never;
101
+ participantToken?: never;
102
+ }
103
+ /** Advanced mode: pass already-generated static credentials. */
104
+ interface LiveKitStaticConnectionConfig<TTrack = unknown> extends LiveKitManagedBaseConfig<TTrack> {
105
+ /** LiveKit server URL, e.g. "wss://your-project.livekit.cloud". */
106
+ serverUrl: string;
107
+ /** Short-lived participant token. Generate this on your server. */
108
+ participantToken: string;
109
+ getConnectionDetails?: never;
110
+ tokenSource?: never;
111
+ }
112
+ type LiveKitManagedConfig<TTrack = unknown> = LiveKitConnectionDetailsConfig<TTrack> | LiveKitTokenSourceConfig<TTrack> | LiveKitStaticConnectionConfig<TTrack>;
113
+ export type LiveKitAdapterConfig<TTrack = unknown> = LiveKitRoomConfig<TTrack> | LiveKitManagedConfig<TTrack>;
114
+ export interface LiveKitOrbAdapter extends OrbAdapter {
115
+ /** Connect to the LiveKit room and start tracking agent state. */
116
+ start(): Promise<void>;
117
+ /** Disconnect from the LiveKit room. */
118
+ stop(): Promise<void>;
119
+ }
120
+ /**
121
+ * Creates an OrbAdapter for LiveKit Agents.
122
+ *
123
+ * Managed modes create and own a Room. App-managed mode listens to a Room that
124
+ * your app already connected. The adapter emits signal-native orb-ui state,
125
+ * including LiveKit `thinking` as `OrbState` `"thinking"`, local microphone
126
+ * audio as `inputVolume`, and agent audio as `outputVolume`.
127
+ */
128
+ export declare function createLiveKitAdapter<TTrack = unknown>(config: LiveKitAdapterConfig<TTrack>): LiveKitOrbAdapter | OrbAdapter;
129
+ export {};
@@ -0,0 +1,37 @@
1
+ import { OrbAdapter } from '../types.js';
2
+ import { OutputVolumeCalibrationSource, OutputVolumeSample } from '../audio-level.js';
3
+ export interface OpenAIRealtimeClientSecret {
4
+ value: string;
5
+ }
6
+ export interface OpenAIRealtimeAdapterConfig {
7
+ /** Fetch a newly minted Realtime client secret for every session start. */
8
+ getClientSecret(): Promise<string | OpenAIRealtimeClientSecret>;
9
+ /** Defaults to OpenAI's GA WebRTC calls endpoint. */
10
+ callsUrl?: string;
11
+ /** Defaults to `{ audio: true }`. */
12
+ mediaStreamConstraints?: MediaStreamConstraints;
13
+ /** Runtime override for tests, React Native shims, or custom browser wrappers. */
14
+ getUserMedia?: (constraints: MediaStreamConstraints) => Promise<MediaStream>;
15
+ /** Runtime override for custom WebRTC implementations. */
16
+ createPeerConnection?: () => RTCPeerConnection;
17
+ /** Runtime override for custom fetch implementations. */
18
+ fetch?: typeof fetch;
19
+ /** Runtime override for custom audio element ownership. */
20
+ createAudioElement?: () => HTMLAudioElement;
21
+ /** Return undefined to disable browser-side volume metering. */
22
+ createAudioContext?: () => AudioContext | undefined;
23
+ /** Optional live-tunable output shaping. A getter is read for every meter sample. */
24
+ outputVolumeCalibration?: OutputVolumeCalibrationSource;
25
+ /** Receives raw, shaped, and smoothed output levels for diagnostics. */
26
+ onOutputVolumeSample?: (sample: OutputVolumeSample) => void;
27
+ }
28
+ export interface OpenAIRealtimeOrbAdapter extends OrbAdapter {
29
+ start(): Promise<void>;
30
+ stop(): Promise<void>;
31
+ }
32
+ /**
33
+ * Creates a managed browser WebRTC adapter for the OpenAI Realtime API.
34
+ * Standard API keys stay on the app's server; the adapter only receives a
35
+ * short-lived client secret.
36
+ */
37
+ export declare function createOpenAIRealtimeAdapter(config: OpenAIRealtimeAdapterConfig): OpenAIRealtimeOrbAdapter;
@@ -0,0 +1,46 @@
1
+ import { OrbAdapter } from '../types.js';
2
+ type PipecatListener = (...args: unknown[]) => void;
3
+ /** Minimal PipecatClient surface used by orb-ui. */
4
+ export interface PipecatClientLike {
5
+ on(event: string, listener: PipecatListener): unknown;
6
+ off?(event: string, listener: PipecatListener): unknown;
7
+ removeListener?(event: string, listener: PipecatListener): unknown;
8
+ connect(...args: unknown[]): Promise<unknown>;
9
+ disconnect(): void | Promise<void>;
10
+ state?: string;
11
+ }
12
+ export interface PipecatParticipantLike {
13
+ id?: string;
14
+ name?: string;
15
+ local?: boolean;
16
+ }
17
+ export interface PipecatAdapterOptions {
18
+ /**
19
+ * Starts and connects the Pipecat client. Override this for transport-specific
20
+ * connection params or `startBotAndConnect()` endpoints.
21
+ */
22
+ connect?: () => void | Promise<unknown>;
23
+ /** Disconnects the Pipecat client. Defaults to `client.disconnect()`. */
24
+ disconnect?: () => void | Promise<void>;
25
+ /**
26
+ * Optional filter for multi-participant transports. Remote audio from local
27
+ * participants is ignored automatically.
28
+ */
29
+ isBotParticipant?: (participant: PipecatParticipantLike) => boolean;
30
+ /** Play remote bot audio tracks automatically. Defaults to true. */
31
+ playRemoteAudio?: boolean;
32
+ /** Runtime override for custom audio element ownership. */
33
+ createAudioElement?: () => HTMLAudioElement;
34
+ }
35
+ export interface PipecatOrbAdapter extends OrbAdapter {
36
+ start(): Promise<void>;
37
+ stop(): Promise<void>;
38
+ }
39
+ /**
40
+ * Creates a signal-native adapter for Pipecat's JavaScript client.
41
+ *
42
+ * The adapter is transport-agnostic: Daily, SmallWebRTC, Pipecat Cloud, and
43
+ * custom transports all expose the same RTVI events through `PipecatClient`.
44
+ */
45
+ export declare function createPipecatAdapter(client: PipecatClientLike, options?: PipecatAdapterOptions): PipecatOrbAdapter;
46
+ export {};
@@ -1,11 +1,7 @@
1
- import { OrbState, OrbAdapter } from '../components/Orb/Orb.types.js';
2
- export type { OrbState, OrbAdapter };
3
- export interface AdapterCallbacks {
4
- onStateChange: (state: OrbState) => void;
5
- onVolumeChange: (volume: number) => void;
6
- }
1
+ import { AdapterCallbacks, LegacyOrbAdapter, OrbAdapter, OrbSignal, OrbSignalListener, OrbState } from '../components/Orb/Orb.types.js';
2
+ export type { AdapterCallbacks, LegacyOrbAdapter, OrbAdapter, OrbSignal, OrbSignalListener, OrbState, };
7
3
  /**
8
- * Shared mic volume curve — rescale real-world mic range to 0–1 with pow shaping.
9
- * Used by both Vapi and ElevenLabs adapters for consistent listening visuals.
4
+ * Shared mic volume curve — rescale real-world mic range to 0–1 with pow shaping
5
+ * for custom provider adapters that need browser-side input metering.
10
6
  */
11
7
  export declare function normalizeMicVolume(v: number): number;
@@ -28,8 +28,8 @@ interface VapiMessage {
28
28
  * call-end → 'idle'
29
29
  * error → 'error'
30
30
  *
31
- * Volume: raw Vapi values are normalized (noise gate + EMA) before being
32
- * passed to onVolumeChange, so themes receive a clean 0–1 signal.
31
+ * Volume: raw Vapi values are normalized (noise gate + EMA) before being emitted
32
+ * as outputVolume while the assistant is speaking.
33
33
  *
34
34
  * @param client - A Vapi instance from @vapi-ai/web
35
35
  * @param options - Optional config (e.g. assistantId to pass to vapi.start())
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=0;function a(t){let n=t<e?0:(t-e)/(1-e),r=n>i?.8:.5;return i+=(n-i)*r,i}return{async start(){await n.start(r?.assistantId)},stop(){n.stop()},subscribe({onStateChange:e,onVolumeChange:r}){let{emitState:o,clearTimer:s}=t(e),c=`idle`,l=!1,u=()=>{l=!0,c=`listening`,o(`listening`)},d=()=>{l=!1,c=`idle`,y(),o(`idle`),r(0),i=0},f=()=>{l&&(c=`speaking`,o(`speaking`),v())},p=()=>{l&&(y(),c=`listening`,o(`listening`))},m=0,h=0,g=0,_=()=>{c===`speaking`&&(h+=(m-h)*.1,r(h)),g=requestAnimationFrame(_)},v=()=>{g||=requestAnimationFrame(_)},y=()=>{g&&=(cancelAnimationFrame(g),0),h=0,m=0},b=e=>{if(c===`speaking`){let t=a(e);m=t/(t+.3)}},x=()=>{},S=e=>{console.error(`[orb-ui/vapi] Error:`,e),y(),o(`error`),r(0),i=0};n.on(`call-start`,u),n.on(`call-end`,d),n.on(`speech-start`,f),n.on(`speech-end`,p),n.on(`volume-level`,b),n.on(`message`,x),n.on(`error`,S);let C=n.start.bind(n);return n.start=async(...e)=>(o(`connecting`),C(...e)),()=>{s(),n.removeListener(`call-start`,u),n.removeListener(`call-end`,d),n.removeListener(`speech-start`,f),n.removeListener(`speech-end`,p),n.removeListener(`volume-level`,b),n.removeListener(`message`,x),n.removeListener(`error`,S),n.start=C}}}}function r(e,t){let n=null,r=null,i=new Set;function a(e){i.forEach(t=>t.onStateChange(e))}function o(e){i.forEach(t=>t.onVolumeChange(e))}function s(){r||=setInterval(()=>{if(!n)return;let e=n.getOutputVolume();o(Math.min(e*2,1))},33)}function c(){r&&=(clearInterval(r),null),o(0)}let l={onStatusChange:({status:e})=>{e===`connecting`&&a(`connecting`)},onConnect:()=>{a(`listening`)},onModeChange:({mode:e})=>{e===`speaking`?(a(`speaking`),s()):(a(`listening`),c())},onDisconnect:()=>{c(),a(`idle`),o(0),n=null},onError:e=>{console.error(`[orb-ui/elevenlabs] Error:`,e),c(),a(`error`),o(0),n=null}};return{subscribe(e){return i.add(e),()=>{i.delete(e),i.size===0&&c()}},async start(){if(!n)try{n=await e.startSession({...t,...l})}catch(e){console.error(`[orb-ui/elevenlabs] startSession failed:`,e),a(`error`),o(0)}},async stop(){if(n){c();try{await n.endSession()}catch(e){console.error(`[orb-ui/elevenlabs] endSession failed:`,e)}n=null}}}}exports.createElevenLabsAdapter=r,exports.createVapiAdapter=n;
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;