orb-ui 0.7.0 → 0.8.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 +77 -23
- package/dist/adapters/audio-level.d.ts +57 -20
- package/dist/adapters/elevenlabs/index.d.ts +13 -2
- package/dist/adapters/gemini-live/index.d.ts +9 -5
- package/dist/adapters/index.d.ts +3 -2
- package/dist/adapters/livekit/browser.d.ts +9 -5
- package/dist/adapters/livekit/index.d.ts +9 -5
- package/dist/adapters/openai-realtime/index.d.ts +9 -5
- package/dist/adapters/pipecat/index.d.ts +9 -5
- package/dist/adapters/types.d.ts +0 -5
- package/dist/adapters/vapi/index.d.ts +29 -3
- package/dist/adapters/volume-presets.d.ts +35 -0
- package/dist/adapters.cjs +1 -1
- package/dist/adapters.js +405 -457
- package/dist/components/Orb/Orb.d.ts +1 -1
- package/dist/components/Orb/Orb.types.d.ts +87 -14
- package/dist/components/Orb/OrbThemeProvider.d.ts +16 -0
- package/dist/components/Orb/index.d.ts +6 -1
- package/dist/components/Orb/signals.d.ts +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/livekit-7Re8E7By.js +394 -0
- package/dist/livekit-C36Kmz6s.cjs +1 -0
- package/dist/livekit-adapter.cjs +1 -1
- package/dist/livekit-adapter.js +6 -4
- package/dist/orb-ui.cjs +7 -7
- package/dist/orb-ui.js +1343 -512
- package/dist/themes/bars/BarsTheme.d.ts +8 -4
- package/dist/themes/circle/CircleTheme.d.ts +8 -4
- package/dist/themes/cloud/CloudTheme.d.ts +8 -4
- package/dist/themes/config.d.ts +151 -0
- package/dist/themes/css-variables.d.ts +5 -0
- package/dist/themes/debug/DebugTheme.d.ts +11 -6
- package/dist/themes/radial/RadialTheme.d.ts +8 -2
- package/dist/themes/slots.d.ts +4 -0
- package/package.json +3 -2
- package/dist/livekit-CukEeYFK.js +0 -316
- package/dist/livekit-Dt-QZ6Gs.cjs +0 -1
package/README.md
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
# orb-ui
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Voice agent UI that feels alive.**
|
|
4
|
+
|
|
5
|
+
Expressive, accessible React components for realtime voice agents. Connect Vapi, ElevenLabs, LiveKit, Pipecat, OpenAI Realtime, Gemini Live, or your own voice stack through one consistent UI layer.
|
|
4
6
|
|
|
5
7
|
<p align="center">
|
|
6
8
|
<a href="https://orb-ui.com">
|
|
7
|
-
<img src="
|
|
9
|
+
<img src="demo/public/og-image-v2.jpg" alt="orb-ui — Voice agent UI that feels alive" width="900" />
|
|
8
10
|
</a>
|
|
9
11
|
</p>
|
|
10
12
|
|
|
11
13
|
<p align="center">
|
|
12
|
-
<a href="https://orb-ui.com">Live
|
|
14
|
+
<a href="https://orb-ui.com">Live demo</a> · <a href="https://orb-ui.com/docs">Documentation</a> · <a href="https://orb-ui.com/playground">Playground</a> · <a href="https://www.npmjs.com/package/orb-ui">npm</a> · <a href="https://github.com/alexanderqchen/orb-ui">Star on GitHub</a>
|
|
13
15
|
</p>
|
|
14
16
|
|
|
15
17
|
```jsx
|
|
@@ -25,6 +27,9 @@ export function VoiceOrb() {
|
|
|
25
27
|
}
|
|
26
28
|
```
|
|
27
29
|
|
|
30
|
+
Vapi uses its existing microphone track for listening motion and its assistant audio events for
|
|
31
|
+
speaking motion. The adapter keeps microphone and output calibration separate.
|
|
32
|
+
|
|
28
33
|
## Install
|
|
29
34
|
|
|
30
35
|
Install the component package:
|
|
@@ -67,20 +72,23 @@ Every provider ends at the same React API:
|
|
|
67
72
|
|
|
68
73
|
The only difference is how the adapter obtains a provider session:
|
|
69
74
|
|
|
70
|
-
| Provider
|
|
71
|
-
|
|
|
72
|
-
| Vapi
|
|
73
|
-
| ElevenLabs
|
|
74
|
-
| LiveKit
|
|
75
|
-
| Pipecat
|
|
76
|
-
| OpenAI Realtime | Return a fresh short-lived client secret from `getClientSecret` |
|
|
77
|
-
| Gemini Live
|
|
75
|
+
| Provider | Required browser setup |
|
|
76
|
+
| ------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
|
|
77
|
+
| [Vapi guide](https://orb-ui.com/docs/adapters/vapi) | Pass a configured Vapi client plus `assistantId` |
|
|
78
|
+
| [ElevenLabs guide](https://orb-ui.com/docs/adapters/elevenlabs) | Pass `Conversation` plus an `agentId`, signed URL, or conversation token |
|
|
79
|
+
| [LiveKit guide](https://orb-ui.com/docs/adapters/livekit) | Provide a token endpoint and optional agent name |
|
|
80
|
+
| [Pipecat guide](https://orb-ui.com/docs/adapters/pipecat) | Pass a configured `PipecatClient` plus its connect callback |
|
|
81
|
+
| [OpenAI Realtime guide](https://orb-ui.com/docs/adapters/openai-realtime) | Return a fresh short-lived client secret from `getClientSecret` |
|
|
82
|
+
| [Gemini Live guide](https://orb-ui.com/docs/adapters/gemini-live) | Open the official Google Live session in `connect` |
|
|
78
83
|
|
|
79
84
|
The adapter owns provider event mapping and emits one consistent `OrbSignal`. OpenAI and Gemini
|
|
80
85
|
standard API keys, and LiveKit participant-token signing, stay on your server. See the
|
|
81
86
|
[adapter overview](https://orb-ui.com/docs/adapters/overview) for the responsibility boundary and
|
|
82
87
|
advanced setup shapes.
|
|
83
88
|
|
|
89
|
+
For an app-owned WebRTC, WebSocket, telephony, or speech runtime, follow the
|
|
90
|
+
[custom integration guide](https://orb-ui.com/docs/adapters/custom).
|
|
91
|
+
|
|
84
92
|
## Quick Start
|
|
85
93
|
|
|
86
94
|
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.
|
|
@@ -212,7 +220,16 @@ function App() {
|
|
|
212
220
|
const [state, setState] = useState('idle')
|
|
213
221
|
const [volume, setVolume] = useState(0)
|
|
214
222
|
|
|
215
|
-
return
|
|
223
|
+
return (
|
|
224
|
+
<Orb
|
|
225
|
+
signal={{
|
|
226
|
+
state,
|
|
227
|
+
inputVolume: state === 'listening' ? volume : 0,
|
|
228
|
+
outputVolume: state === 'speaking' ? volume : 0,
|
|
229
|
+
}}
|
|
230
|
+
theme="circle"
|
|
231
|
+
/>
|
|
232
|
+
)
|
|
216
233
|
}
|
|
217
234
|
```
|
|
218
235
|
|
|
@@ -226,6 +243,44 @@ function App() {
|
|
|
226
243
|
}
|
|
227
244
|
```
|
|
228
245
|
|
|
246
|
+
### Theme presets and overrides
|
|
247
|
+
|
|
248
|
+
Theme strings keep the current balanced behavior. Choose `calm` or `expressive`, then override only
|
|
249
|
+
the theme-specific values your product needs:
|
|
250
|
+
|
|
251
|
+
```jsx
|
|
252
|
+
<Orb
|
|
253
|
+
signal={signal}
|
|
254
|
+
theme={{
|
|
255
|
+
name: 'circle',
|
|
256
|
+
preset: 'calm',
|
|
257
|
+
appearance: { colors: { listening: '#8b9cff', speaking: '#f4f7ff' } },
|
|
258
|
+
motion: { responseExponent: 0.9, activityRiseMs: 80, activityFallMs: 180 },
|
|
259
|
+
}}
|
|
260
|
+
/>
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
See the [theme customization guide](https://orb-ui.com/docs/themes/customization) for every
|
|
264
|
+
theme-specific appearance, geometry, and motion field.
|
|
265
|
+
|
|
266
|
+
For application-wide defaults, stable internal slots, responsive CSS variables, or completely
|
|
267
|
+
custom artwork, use the advanced customization layer:
|
|
268
|
+
|
|
269
|
+
```tsx
|
|
270
|
+
import { Orb, OrbThemeProvider } from 'orb-ui'
|
|
271
|
+
;<OrbThemeProvider theme={{ name: 'circle', preset: 'calm' }}>
|
|
272
|
+
<Orb
|
|
273
|
+
adapter={adapter}
|
|
274
|
+
style={{ '--orb-ui-size': 'clamp(180px, 32vw, 320px)' }}
|
|
275
|
+
slotProps={{ surface: { className: 'brand-orb__surface' } }}
|
|
276
|
+
/>
|
|
277
|
+
</OrbThemeProvider>
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
Pass `renderTheme` when your product needs entirely custom DOM, SVG, canvas, or WebGL artwork. Its
|
|
281
|
+
renderer receives normalized input/output activity plus accessible root/control props, while Orb
|
|
282
|
+
continues to manage provider subscription and session start/stop behavior.
|
|
283
|
+
|
|
229
284
|
### External session controls
|
|
230
285
|
|
|
231
286
|
Keep the orb as a passive visual when start and stop controls belong elsewhere in your layout.
|
|
@@ -267,9 +322,8 @@ the orb with the typed style variable:
|
|
|
267
322
|
| Prop | Type | Default | Description |
|
|
268
323
|
| ------------- | ------------------------------------------------------ | --------- | ------------------------------------------------------- |
|
|
269
324
|
| `theme` | `'debug' \| 'circle' \| 'bars' \| 'cloud' \| 'radial'` | `'debug'` | Visual theme |
|
|
270
|
-
| `signal` | `OrbSignal` | — |
|
|
325
|
+
| `signal` | `OrbSignal` | — | Controlled signal with state and directional volumes |
|
|
271
326
|
| `state` | `OrbState` | `'idle'` | Conversation state (controlled mode) |
|
|
272
|
-
| `volume` | `number` | `0` | Audio volume, 0–1. Overrides signal/adapter volume. |
|
|
273
327
|
| `adapter` | `OrbAdapter` | — | Provider adapter (manages signal updates automatically) |
|
|
274
328
|
| `size` | `number` | `200` | Size in pixels |
|
|
275
329
|
| `className` | `string` | — | Optional class name for the rendered theme |
|
|
@@ -286,15 +340,15 @@ the orb with the typed style variable:
|
|
|
286
340
|
|
|
287
341
|
## Supported Providers
|
|
288
342
|
|
|
289
|
-
| Provider | Adapter
|
|
290
|
-
| ------------------------------------------------------------------------- |
|
|
291
|
-
| [Vapi](https://vapi.ai) | `createVapiAdapter` from `orb-ui/adapters`
|
|
292
|
-
| [ElevenLabs](https://elevenlabs.io/conversational-ai) | `createElevenLabsAdapter` from `orb-ui/adapters`
|
|
293
|
-
| [LiveKit](https://livekit.io) | `createLiveKitAdapter` from `orb-ui/adapters`
|
|
294
|
-
| [Pipecat](https://pipecat.ai) | `createPipecatAdapter` from `orb-ui/adapters`
|
|
295
|
-
| [OpenAI Realtime](https://developers.openai.com/api/docs/guides/realtime) | `createOpenAIRealtimeAdapter` from `orb-ui/adapters`
|
|
296
|
-
| [Gemini Live](https://ai.google.dev/gemini-api/docs/live-api) | `createGeminiLiveAdapter` from `orb-ui/adapters`
|
|
297
|
-
| Custom | Use controlled mode
|
|
343
|
+
| Provider | Adapter |
|
|
344
|
+
| ------------------------------------------------------------------------- | ------------------------------------------------------------------- |
|
|
345
|
+
| [Vapi](https://vapi.ai) | `createVapiAdapter` from `orb-ui/adapters` |
|
|
346
|
+
| [ElevenLabs](https://elevenlabs.io/conversational-ai) | `createElevenLabsAdapter` from `orb-ui/adapters` |
|
|
347
|
+
| [LiveKit](https://livekit.io) | `createLiveKitAdapter` from `orb-ui/adapters` |
|
|
348
|
+
| [Pipecat](https://pipecat.ai) | `createPipecatAdapter` from `orb-ui/adapters` |
|
|
349
|
+
| [OpenAI Realtime](https://developers.openai.com/api/docs/guides/realtime) | `createOpenAIRealtimeAdapter` from `orb-ui/adapters` |
|
|
350
|
+
| [Gemini Live](https://ai.google.dev/gemini-api/docs/live-api) | `createGeminiLiveAdapter` from `orb-ui/adapters` |
|
|
351
|
+
| Custom | Use controlled mode with a directional `signal` or build an adapter |
|
|
298
352
|
|
|
299
353
|
## Development
|
|
300
354
|
|
|
@@ -1,28 +1,65 @@
|
|
|
1
|
-
export interface
|
|
2
|
-
/** Raw
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
1
|
+
export interface VolumeAmplitudeCalibration {
|
|
2
|
+
/** Raw values at or below this level are treated as silence. */
|
|
3
|
+
silenceFloor: number;
|
|
4
|
+
/** Raw value representing ordinary conversational speech. Maps to 0.5. */
|
|
5
|
+
speechReference: number;
|
|
6
|
+
/** Raw value representing a strong, uncommon speech peak. Maps to 1. */
|
|
7
|
+
speechPeak: number;
|
|
8
|
+
}
|
|
9
|
+
export interface VolumeEnvelopeCalibration {
|
|
10
|
+
/** Milliseconds to move 90% toward a rising target. */
|
|
11
|
+
riseTimeMs: number;
|
|
12
|
+
/** Milliseconds to move 90% toward a falling target. */
|
|
13
|
+
fallTimeMs: number;
|
|
14
|
+
}
|
|
15
|
+
export interface VolumeCalibration {
|
|
16
|
+
amplitude: VolumeAmplitudeCalibration;
|
|
17
|
+
envelope: VolumeEnvelopeCalibration;
|
|
18
|
+
}
|
|
19
|
+
export interface VolumeCalibrationOverrides {
|
|
20
|
+
amplitude?: Partial<VolumeAmplitudeCalibration>;
|
|
21
|
+
envelope?: Partial<VolumeEnvelopeCalibration>;
|
|
22
|
+
}
|
|
23
|
+
export type VolumeCalibrationSource = VolumeCalibrationOverrides | (() => VolumeCalibrationOverrides);
|
|
24
|
+
export interface VolumeSample {
|
|
25
|
+
/** Unmodified value measured from the provider audio source. */
|
|
16
26
|
raw: number;
|
|
17
|
-
/** Value after
|
|
18
|
-
|
|
19
|
-
/**
|
|
27
|
+
/** Value after silence, reference, and peak mapping. */
|
|
28
|
+
mapped: number;
|
|
29
|
+
/** Stable envelope after elapsed-time rise/fall processing. */
|
|
20
30
|
normalized: number;
|
|
31
|
+
/** Elapsed time used for this envelope update. */
|
|
32
|
+
elapsedMs: number;
|
|
33
|
+
}
|
|
34
|
+
export interface VolumeCalibrationCapture {
|
|
35
|
+
silence: number[];
|
|
36
|
+
quiet: number[];
|
|
37
|
+
normal: number[];
|
|
38
|
+
energetic: number[];
|
|
39
|
+
}
|
|
40
|
+
export interface VolumeCalibrationMetrics {
|
|
41
|
+
silenceP99: number;
|
|
42
|
+
quietMedian: number;
|
|
43
|
+
normalMedian: number;
|
|
44
|
+
energeticMedian: number;
|
|
45
|
+
speechP99: number;
|
|
46
|
+
saturationRatio: number;
|
|
47
|
+
}
|
|
48
|
+
export interface VolumeCalibrationFit {
|
|
49
|
+
calibration: VolumeCalibration;
|
|
50
|
+
metrics: VolumeCalibrationMetrics;
|
|
51
|
+
}
|
|
52
|
+
export interface VolumeNormalizer {
|
|
53
|
+
sample(rawValue: number, timestampMs?: number): VolumeSample;
|
|
54
|
+
reset(value?: number): void;
|
|
21
55
|
}
|
|
22
56
|
export interface MediaStreamTrackVolumeMeter {
|
|
23
57
|
stop(): Promise<void>;
|
|
24
58
|
}
|
|
25
59
|
export type AudioContextSource = () => AudioContext | undefined;
|
|
26
|
-
export declare const
|
|
27
|
-
export declare function
|
|
60
|
+
export declare const DEFAULT_VOLUME_CALIBRATION: VolumeCalibration;
|
|
61
|
+
export declare function mapVolumeAmplitude(rawValue: number, calibration: VolumeAmplitudeCalibration): number;
|
|
62
|
+
export declare function calibrateVolume(rawValue: number, previous: number, elapsedMs: number, defaults?: VolumeCalibration, source?: VolumeCalibrationSource): VolumeSample;
|
|
63
|
+
export declare function createVolumeNormalizer(defaults?: VolumeCalibration, source?: VolumeCalibrationSource): VolumeNormalizer;
|
|
64
|
+
export declare function fitVolumeCalibration(capture: VolumeCalibrationCapture, envelope?: VolumeEnvelopeCalibration): VolumeCalibrationFit;
|
|
28
65
|
export declare function createMediaStreamTrackVolumeMeter(track: MediaStreamTrack, createAudioContext: AudioContextSource, onVolume: (volume: number) => void): MediaStreamTrackVolumeMeter | undefined;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { OrbAdapter } from '../types.js';
|
|
2
|
+
import { VolumeCalibrationSource, VolumeSample } from '../audio-level.js';
|
|
2
3
|
export type ElevenLabsMode = 'speaking' | 'listening';
|
|
3
4
|
export type ElevenLabsStatus = 'disconnected' | 'connecting' | 'connected' | 'disconnecting';
|
|
4
5
|
export type ElevenLabsConnectionType = 'websocket' | 'webrtc';
|
|
@@ -41,13 +42,23 @@ type ElevenLabsSessionAuth = {
|
|
|
41
42
|
signedUrl?: never;
|
|
42
43
|
connectionType?: 'webrtc';
|
|
43
44
|
};
|
|
44
|
-
|
|
45
|
+
type ElevenLabsSessionConfig = ElevenLabsSessionAuth & {
|
|
45
46
|
/** orb-ui expects a voice conversation, so text-only sessions are intentionally unsupported. */
|
|
46
47
|
textOnly?: false;
|
|
47
48
|
/** Allow @elevenlabs/client startSession options that orb-ui does not inspect. */
|
|
48
49
|
[key: string]: unknown;
|
|
49
50
|
};
|
|
50
|
-
export type
|
|
51
|
+
export type ElevenLabsConfig = ElevenLabsSessionConfig & {
|
|
52
|
+
/** Optional live-tunable input calibration overrides. */
|
|
53
|
+
inputVolumeCalibration?: VolumeCalibrationSource;
|
|
54
|
+
/** Optional live-tunable output calibration overrides. */
|
|
55
|
+
outputVolumeCalibration?: VolumeCalibrationSource;
|
|
56
|
+
/** Receives raw, mapped, and normalized input levels for diagnostics. */
|
|
57
|
+
onInputVolumeSample?: (sample: VolumeSample) => void;
|
|
58
|
+
/** Receives raw, mapped, and normalized output levels for diagnostics. */
|
|
59
|
+
onOutputVolumeSample?: (sample: VolumeSample) => void;
|
|
60
|
+
};
|
|
61
|
+
export type ElevenLabsStartSessionOptions = ElevenLabsSessionConfig & ElevenLabsCallbacks;
|
|
51
62
|
export interface ElevenLabsConversationClass {
|
|
52
63
|
startSession(options: ElevenLabsStartSessionOptions): Promise<ElevenLabsConversation>;
|
|
53
64
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { OrbAdapter } from '../types.js';
|
|
2
|
-
import {
|
|
2
|
+
import { VolumeCalibrationSource, VolumeSample } from '../audio-level.js';
|
|
3
3
|
export interface GeminiLiveInlineData {
|
|
4
4
|
data?: string;
|
|
5
5
|
mimeType?: string;
|
|
@@ -53,10 +53,14 @@ export interface GeminiLiveAdapterConfig {
|
|
|
53
53
|
getUserMedia?: (constraints: MediaStreamConstraints) => Promise<MediaStream>;
|
|
54
54
|
/** Runtime override for tests or custom browser wrappers. */
|
|
55
55
|
createAudioContext?: () => AudioContext;
|
|
56
|
-
/** Optional live-tunable
|
|
57
|
-
|
|
58
|
-
/**
|
|
59
|
-
|
|
56
|
+
/** Optional live-tunable input calibration overrides. */
|
|
57
|
+
inputVolumeCalibration?: VolumeCalibrationSource;
|
|
58
|
+
/** Optional live-tunable output calibration overrides. */
|
|
59
|
+
outputVolumeCalibration?: VolumeCalibrationSource;
|
|
60
|
+
/** Receives raw, mapped, and normalized input levels for diagnostics. */
|
|
61
|
+
onInputVolumeSample?: (sample: VolumeSample) => void;
|
|
62
|
+
/** Receives raw, mapped, and normalized output levels for diagnostics. */
|
|
63
|
+
onOutputVolumeSample?: (sample: VolumeSample) => void;
|
|
60
64
|
}
|
|
61
65
|
export interface GeminiLiveOrbAdapter extends OrbAdapter {
|
|
62
66
|
start(): Promise<void>;
|
package/dist/adapters/index.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
export { createVapiAdapter } from './vapi/index.js';
|
|
1
|
+
export { createVapiAdapter, type VapiAdapterOptions } from './vapi/index.js';
|
|
2
2
|
export { createElevenLabsAdapter, type ElevenLabsCallbacks, type ElevenLabsConfig, type ElevenLabsConnectionType, type ElevenLabsConversation, type ElevenLabsConversationClass, type ElevenLabsMode, type ElevenLabsOrbAdapter, type ElevenLabsStartSessionOptions, type ElevenLabsStatus, } from './elevenlabs/index.js';
|
|
3
3
|
export { createLiveKitAdapter, type LiveKitAdapterConfig, type LiveKitConnectionDetails, type LiveKitOrbAdapter, type LiveKitResolvedTokenOptions, type LiveKitTokenOptions, type LiveKitTokenSource, } from './livekit/index.js';
|
|
4
4
|
export { createPipecatAdapter, type PipecatAdapterOptions, type PipecatClientLike, type PipecatOrbAdapter, type PipecatParticipantLike, type PipecatTracksLike, } from './pipecat/index.js';
|
|
5
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
|
-
export {
|
|
7
|
+
export { DEFAULT_VOLUME_CALIBRATION, calibrateVolume, createVolumeNormalizer, fitVolumeCalibration, mapVolumeAmplitude, type VolumeAmplitudeCalibration, type VolumeCalibration, type VolumeCalibrationCapture, type VolumeCalibrationFit, type VolumeCalibrationMetrics, type VolumeCalibrationOverrides, type VolumeCalibrationSource, type VolumeEnvelopeCalibration, type VolumeNormalizer, type VolumeSample, } from './audio-level.js';
|
|
8
|
+
export { PROVIDER_VOLUME_CALIBRATIONS, type DirectionalVolumeCalibration } from './volume-presets.js';
|
|
8
9
|
export type { OrbAdapter, OrbSignal, OrbSignalListener, OrbState } from './types.js';
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { LiveKitOrbAdapter, LiveKitTokenOptions } from './index.js';
|
|
2
|
-
import {
|
|
2
|
+
import { VolumeCalibrationSource, VolumeSample } from '../audio-level.js';
|
|
3
3
|
interface LiveKitBrowserAdapterBase extends Omit<LiveKitTokenOptions, 'agentName' | 'roomName'> {
|
|
4
4
|
/** Agent dispatched into the room. Required for LiveKit Cloud sandbox sessions. */
|
|
5
5
|
agentName?: LiveKitTokenOptions['agentName'];
|
|
@@ -9,10 +9,14 @@ interface LiveKitBrowserAdapterBase extends Omit<LiveKitTokenOptions, 'agentName
|
|
|
9
9
|
connectOptions?: Record<string, unknown>;
|
|
10
10
|
/** Enable the local microphone after connecting. Defaults to true. */
|
|
11
11
|
enableMicrophone?: boolean;
|
|
12
|
-
/** Optional live-tunable
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
|
|
12
|
+
/** Optional live-tunable input calibration overrides. */
|
|
13
|
+
inputVolumeCalibration?: VolumeCalibrationSource;
|
|
14
|
+
/** Optional live-tunable output calibration overrides. */
|
|
15
|
+
outputVolumeCalibration?: VolumeCalibrationSource;
|
|
16
|
+
/** Receives raw, mapped, and normalized input levels for diagnostics. */
|
|
17
|
+
onInputVolumeSample?: (sample: VolumeSample) => void;
|
|
18
|
+
/** Receives raw, mapped, and normalized output levels for diagnostics. */
|
|
19
|
+
onOutputVolumeSample?: (sample: VolumeSample) => void;
|
|
16
20
|
}
|
|
17
21
|
export type LiveKitTokenEndpointOptions = Omit<RequestInit, 'body'>;
|
|
18
22
|
export interface LiveKitSandboxOptions {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { OrbAdapter } from '../types.js';
|
|
2
|
-
import {
|
|
2
|
+
import { VolumeCalibrationSource, VolumeSample } from '../audio-level.js';
|
|
3
3
|
interface LKAnalyserResult {
|
|
4
4
|
calculateVolume: () => number;
|
|
5
5
|
cleanup: () => Promise<void>;
|
|
@@ -69,10 +69,14 @@ export interface LiveKitTokenSource {
|
|
|
69
69
|
fetch(options?: LiveKitResolvedTokenOptions, force?: boolean): Promise<LiveKitConnectionDetails>;
|
|
70
70
|
}
|
|
71
71
|
interface LiveKitVolumeConfig {
|
|
72
|
-
/** Optional live-tunable
|
|
73
|
-
|
|
74
|
-
/**
|
|
75
|
-
|
|
72
|
+
/** Optional live-tunable input calibration overrides. */
|
|
73
|
+
inputVolumeCalibration?: VolumeCalibrationSource;
|
|
74
|
+
/** Optional live-tunable output calibration overrides. */
|
|
75
|
+
outputVolumeCalibration?: VolumeCalibrationSource;
|
|
76
|
+
/** Receives raw, mapped, and normalized input levels for diagnostics. */
|
|
77
|
+
onInputVolumeSample?: (sample: VolumeSample) => void;
|
|
78
|
+
/** Receives raw, mapped, and normalized output levels for diagnostics. */
|
|
79
|
+
onOutputVolumeSample?: (sample: VolumeSample) => void;
|
|
76
80
|
}
|
|
77
81
|
interface LiveKitManagedBaseConfig<TTrack = unknown> extends LiveKitVolumeConfig {
|
|
78
82
|
/** The createAudioAnalyser function from livekit-client. */
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { OrbAdapter } from '../types.js';
|
|
2
|
-
import {
|
|
2
|
+
import { VolumeCalibrationSource, VolumeSample } from '../audio-level.js';
|
|
3
3
|
export interface OpenAIRealtimeClientSecret {
|
|
4
4
|
value: string;
|
|
5
5
|
}
|
|
@@ -20,10 +20,14 @@ export interface OpenAIRealtimeAdapterConfig {
|
|
|
20
20
|
createAudioElement?: () => HTMLAudioElement;
|
|
21
21
|
/** Return undefined to disable browser-side volume metering. */
|
|
22
22
|
createAudioContext?: () => AudioContext | undefined;
|
|
23
|
-
/** Optional live-tunable
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
|
|
23
|
+
/** Optional live-tunable input calibration overrides. */
|
|
24
|
+
inputVolumeCalibration?: VolumeCalibrationSource;
|
|
25
|
+
/** Optional live-tunable output calibration overrides. */
|
|
26
|
+
outputVolumeCalibration?: VolumeCalibrationSource;
|
|
27
|
+
/** Receives raw, mapped, and normalized input levels for diagnostics. */
|
|
28
|
+
onInputVolumeSample?: (sample: VolumeSample) => void;
|
|
29
|
+
/** Receives raw, mapped, and normalized output levels for diagnostics. */
|
|
30
|
+
onOutputVolumeSample?: (sample: VolumeSample) => void;
|
|
27
31
|
}
|
|
28
32
|
export interface OpenAIRealtimeOrbAdapter extends OrbAdapter {
|
|
29
33
|
start(): Promise<void>;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { OrbAdapter } from '../types.js';
|
|
2
|
-
import { AudioContextSource,
|
|
2
|
+
import { AudioContextSource, VolumeCalibrationSource, VolumeSample } from '../audio-level.js';
|
|
3
3
|
type PipecatListener = (...args: unknown[]) => void;
|
|
4
4
|
/** Minimal PipecatClient surface used by orb-ui. */
|
|
5
5
|
export interface PipecatClientLike {
|
|
@@ -43,10 +43,14 @@ export interface PipecatAdapterOptions {
|
|
|
43
43
|
createAudioElement?: () => HTMLAudioElement;
|
|
44
44
|
/** Return undefined to disable browser-track volume metering. */
|
|
45
45
|
createAudioContext?: AudioContextSource;
|
|
46
|
-
/** Optional live-tunable
|
|
47
|
-
|
|
48
|
-
/**
|
|
49
|
-
|
|
46
|
+
/** Optional live-tunable input calibration overrides. */
|
|
47
|
+
inputVolumeCalibration?: VolumeCalibrationSource;
|
|
48
|
+
/** Optional live-tunable output calibration overrides. */
|
|
49
|
+
outputVolumeCalibration?: VolumeCalibrationSource;
|
|
50
|
+
/** Receives raw, mapped, and normalized input levels for diagnostics. */
|
|
51
|
+
onInputVolumeSample?: (sample: VolumeSample) => void;
|
|
52
|
+
/** Receives raw, mapped, and normalized output levels for diagnostics. */
|
|
53
|
+
onOutputVolumeSample?: (sample: VolumeSample) => void;
|
|
50
54
|
}
|
|
51
55
|
export interface PipecatOrbAdapter extends OrbAdapter {
|
|
52
56
|
start(): Promise<void>;
|
package/dist/adapters/types.d.ts
CHANGED
|
@@ -1,7 +1,2 @@
|
|
|
1
1
|
import { OrbAdapter, OrbSignal, OrbSignalListener, OrbState } from '../components/Orb/Orb.types.js';
|
|
2
2
|
export type { OrbAdapter, OrbSignal, OrbSignalListener, OrbState };
|
|
3
|
-
/**
|
|
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.
|
|
6
|
-
*/
|
|
7
|
-
export declare function normalizeMicVolume(v: number): number;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { OrbAdapter } from '../types.js';
|
|
2
|
+
import { AudioContextSource, VolumeCalibrationSource, VolumeSample } from '../audio-level.js';
|
|
2
3
|
interface VapiClient {
|
|
3
4
|
on(event: 'call-start', listener: () => void): void;
|
|
4
5
|
on(event: 'call-end', listener: () => void): void;
|
|
@@ -10,6 +11,20 @@ interface VapiClient {
|
|
|
10
11
|
removeListener(event: string, listener: (...args: unknown[]) => void): void;
|
|
11
12
|
start(...args: any[]): Promise<unknown>;
|
|
12
13
|
stop(): void;
|
|
14
|
+
/** Public SDK access to the existing call's microphone; no second capture. */
|
|
15
|
+
getDailyCallObject?(): {
|
|
16
|
+
participants(): {
|
|
17
|
+
local?: {
|
|
18
|
+
tracks?: {
|
|
19
|
+
audio?: {
|
|
20
|
+
state?: string;
|
|
21
|
+
persistentTrack?: MediaStreamTrack;
|
|
22
|
+
track?: MediaStreamTrack;
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
} | null;
|
|
13
28
|
}
|
|
14
29
|
interface VapiMessage {
|
|
15
30
|
type: string;
|
|
@@ -28,15 +43,26 @@ interface VapiMessage {
|
|
|
28
43
|
* call-end → 'idle'
|
|
29
44
|
* error → 'error'
|
|
30
45
|
*
|
|
31
|
-
* Volume: raw Vapi values are
|
|
32
|
-
* as outputVolume while the assistant is speaking.
|
|
46
|
+
* Volume: raw Vapi values are mapped through the provider profile and emitted
|
|
47
|
+
* as a stable normalized outputVolume envelope while the assistant is speaking.
|
|
48
|
+
* Input: meters the SDK-owned local audio track when getDailyCallObject exists.
|
|
33
49
|
*
|
|
34
50
|
* @param client - A Vapi instance from @vapi-ai/web
|
|
35
51
|
* @param options - Optional config (e.g. assistantId to pass to vapi.start())
|
|
36
52
|
*/
|
|
37
|
-
interface VapiAdapterOptions {
|
|
53
|
+
export interface VapiAdapterOptions {
|
|
38
54
|
/** Assistant ID passed to vapi.start() when the orb is clicked. */
|
|
39
55
|
assistantId?: string;
|
|
56
|
+
/** Return undefined to disable metering of the SDK-owned microphone track. */
|
|
57
|
+
createAudioContext?: AudioContextSource;
|
|
58
|
+
/** Optional live-tunable input calibration overrides. */
|
|
59
|
+
inputVolumeCalibration?: VolumeCalibrationSource;
|
|
60
|
+
/** Optional live-tunable output calibration overrides. */
|
|
61
|
+
outputVolumeCalibration?: VolumeCalibrationSource;
|
|
62
|
+
/** Receives raw microphone RMS, mapped, and normalized input levels. */
|
|
63
|
+
onInputVolumeSample?: (sample: VolumeSample) => void;
|
|
64
|
+
/** Receives raw, mapped, and normalized output levels for diagnostics. */
|
|
65
|
+
onOutputVolumeSample?: (sample: VolumeSample) => void;
|
|
40
66
|
}
|
|
41
67
|
export declare function createVapiAdapter(client: VapiClient, options?: VapiAdapterOptions): OrbAdapter;
|
|
42
68
|
export {};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { VolumeCalibration } from './audio-level.js';
|
|
2
|
+
export interface DirectionalVolumeCalibration {
|
|
3
|
+
input?: VolumeCalibration;
|
|
4
|
+
output?: VolumeCalibration;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Shipped provider baselines. The playground calibration runner generates
|
|
8
|
+
* replacements from guided raw-level captures without requiring manual sliders.
|
|
9
|
+
*/
|
|
10
|
+
export declare const PROVIDER_VOLUME_CALIBRATIONS: {
|
|
11
|
+
readonly vapi: {
|
|
12
|
+
readonly input: VolumeCalibration;
|
|
13
|
+
readonly output: VolumeCalibration;
|
|
14
|
+
};
|
|
15
|
+
readonly elevenlabs: {
|
|
16
|
+
readonly input: VolumeCalibration;
|
|
17
|
+
readonly output: VolumeCalibration;
|
|
18
|
+
};
|
|
19
|
+
readonly livekit: {
|
|
20
|
+
readonly input: VolumeCalibration;
|
|
21
|
+
readonly output: VolumeCalibration;
|
|
22
|
+
};
|
|
23
|
+
readonly pipecat: {
|
|
24
|
+
readonly input: VolumeCalibration;
|
|
25
|
+
readonly output: VolumeCalibration;
|
|
26
|
+
};
|
|
27
|
+
readonly openai: {
|
|
28
|
+
readonly input: VolumeCalibration;
|
|
29
|
+
readonly output: VolumeCalibration;
|
|
30
|
+
};
|
|
31
|
+
readonly gemini: {
|
|
32
|
+
readonly input: VolumeCalibration;
|
|
33
|
+
readonly output: VolumeCalibration;
|
|
34
|
+
};
|
|
35
|
+
};
|
package/dist/adapters.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./livekit-Dt-QZ6Gs.cjs");var t=.12;function n(e){let t=`idle`,n=null;function r(r){if(n&&=(clearTimeout(n),null),t===`speaking`&&r===`listening`){n=setTimeout(()=>{t=r,e(r),n=null},350);return}t=r,e(r)}function i(){n&&=(clearTimeout(n),null)}return{emitState:r,clearTimer:i}}function r(e,r){let i=new Set,a=null;function o(){a||(a=e.start.bind(e),e.start=async(...e)=>(i.forEach(e=>e()),a(...e)))}function s(){i.size>0||!a||(e.start=a,a=null)}return{async start(){await e.start(r?.assistantId)},stop(){e.stop()},subscribe(r){let a={state:`idle`,volume:0,outputVolume:0},c=0;function l(e){let n=e<t?0:(e-t)/(1-t),r=n>c?.8:.5;return c+=(n-c)*r,c}function u(e){a=e,r(e)}function d(e){u({...a,...e,state:e.state??a.state})}let{emitState:f,clearTimer:p}=n(e=>d({state:e})),m=()=>f(`connecting`),h=`idle`,g=!1,_=()=>{g=!0,h=`listening`,f(`listening`),d({volume:0,outputVolume:0})},v=()=>{g=!1,h=`idle`,E(),f(`idle`),d({volume:0,outputVolume:0}),c=0},y=()=>{g&&(h=`speaking`,f(`speaking`),d({volume:0,outputVolume:0}),T())},b=()=>{g&&(E(),h=`listening`,d({volume:0,outputVolume:0}),c=0,f(`listening`))},x=0,S=0,C=0,w=()=>{h===`speaking`&&(S+=(x-S)*.1,d({volume:S,outputVolume:S})),C=requestAnimationFrame(w)},T=()=>{C||=requestAnimationFrame(w)},E=()=>{C&&=(cancelAnimationFrame(C),0),S=0,x=0},D=e=>{if(h===`speaking`){let t=l(e);x=t/(t+.3)}},O=()=>{},k=e=>{console.error(`[orb-ui/vapi] Error:`,e),g=!1,h=`error`,p(),E(),d({state:`error`,volume:0,outputVolume:0,error:e}),c=0};return e.on(`call-start`,_),e.on(`call-end`,v),e.on(`speech-start`,y),e.on(`speech-end`,b),e.on(`volume-level`,D),e.on(`message`,O),e.on(`error`,k),i.add(m),o(),()=>{p(),E(),c=0,e.removeListener(`call-start`,_),e.removeListener(`call-end`,v),e.removeListener(`speech-start`,y),e.removeListener(`speech-end`,b),e.removeListener(`volume-level`,D),e.removeListener(`message`,O),e.removeListener(`error`,k),i.delete(m),s()}}}}function i(e,t){let n=null,r=0,i=null,a=null,o={state:`idle`,volume:0,inputVolume:0,outputVolume:0},s=`idle`,c=new Set;function l(e){o=e,c.forEach(t=>t(e))}function u(e){o={...o,...e,state:e.state??o.state},l(o)}function d(e){s=e,u({state:e})}function f(){a||=setInterval(()=>{if(n){if(s===`listening`){let e=Math.min(n.getInputVolume()*2,1);u({volume:e,inputVolume:e})}else if(s===`speaking`){let e=Math.min(n.getOutputVolume()*2,1);u({volume:e,outputVolume:e})}}},33)}function p(){a&&=(clearInterval(a),null)}function m(){p(),u({volume:0,inputVolume:0,outputVolume:0})}function h(){s=`idle`,u({state:`idle`,volume:0,inputVolume:0,outputVolume:0})}function g(e){return e===r}function _(e){return{onStatusChange:({status:t})=>{g(e)&&t===`connecting`&&d(`connecting`)},onConnect:()=>{g(e)&&(d(`listening`),f())},onModeChange:({mode:t})=>{g(e)&&(t===`speaking`?(d(`speaking`),f()):(d(`listening`),f()))},onDisconnect:()=>{g(e)&&(p(),n=null,h())},onError:t=>{g(e)&&(console.error(`[orb-ui/elevenlabs] Error:`,t),p(),s=`error`,u({state:`error`,volume:0,inputVolume:0,outputVolume:0,error:t}),n=null)}}}return{subscribe(e){return c.add(e),e(o),n&&(s===`listening`||s===`speaking`)&&f(),()=>{c.delete(e),c.size===0&&m()}},async start(){if(n||i)return i??void 0;r+=1;let a=r;return i=(async()=>{try{let r=await e.startSession({...t,..._(a)});if(!g(a)){await r.endSession().catch(e=>{console.error(`[orb-ui/elevenlabs] stale session cleanup failed:`,e)});return}n=r}catch(e){if(!g(a))return;console.error(`[orb-ui/elevenlabs] startSession failed:`,e),d(`error`),u({volume:0,inputVolume:0,outputVolume:0,error:e})}finally{i=null}})(),i},async stop(){let e=n;if(!e){i&&(r+=1,p(),h(),await i);return}let t=r;p();try{await e.endSession()}catch(e){console.error(`[orb-ui/elevenlabs] endSession failed:`,e)}n===e&&g(t)&&(n=null,h())}}}var a={connected:`connected`,disconnected:`disconnected`,transportStateChanged:`transportStateChanged`,botReady:`botReady`,botDisconnected:`botDisconnected`,error:`error`,messageError:`messageError`,deviceError:`deviceError`,localAudioLevel:`localAudioLevel`,remoteAudioLevel:`remoteAudioLevel`,botStartedSpeaking:`botStartedSpeaking`,botStoppedSpeaking:`botStoppedSpeaking`,userStartedSpeaking:`userStartedSpeaking`,userStoppedSpeaking:`userStoppedSpeaking`,botLlmStarted:`botLlmStarted`,botTtsStarted:`botTtsStarted`},o=.002,s=4,c=.8,l=.6,u=.2,d={noiseFloor:.002,gain:5.1,exponent:.8,attack:.5,release:.22};function f(){if(typeof window>`u`)return;let e=window.AudioContext;return e?new e:void 0}function p(e){switch(e){case`initializing`:case`initialized`:case`authenticating`:case`authenticated`:case`connecting`:case`connected`:return`connecting`;case`ready`:return`listening`;case`disconnected`:case`disconnecting`:return`idle`;case`error`:return`error`;default:return}}function m(e){if(typeof e!=`number`||!Number.isFinite(e)||e<=o)return 0;let t=Math.min(1,Math.max(0,e-o));return Math.min(1,t*s)**+c}function h(e,t){let n=m(e),r=n>t?l:u;return t+(n-t)*r}function g(e){return typeof e==`object`&&!!e&&`kind`in e&&typeof e.kind==`string`}function _(t,n={}){let r=new Set,i=new Map,o={state:p(t.state??``)??`idle`,volume:0,inputVolume:0,outputVolume:0},s=!1,c=0,l=0,u=null,m=null,_,v;function y(){let e=typeof n.outputVolumeCalibration==`function`?n.outputVolumeCalibration():n.outputVolumeCalibration;return{...d,...e}}function b(e){o=e,r.forEach(t=>t(e))}function x(e,t){c=0,l=0,b({state:e,volume:0,inputVolume:0,outputVolume:0,...t===void 0?{}:{error:t}})}function S(e){if(o.state!==`listening`)return;c=h(e,c);let t=c;b({...o,volume:t,inputVolume:t,outputVolume:0})}function C(t,r){if(o.state!==`speaking`)return;if(r&&typeof r==`object`){let e=r;if(e.local||n.isBotParticipant&&!n.isBotParticipant(e))return}let i=e.r(typeof t==`number`?t:0,l,y);l=i.normalized,n.onOutputVolumeSample?.(i);let a=i.normalized;b({...o,volume:a,inputVolume:0,outputVolume:a})}function w(){u=null,_?.stop(),_=void 0}function T(){m=null,v?.stop(),v=void 0}function E(){w(),T()}function D(t){u===t&&_||(w(),u=t,_=e.i(t,n.createAudioContext??f,S),_||(u=null))}function O(t){m===t&&v||(T(),m=t,v=e.i(t,n.createAudioContext??f,C),v||(m=null))}function k(){let e=t.tracks?.();e?.local?.audio&&D(e.local.audio),e?.bot?.audio&&O(e.bot.audio)}function A(e){if(!e||typeof e!=`object`)return!0;let t=e;return t.local?!1:n.isBotParticipant?.(t)??!0}function j(e,t){if(n.playRemoteAudio===!1||!g(e)||e.kind!==`audio`||!A(t))return;let r=n.createAudioElement?.()??new Audio;r.autoplay=!0,r.srcObject=new MediaStream([e]),i.set(e,r),r.play().catch(()=>void 0)}function M(e){if(!g(e))return;let t=i.get(e);t&&(t.pause(),t.srcObject=null,t.remove(),i.delete(e))}function N(e,n){if(!g(e)||e.kind!==`audio`)return;let r=t.tracks?.().local?.audio;n?.local===!0||e===r?D(e):A(n)&&O(e),j(e,n)}function P(e){e===u&&w(),e===m&&T(),M(e)}function F(){i.forEach(e=>{e.pause(),e.srcObject=null,e.remove()}),i.clear()}function I(){E(),x(`idle`)}function L(){x(`listening`),k()}let R=[[a.connected,()=>x(`connecting`)],[a.botReady,L],[a.disconnected,I],[a.botDisconnected,I],[a.transportStateChanged,e=>{if(typeof e!=`string`)return;let t=p(e);t&&x(t)}],[a.userStartedSpeaking,()=>x(`listening`)],[a.userStoppedSpeaking,()=>{o.state===`listening`&&x(`thinking`)}],[a.botLlmStarted,()=>x(`thinking`)],[a.botTtsStarted,()=>x(`thinking`)],[a.botStartedSpeaking,()=>x(`speaking`)],[a.botStoppedSpeaking,()=>x(`listening`)],[a.localAudioLevel,e=>!_&&S(e)],[a.remoteAudioLevel,(e,t)=>!v&&C(e,t)],[`trackStarted`,N],[`trackStopped`,P],[a.error,e=>x(`error`,e)],[a.messageError,e=>x(`error`,e)],[a.deviceError,e=>x(`error`,e)]];function z(){s||(s=!0,R.forEach(([e,n])=>t.on(e,n)))}function B(){s&&(s=!1,R.forEach(([e,n])=>{t.off?t.off(e,n):t.removeListener?.(e,n)}),E(),F())}return{subscribe(e){return r.add(e),z(),e(o),()=>{r.delete(e),r.size===0&&B()}},async start(){x(`connecting`);try{await(n.connect?n.connect():t.connect())}catch(e){throw x(`error`,e),e}},async stop(){try{await(n.disconnect?n.disconnect():t.disconnect())}finally{E(),F(),x(`idle`)}}}}var v=`https://api.openai.com/v1/realtime/calls`,y=.015,b=8,x={noiseFloor:.003,gain:4,exponent:.8,attack:.55,release:.1};function S(){let e=window.AudioContext;return e?new e:void 0}function C(e){return Math.min(1,Math.max(0,(e*4)**.8))}function w(e,t,n){try{let r=t();if(!r)return;let i=r.createMediaStreamSource(e),a=r.createAnalyser();a.fftSize=512,a.smoothingTimeConstant=.25,i.connect(a);let o=new Float32Array(a.fftSize),s=setInterval(()=>{a.getFloatTimeDomainData(o);let e=0;for(let t of o)e+=t*t;n(Math.sqrt(e/o.length))},33);return{async stop(){clearInterval(s),i.disconnect(),a.disconnect(),r.state!==`closed`&&await r.close()}}}catch{return}}function T(e){let t=typeof e==`string`?e:e.value;if(!t)throw Error(`[orb-ui/openai-realtime] getClientSecret returned an empty value.`);return t}function E(t){let n=new Set,r={state:`idle`,volume:0,inputVolume:0,outputVolume:0},i=null,a=null,o=null,s=null,c,l,u=0,d=0,f=!1;function p(){let e=typeof t.outputVolumeCalibration==`function`?t.outputVolumeCalibration():t.outputVolumeCalibration;return{...x,...e}}function m(e){r=e,n.forEach(t=>t(e))}function h(e,t){r.state===e&&t===void 0||(e!==`speaking`&&(d=0),m({state:e,volume:0,inputVolume:0,outputVolume:0,...t===void 0?{}:{error:t}}))}function g(e){if(r.state!==`listening`)return;let t=C(e);m({...r,volume:t,inputVolume:t,outputVolume:0})}function _(n){let i=e.r(n,d,p);d=i.normalized,t.onOutputVolumeSample?.(i);let a=i.normalized;if(a>y)u=0,r.state!==`speaking`&&h(`speaking`);else if(r.state===`speaking`&&(u+=1,u>=b)){u=0,h(`listening`);return}r.state===`speaking`&&m({...r,volume:a,inputVolume:0,outputVolume:a})}function E(e){switch(e.type){case`session.created`:case`session.updated`:h(`listening`);break;case`input_audio_buffer.speech_started`:h(`listening`);break;case`input_audio_buffer.speech_stopped`:case`response.created`:h(`thinking`);break;case`response.output_audio.delta`:case`output_audio_buffer.started`:h(`speaking`);break;case`output_audio_buffer.stopped`:h(`listening`);break;case`response.done`:case`response.cancelled`:r.state!==`speaking`&&h(`listening`);break;case`error`:h(`error`,e.error??e);break}}async function D(e){f=!0,a?.close(),a=null,i?.close(),i=null,o?.getTracks().forEach(e=>e.stop()),o=null,s?.pause(),s&&(s.srcObject=null),s?.remove(),s=null,await Promise.all([c?.stop(),l?.stop()]),c=void 0,l=void 0,u=0,d=0,e&&h(`idle`),f=!1}return{subscribe(e){return n.add(e),e(r),()=>n.delete(e)},async start(){if(!i){h(`connecting`),f=!1;try{let e=t.getUserMedia??(e=>navigator.mediaDevices.getUserMedia(e)),n=t.createPeerConnection??(()=>new RTCPeerConnection),r=t.fetch??fetch,u=t.createAudioElement??(()=>new Audio),d=t.createAudioContext??S,p=T(await t.getClientSecret());o=await e(t.mediaStreamConstraints??{audio:!0}),c=w(o,d,g);let m=n();i=m,o.getAudioTracks().forEach(e=>m.addTrack(e,o)),s=u(),s.autoplay=!0,m.ontrack=e=>{let t=e.streams[0]??new MediaStream([e.track]);s&&(s.srcObject=t),s?.play().catch(()=>void 0),l?.stop(),l=w(t,d,_)},m.onconnectionstatechange=()=>{f||(m.connectionState===`failed`?h(`error`,Error(`[orb-ui/openai-realtime] WebRTC connection failed.`)):(m.connectionState===`disconnected`||m.connectionState===`closed`)&&h(`idle`))};let y=m.createDataChannel(`oai-events`);a=y,y.onopen=()=>h(`listening`),y.onmessage=e=>{try{E(JSON.parse(String(e.data)))}catch{}},y.onerror=e=>h(`error`,e),y.onclose=()=>{f||h(`idle`)};let b=await m.createOffer();await m.setLocalDescription(b);let x=await r(t.callsUrl??v,{method:`POST`,body:b.sdp,headers:{Authorization:`Bearer ${p}`,"Content-Type":`application/sdp`}});if(!x.ok){let e=await x.text();throw Error(`[orb-ui/openai-realtime] Session negotiation failed (${x.status}): ${e}`)}await m.setRemoteDescription({type:`answer`,sdp:await x.text()})}catch(e){throw await D(!1),h(`error`,e),e}}},async stop(){await D(!0)}}}var D=16e3,O={noiseFloor:.003,gain:4,exponent:.8,attack:.3,release:.1};function k(e){let t=0;for(let n of e)t+=n*n;return Math.sqrt(t/e.length)}function A(e){return Math.min(1,Math.max(0,(k(e)*4)**.8))}function j(e,t,n){if(t===n)return e;let r=t/n,i=Math.max(1,Math.round(e.length/r)),a=new Float32Array(i);for(let t=0;t<i;t+=1){let n=t*r,i=Math.floor(n),o=Math.min(e.length-1,i+1),s=n-i;a[t]=e[i]*(1-s)+e[o]*s}return a}function M(e){let t=new Uint8Array(e.length*2),n=new DataView(t.buffer);e.forEach((e,t)=>{let r=Math.max(-1,Math.min(1,e));n.setInt16(t*2,r<0?r*32768:r*32767,!0)});let r=``;return t.forEach(e=>{r+=String.fromCharCode(e)}),btoa(r)}function N(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);let r=new DataView(n.buffer),i=new Float32Array(Math.floor(n.length/2));for(let e=0;e<i.length;e+=1)i[e]=r.getInt16(e*2,!0)/32768;return i}function P(e){let t=e?.match(/rate=(\d+)/i);return t?Number(t[1]):24e3}function F(t){let n=new Set,r=new Set,i={state:`idle`,volume:0,inputVolume:0,outputVolume:0},a=null,o=null,s=null,c=null,l=null,u=null,d=null,f=null,p=null,m=!1,h=0,g=0,_=!1,v=!1;function y(){return t.activityDetection!==`server`}function b(){let e=typeof t.outputVolumeCalibration==`function`?t.outputVolumeCalibration():t.outputVolumeCalibration;return{...O,...e}}function x(e){i=e,n.forEach(t=>t(e))}function S(e,t){i.state===e&&t===void 0||(e!==`speaking`&&(g=0),x({state:e,volume:0,inputVolume:0,outputVolume:0,...t===void 0?{}:{error:t}}))}function C(){p&&=(clearTimeout(p),null)}function w(e){e>(t.speechThreshold??.04)?(!m&&y()&&a?.sendRealtimeInput({activityStart:{}}),m=!0,C(),i.state!==`listening`&&S(`listening`)):m&&!p&&(p=setTimeout(()=>{p=null,m=!1,y()&&a?.sendRealtimeInput({activityEnd:{}}),i.state===`listening`&&S(`thinking`)},t.speechEndDelayMs??500)),i.state===`listening`&&x({...i,volume:e,inputVolume:e,outputVolume:0})}function T(){r.forEach(e=>{try{e.stop()}catch{}e.disconnect()}),r.clear(),h=s?.currentTime??0}function E(){_&&r.size===0&&(_=!1,S(`listening`))}function F(e){if(!s||!d||!e.data)return;let t=N(e.data),n=s.createBuffer(1,t.length,P(e.mimeType));n.getChannelData(0).set(t);let a=s.createBufferSource();a.buffer=n,a.connect(d);let o=Math.max(s.currentTime,h);h=o+n.duration,r.add(a),a.onended=()=>{r.delete(a),a.disconnect(),E()},a.start(o),i.state!==`speaking`&&S(`speaking`)}function I(e){e.setupComplete&&S(`listening`);let t=e.serverContent;if(!t)return;if(t.interrupted){T(),_=!1,S(`listening`);return}let n=t.modelTurn?.parts?.filter(e=>e.inlineData?.data)??[];t.modelTurn&&n.length===0&&i.state!==`speaking`&&S(`thinking`),n.forEach(e=>F(e.inlineData)),t.waitingForInput&&(T(),S(`listening`)),(t.turnComplete||t.generationComplete)&&(_=!0,E())}function L(){if(!d)return;let n=new Float32Array(d.fftSize);f=setInterval(()=>{if(!d||i.state!==`speaking`)return;d.getFloatTimeDomainData(n);let r=e.r(k(n),g,b);g=r.normalized,t.onOutputVolumeSample?.(r);let a=r.normalized;x({...i,volume:a,inputVolume:0,outputVolume:a})},33)}function R(){!s||!o||!a||(c=s.createMediaStreamSource(o),l=s.createScriptProcessor(4096,1,1),u=s.createGain(),u.gain.value=0,c.connect(l),l.connect(u),u.connect(s.destination),l.onaudioprocess=e=>{if(!a||v)return;let n=e.inputBuffer.getChannelData(0);w(A(n));let r=j(n,s?.sampleRate??D,t.inputSampleRate??D);a.sendRealtimeInput({audio:{data:M(r),mimeType:`audio/pcm;rate=${t.inputSampleRate??D}`}})})}async function z(e){v=!0,C(),f&&clearInterval(f),f=null,T(),l?.disconnect(),c?.disconnect(),u?.disconnect(),d?.disconnect(),l=null,c=null,u=null,d=null,o?.getTracks().forEach(e=>e.stop()),o=null,s&&s.state!==`closed`&&await s.close(),s=null,a=null,m=!1,_=!1,g=0,e&&S(`idle`),v=!1}return{subscribe(e){return n.add(e),e(i),()=>n.delete(e)},async start(){if(!a){S(`connecting`),v=!1;try{let e=t.getUserMedia??(e=>navigator.mediaDevices.getUserMedia(e)),n=t.createAudioContext??(()=>new window.AudioContext);o=await e(t.mediaStreamConstraints??{audio:!0}),s=n(),s.state===`suspended`&&await s.resume(),d=s.createAnalyser(),d.fftSize=512,d.smoothingTimeConstant=.25,d.connect(s.destination),L(),a=await t.connect({onopen:()=>S(`listening`),onmessage:I,onerror:e=>S(`error`,e),onclose:()=>{v||S(`idle`)}}),R(),S(`listening`)}catch(e){throw a?.close(),await z(!1),S(`error`,e),e}}},async stop(){v=!0;try{m&&y()&&a?.sendRealtimeInput({activityEnd:{}}),a?.sendRealtimeInput({audioStreamEnd:!0})}catch{}a?.close(),await z(!0)}}}exports.DEFAULT_OUTPUT_VOLUME_CALIBRATION=e.n,exports.createElevenLabsAdapter=i,exports.createGeminiLiveAdapter=F,exports.createLiveKitAdapter=e.t,exports.createOpenAIRealtimeAdapter=E,exports.createPipecatAdapter=_,exports.createVapiAdapter=r;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./livekit-C36Kmz6s.cjs");var t=160;function n(e){let t=`idle`,n=null;function r(r){if(n&&=(clearTimeout(n),null),t===`speaking`&&r===`listening`){n=setTimeout(()=>{t=r,e(r),n=null},350);return}t=r,e(r)}function i(){n&&=(clearTimeout(n),null)}return{emitState:r,clearTimer:i}}function r(r,i){let a=new Set,o=new Set,s=null;function c(){s||(s=r.start.bind(r),r.start=async(...e)=>(a.forEach(e=>e()),s(...e)))}function l(){a.size>0||!s||(r.start=s,s=null)}return{async start(){await r.start(i?.assistantId)},stop(){o.forEach(e=>e()),r.stop()},subscribe(s){let u={state:`idle`,inputVolume:0,outputVolume:0},d=e.o(e.n.vapi.input,i?.inputVolumeCalibration),f=e.o(e.n.vapi.output,i?.outputVolumeCalibration);function p(e){u=e,s(e)}function m(e){p({...u,...e,state:e.state??u.state})}let{emitState:h,clearTimer:g}=n(e=>{v=e,e===`listening`?(I(),m({state:e,outputVolume:0})):m({state:e})}),_=()=>h(`connecting`),v=`idle`,y=!1,b,x,S;function C(e=!0){x?.stop().catch(()=>void 0),x=void 0,b=void 0,d.reset(),e&&u.inputVolume&&m({inputVolume:0})}function w(){let t;try{let e=r.getDailyCallObject?.()?.participants().local?.tracks?.audio;(!e?.state||e.state===`playable`)&&(t=e?.persistentTrack??e?.track)}catch{}if((t?.readyState===`ended`||t?.enabled===!1||t?.muted)&&(t=void 0),t===b||(C(),!t))return;b=t;let n=t;x=e.a(t,i?.createAudioContext??(()=>{if(!(typeof window>`u`||!window.AudioContext))return new window.AudioContext}),e=>{if(!y||b!==n)return;let t=d.sample(n.enabled&&!n.muted&&n.readyState!==`ended`?e:0);i?.onInputVolumeSample?.(t),m({inputVolume:t.normalized})})}function T(e=!0){S!==void 0&&clearInterval(S),S=void 0,C(e)}let E=()=>{y=!0,h(`listening`),r.getDailyCallObject&&(w(),S===void 0&&(S=setInterval(w,100)))},D=()=>{y=!1,v=`idle`,T(),I(),h(`idle`),m({inputVolume:0,outputVolume:0})},O=()=>{y&&(h(`speaking`),F())},k=()=>{y&&(A=0,j=0,M=0,h(`listening`))},A=0,j=0,M=0,N=0,P=e=>{if(v===`speaking`){let n=e-M<=t?j:A,r=f.sample(n,e);i?.onOutputVolumeSample?.(r),m({outputVolume:r.normalized})}N=requestAnimationFrame(P)},F=()=>{N||=requestAnimationFrame(P)},I=()=>{N&&=(cancelAnimationFrame(N),0),A=0,j=0,M=0,f.reset()},L=t=>{v===`speaking`&&(A=t,t>e.n.vapi.output.amplitude.silenceFloor&&(j=t,M=performance.now()))},R=()=>{},z=e=>{console.error(`[orb-ui/vapi] Error:`,e),y=!1,v=`error`,g(),T(),I(),m({state:`error`,inputVolume:0,outputVolume:0,error:e})};return r.on(`call-start`,E),r.on(`call-end`,D),r.on(`speech-start`,O),r.on(`speech-end`,k),r.on(`volume-level`,L),r.on(`message`,R),r.on(`error`,z),a.add(_),o.add(D),c(),()=>{g(),y=!1,T(!1),I(),r.removeListener(`call-start`,E),r.removeListener(`call-end`,D),r.removeListener(`speech-start`,O),r.removeListener(`speech-end`,k),r.removeListener(`volume-level`,L),r.removeListener(`message`,R),r.removeListener(`error`,z),a.delete(_),o.delete(D),l()}}}}function i(t,n){let{inputVolumeCalibration:r,outputVolumeCalibration:i,onInputVolumeSample:a,onOutputVolumeSample:o,...s}=n,c=null,l=0,u=null,d=null,f={state:`idle`,inputVolume:0,outputVolume:0},p=`idle`,m=e.o(e.n.elevenlabs.input,r),h=e.o(e.n.elevenlabs.output,i),g=new Set;function _(e){f=e,g.forEach(t=>t(e))}function v(e){f={...f,...e,state:e.state??f.state},_(f)}function y(e){if(p=e,e===`idle`||e===`connecting`||e===`error`){m.reset(),h.reset(),v({state:e,inputVolume:0,outputVolume:0});return}v({state:e})}function b(){d||=setInterval(()=>{if(!c)return;let e=m.sample(c.getInputVolume()),t=h.sample(c.getOutputVolume());a?.(e),o?.(t),v({inputVolume:e.normalized,outputVolume:t.normalized})},33)}function x(){d&&=(clearInterval(d),null)}function S(){x(),m.reset(),h.reset(),v({inputVolume:0,outputVolume:0})}function C(){p=`idle`,m.reset(),h.reset(),v({state:`idle`,inputVolume:0,outputVolume:0})}function w(e){return e===l}function T(e){return{onStatusChange:({status:t})=>{w(e)&&t===`connecting`&&y(`connecting`)},onConnect:()=>{w(e)&&(y(`listening`),b())},onModeChange:({mode:t})=>{w(e)&&(t===`speaking`?(y(`speaking`),b()):(y(`listening`),b()))},onDisconnect:()=>{w(e)&&(x(),c=null,C())},onError:t=>{w(e)&&(console.error(`[orb-ui/elevenlabs] Error:`,t),x(),p=`error`,v({state:`error`,inputVolume:0,outputVolume:0,error:t}),c=null)}}}return{subscribe(e){return g.add(e),e(f),c&&(p===`listening`||p===`speaking`)&&b(),()=>{g.delete(e),g.size===0&&S()}},async start(){if(c||u)return u??void 0;l+=1;let e=l;return u=(async()=>{try{let n=await t.startSession({...s,...T(e)});if(!w(e)){await n.endSession().catch(e=>{console.error(`[orb-ui/elevenlabs] stale session cleanup failed:`,e)});return}c=n}catch(t){if(!w(e))return;console.error(`[orb-ui/elevenlabs] startSession failed:`,t),y(`error`),v({inputVolume:0,outputVolume:0,error:t})}finally{u=null}})(),u},async stop(){let e=c;if(!e){u&&(l+=1,x(),C(),await u);return}let t=l;x();try{await e.endSession()}catch(e){console.error(`[orb-ui/elevenlabs] endSession failed:`,e)}c===e&&w(t)&&(c=null,C())}}}var a={connected:`connected`,disconnected:`disconnected`,transportStateChanged:`transportStateChanged`,botReady:`botReady`,botDisconnected:`botDisconnected`,error:`error`,messageError:`messageError`,deviceError:`deviceError`,localAudioLevel:`localAudioLevel`,remoteAudioLevel:`remoteAudioLevel`,botStartedSpeaking:`botStartedSpeaking`,botStoppedSpeaking:`botStoppedSpeaking`,userStartedSpeaking:`userStartedSpeaking`,userStoppedSpeaking:`userStoppedSpeaking`,botLlmStarted:`botLlmStarted`,botTtsStarted:`botTtsStarted`};function o(){if(typeof window>`u`)return;let e=window.AudioContext;return e?new e:void 0}function s(e){switch(e){case`initializing`:case`initialized`:case`authenticating`:case`authenticated`:case`connecting`:case`connected`:return`connecting`;case`ready`:return`listening`;case`disconnected`:case`disconnecting`:return`idle`;case`error`:return`error`;default:return}}function c(e){return typeof e==`object`&&!!e&&`kind`in e&&typeof e.kind==`string`}function l(t,n={}){let r=new Set,i=new Map,l={state:s(t.state??``)??`idle`,inputVolume:0,outputVolume:0},u=!1,d=null,f=null,p,m,h=e.o(e.n.pipecat.input,n.inputVolumeCalibration),g=e.o(e.n.pipecat.output,n.outputVolumeCalibration);function _(e){l=e,r.forEach(t=>t(e))}function v(e,t){let n=e===`idle`||e===`connecting`||e===`error`;n&&(h.reset(),g.reset()),_({...l,state:e,...n?{inputVolume:0,outputVolume:0}:{},...t===void 0?{}:{error:t}})}function y(e){let t=h.sample(typeof e==`number`?e:0);n.onInputVolumeSample?.(t),_({...l,inputVolume:t.normalized})}function b(e,t){if(t&&typeof t==`object`){let e=t;if(e.local||n.isBotParticipant&&!n.isBotParticipant(e))return}let r=g.sample(typeof e==`number`?e:0);n.onOutputVolumeSample?.(r),_({...l,outputVolume:r.normalized})}function x(){d=null,p?.stop(),p=void 0}function S(){f=null,m?.stop(),m=void 0}function C(){x(),S()}function w(t){d===t&&p||(x(),d=t,p=e.a(t,n.createAudioContext??o,y),p||(d=null))}function T(t){f===t&&m||(S(),f=t,m=e.a(t,n.createAudioContext??o,b),m||(f=null))}function E(){let e=t.tracks?.();e?.local?.audio&&w(e.local.audio),e?.bot?.audio&&T(e.bot.audio)}function D(e){if(!e||typeof e!=`object`)return!0;let t=e;return t.local?!1:n.isBotParticipant?.(t)??!0}function O(e,t){if(n.playRemoteAudio===!1||!c(e)||e.kind!==`audio`||!D(t))return;let r=n.createAudioElement?.()??new Audio;r.autoplay=!0,r.srcObject=new MediaStream([e]),i.set(e,r),r.play().catch(()=>void 0)}function k(e){if(!c(e))return;let t=i.get(e);t&&(t.pause(),t.srcObject=null,t.remove(),i.delete(e))}function A(e,n){if(!c(e)||e.kind!==`audio`)return;let r=t.tracks?.().local?.audio;n?.local===!0||e===r?w(e):D(n)&&T(e),O(e,n)}function j(e){e===d&&x(),e===f&&S(),k(e)}function M(){i.forEach(e=>{e.pause(),e.srcObject=null,e.remove()}),i.clear()}function N(){C(),v(`idle`)}function P(){v(`listening`),E()}function F(){l.state!==`speaking`&&v(`thinking`)}let I=[[a.connected,()=>v(`connecting`)],[a.botReady,P],[a.disconnected,N],[a.botDisconnected,N],[a.transportStateChanged,e=>{if(typeof e!=`string`)return;let t=s(e);t&&v(t)}],[a.userStartedSpeaking,()=>v(`listening`)],[a.userStoppedSpeaking,()=>{l.state===`listening`&&v(`thinking`)}],[a.botLlmStarted,F],[a.botTtsStarted,F],[a.botStartedSpeaking,()=>v(`speaking`)],[a.botStoppedSpeaking,()=>v(`listening`)],[a.localAudioLevel,e=>!p&&y(e)],[a.remoteAudioLevel,(e,t)=>!m&&b(e,t)],[`trackStarted`,A],[`trackStopped`,j],[a.error,e=>v(`error`,e)],[a.messageError,e=>v(`error`,e)],[a.deviceError,e=>v(`error`,e)]];function L(){u||(u=!0,I.forEach(([e,n])=>t.on(e,n)))}function R(){u&&(u=!1,I.forEach(([e,n])=>{t.off?t.off(e,n):t.removeListener?.(e,n)}),C(),M())}return{subscribe(e){return r.add(e),L(),e(l),()=>{r.delete(e),r.size===0&&R()}},async start(){v(`connecting`);try{await(n.connect?n.connect():t.connect())}catch(e){throw v(`error`,e),e}},async stop(){try{await(n.disconnect?n.disconnect():t.disconnect())}finally{C(),M(),v(`idle`)}}}}var u=`https://api.openai.com/v1/realtime/calls`,d=.015,f=8;function p(){let e=window.AudioContext;return e?new e:void 0}function m(e,t,n){try{let r=t();if(!r)return;let i=r.createMediaStreamSource(e),a=r.createAnalyser();a.fftSize=512,a.smoothingTimeConstant=.25,i.connect(a);let o=new Float32Array(a.fftSize),s=setInterval(()=>{a.getFloatTimeDomainData(o);let e=0;for(let t of o)e+=t*t;n(Math.sqrt(e/o.length))},33);return{async stop(){clearInterval(s),i.disconnect(),a.disconnect(),r.state!==`closed`&&await r.close()}}}catch{return}}function h(e){let t=typeof e==`string`?e:e.value;if(!t)throw Error(`[orb-ui/openai-realtime] getClientSecret returned an empty value.`);return t}function g(t){let n=new Set,r={state:`idle`,inputVolume:0,outputVolume:0},i=null,a=null,o=null,s=null,c,l,g=0,_=`unknown`,v=!1,y=!1,b=e.o(e.n.openai.input,t.inputVolumeCalibration),x=e.o(e.n.openai.output,t.outputVolumeCalibration);function S(e){r=e,n.forEach(t=>t(e))}function C(e,t){if(r.state===e&&t===void 0)return;let n=e===`idle`||e===`connecting`||e===`error`;n&&(b.reset(),x.reset()),S({...r,state:e,...n?{inputVolume:0,outputVolume:0}:{},...t===void 0?{}:{error:t}})}function w(e){let n=b.sample(e);t.onInputVolumeSample?.(n),S({...r,inputVolume:n.normalized})}function T(e){let n=x.sample(e);t.onOutputVolumeSample?.(n);let i=n.normalized;_===`unknown`&&!v&&r.state!==`idle`&&r.state!==`connecting`&&r.state!==`error`&&(i>d?(g=0,r.state!==`speaking`&&C(`speaking`)):r.state===`speaking`&&(g+=1,g>=f&&(g=0,C(`listening`)))),S({...r,outputVolume:i})}function E(e){switch(e.type){case`session.created`:case`session.updated`:C(`listening`);break;case`input_audio_buffer.speech_started`:v=!0,C(`listening`);break;case`input_audio_buffer.speech_stopped`:v=!1,C(_===`playing`?`speaking`:`thinking`);break;case`response.created`:!v&&_!==`playing`&&C(`thinking`);break;case`response.output_audio.delta`:v||C(`speaking`);break;case`output_audio_buffer.started`:_=`playing`,g=0,v||C(`speaking`);break;case`output_audio_buffer.stopped`:case`output_audio_buffer.cleared`:_=`stopped`,g=0,C(`listening`);break;case`response.done`:case`response.cancelled`:r.state!==`speaking`&&C(`listening`);break;case`error`:C(`error`,e.error??e);break}}async function D(e){y=!0,a?.close(),a=null,i?.close(),i=null,o?.getTracks().forEach(e=>e.stop()),o=null,s?.pause(),s&&(s.srcObject=null),s?.remove(),s=null,await Promise.all([c?.stop(),l?.stop()]),c=void 0,l=void 0,g=0,_=`unknown`,v=!1,b.reset(),x.reset(),e&&C(`idle`),y=!1}return{subscribe(e){return n.add(e),e(r),()=>n.delete(e)},async start(){if(!i){C(`connecting`),y=!1;try{let e=t.getUserMedia??(e=>navigator.mediaDevices.getUserMedia(e)),n=t.createPeerConnection??(()=>new RTCPeerConnection),r=t.fetch??fetch,d=t.createAudioElement??(()=>new Audio),f=t.createAudioContext??p,g=h(await t.getClientSecret());o=await e(t.mediaStreamConstraints??{audio:!0}),c=m(o,f,w);let _=n();i=_,o.getAudioTracks().forEach(e=>_.addTrack(e,o)),s=d(),s.autoplay=!0,_.ontrack=e=>{let t=e.streams[0]??new MediaStream([e.track]);s&&(s.srcObject=t),s?.play().catch(()=>void 0),l?.stop(),l=m(t,f,T)},_.onconnectionstatechange=()=>{y||(_.connectionState===`failed`?C(`error`,Error(`[orb-ui/openai-realtime] WebRTC connection failed.`)):(_.connectionState===`disconnected`||_.connectionState===`closed`)&&C(`idle`))};let v=_.createDataChannel(`oai-events`);a=v,v.onopen=()=>C(`listening`),v.onmessage=e=>{try{E(JSON.parse(String(e.data)))}catch{}},v.onerror=e=>C(`error`,e),v.onclose=()=>{y||C(`idle`)};let b=await _.createOffer();await _.setLocalDescription(b);let x=await r(t.callsUrl??u,{method:`POST`,body:b.sdp,headers:{Authorization:`Bearer ${g}`,"Content-Type":`application/sdp`}});if(!x.ok){let e=await x.text();throw Error(`[orb-ui/openai-realtime] Session negotiation failed (${x.status}): ${e}`)}await _.setRemoteDescription({type:`answer`,sdp:await x.text()})}catch(e){throw await D(!1),C(`error`,e),e}}},async stop(){await D(!0)}}}var _=16e3;function v(e){let t=0;for(let n of e)t+=n*n;return Math.sqrt(t/e.length)}function y(e,t,n){if(t===n)return e;let r=t/n,i=Math.max(1,Math.round(e.length/r)),a=new Float32Array(i);for(let t=0;t<i;t+=1){let n=t*r,i=Math.floor(n),o=Math.min(e.length-1,i+1),s=n-i;a[t]=e[i]*(1-s)+e[o]*s}return a}function b(e){let t=new Uint8Array(e.length*2),n=new DataView(t.buffer);e.forEach((e,t)=>{let r=Math.max(-1,Math.min(1,e));n.setInt16(t*2,r<0?r*32768:r*32767,!0)});let r=``;return t.forEach(e=>{r+=String.fromCharCode(e)}),btoa(r)}function x(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e+=1)n[e]=t.charCodeAt(e);let r=new DataView(n.buffer),i=new Float32Array(Math.floor(n.length/2));for(let e=0;e<i.length;e+=1)i[e]=r.getInt16(e*2,!0)/32768;return i}function S(e){let t=e?.match(/rate=(\d+)/i);return t?Number(t[1]):24e3}function C(t){let n=new Set,r=new Set,i={state:`idle`,inputVolume:0,outputVolume:0},a=null,o=null,s=null,c=null,l=null,u=null,d=null,f=null,p=null,m=!1,h=0,g=!1,C=!1,w=e.o(e.n.gemini.input,t.inputVolumeCalibration),T=e.o(e.n.gemini.output,t.outputVolumeCalibration);function E(){return t.activityDetection!==`server`}function D(e){i=e,n.forEach(t=>t(e))}function O(e,t){if(i.state===e&&t===void 0)return;let n=e===`idle`||e===`connecting`||e===`error`;n&&(w.reset(),T.reset()),D({...i,state:e,...n?{inputVolume:0,outputVolume:0}:{},...t===void 0?{}:{error:t}})}function k(){p&&=(clearTimeout(p),null)}function A(e){let n=w.sample(e);t.onInputVolumeSample?.(n);let r=n.normalized,o=t.speechThreshold??.04;n.mapped>o?(!m&&E()&&a?.sendRealtimeInput({activityStart:{}}),m=!0,k(),i.state!==`listening`&&O(`listening`)):m&&!p&&(p=setTimeout(()=>{p=null,m=!1,E()&&a?.sendRealtimeInput({activityEnd:{}}),i.state===`listening`&&O(`thinking`)},t.speechEndDelayMs??500)),D({...i,inputVolume:r})}function j(){r.forEach(e=>{try{e.stop()}catch{}e.disconnect()}),r.clear(),h=s?.currentTime??0}function M(){g&&r.size===0&&(g=!1,O(`listening`))}function N(e){if(!s||!d||!e.data)return;let t=x(e.data),n=s.createBuffer(1,t.length,S(e.mimeType));n.getChannelData(0).set(t);let a=s.createBufferSource();a.buffer=n,a.connect(d);let o=Math.max(s.currentTime,h);h=o+n.duration,r.add(a),a.onended=()=>{r.delete(a),a.disconnect(),M()},a.start(o),!m&&i.state!==`speaking`&&O(`speaking`)}function P(e){e.setupComplete&&O(`listening`);let t=e.serverContent;if(!t)return;if(t.interrupted){j(),g=!1,O(`listening`);return}let n=t.modelTurn?.parts?.filter(e=>e.inlineData?.data)??[];t.modelTurn&&n.length===0&&i.state!==`speaking`&&O(`thinking`),n.forEach(e=>N(e.inlineData)),t.waitingForInput&&(j(),O(`listening`)),(t.turnComplete||t.generationComplete)&&(g=!0,M())}function F(){if(!d)return;let e=new Float32Array(d.fftSize);f=setInterval(()=>{if(!d)return;d.getFloatTimeDomainData(e);let n=T.sample(v(e));t.onOutputVolumeSample?.(n),D({...i,outputVolume:n.normalized})},33)}function I(){!s||!o||!a||(c=s.createMediaStreamSource(o),l=s.createScriptProcessor(4096,1,1),u=s.createGain(),u.gain.value=0,c.connect(l),l.connect(u),u.connect(s.destination),l.onaudioprocess=e=>{if(!a||C)return;let n=e.inputBuffer.getChannelData(0);A(v(n));let r=y(n,s?.sampleRate??_,t.inputSampleRate??_);a.sendRealtimeInput({audio:{data:b(r),mimeType:`audio/pcm;rate=${t.inputSampleRate??_}`}})})}async function L(e){C=!0,k(),f&&clearInterval(f),f=null,j(),l?.disconnect(),c?.disconnect(),u?.disconnect(),d?.disconnect(),l=null,c=null,u=null,d=null,o?.getTracks().forEach(e=>e.stop()),o=null,s&&s.state!==`closed`&&await s.close(),s=null,a=null,m=!1,g=!1,w.reset(),T.reset(),e&&O(`idle`),C=!1}return{subscribe(e){return n.add(e),e(i),()=>n.delete(e)},async start(){if(!a){O(`connecting`),C=!1;try{let e=t.getUserMedia??(e=>navigator.mediaDevices.getUserMedia(e)),n=t.createAudioContext??(()=>new window.AudioContext);o=await e(t.mediaStreamConstraints??{audio:!0}),s=n(),s.state===`suspended`&&await s.resume(),d=s.createAnalyser(),d.fftSize=512,d.smoothingTimeConstant=.25,d.connect(s.destination),F(),a=await t.connect({onopen:()=>O(`listening`),onmessage:P,onerror:e=>O(`error`,e),onclose:()=>{C||O(`idle`)}}),I(),O(`listening`)}catch(e){throw a?.close(),await L(!1),O(`error`,e),e}}},async stop(){C=!0;try{m&&E()&&a?.sendRealtimeInput({activityEnd:{}}),a?.sendRealtimeInput({audioStreamEnd:!0})}catch{}a?.close(),await L(!0)}}}exports.DEFAULT_VOLUME_CALIBRATION=e.r,exports.PROVIDER_VOLUME_CALIBRATIONS=e.n,exports.calibrateVolume=e.i,exports.createElevenLabsAdapter=i,exports.createGeminiLiveAdapter=C,exports.createLiveKitAdapter=e.t,exports.createOpenAIRealtimeAdapter=g,exports.createPipecatAdapter=l,exports.createVapiAdapter=r,exports.createVolumeNormalizer=e.o,exports.fitVolumeCalibration=e.s,exports.mapVolumeAmplitude=e.c;
|