@sathamai/livekit-plugin 0.1.4 → 0.1.5

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
@@ -176,6 +176,22 @@ preset on the server and is not needed.
176
176
  - **Not supported:** video, and reconnection (a dropped connection ends the call with an
177
177
  unrecoverable error).
178
178
 
179
+ ## Background sound
180
+
181
+ LiveKit plays the agent's audio only during replies, so satham's server-mixed background sound is not used
182
+ here: `RealtimeModel` refuses `ambience` with a sound, and turns a preset agent's off. `AmbiencePlayer`
183
+ plays it in the room instead, on LiveKit's own `BackgroundAudioPlayer`:
184
+
185
+ ```ts
186
+ const ambience = new satham.AmbiencePlayer({ bed: voice.BuiltinAudioClip.OFFICE_AMBIENCE, strength: 1.0 });
187
+ await ambience.start({ room: ctx.room, agentSession: session });
188
+ ```
189
+
190
+ `bed` is a file or a LiveKit clip (or none, for typing alone), measured when the player starts so that
191
+ strength 1.0 is -35 dBFS RMS. Typing (`@sathamai/sdk`'s CC0 takes, or `typingSounds: [...]`) plays while
192
+ the agent is `'thinking'`, which is when a realtime agent's tools run, from 0.4 s in, capped at `strength`.
193
+ `ambience.update({ strength, typing, typingStrength })` changes it mid-call.
194
+
179
195
  ## Text to speech
180
196
 
181
197
  `TTS` gives an `AgentSession` with its own STT and LLM satham's voices, spoken by kural-1, satham's
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Background sound for a LiveKit agent (agents-js), played by LiveKit's own `BackgroundAudioPlayer`.
3
+ *
4
+ * `AmbiencePlayer` publishes a second audio track in the room: an optional room sound (`bed`, a file or
5
+ * one of LiveKit's `BuiltinAudioClip`s), and keyboard typing while a tool call runs longer than 0.4 s, from
6
+ * the typing takes bundled with `@sathamai/sdk`. It is on satham's scale: strength 1.0 puts any sound at
7
+ * -35 dBFS RMS (each file is measured when the player starts), and typing is capped at the room sound's
8
+ * level. It works with any LiveKit realtime model, satham's or the OpenAI plugin pointed at satham's
9
+ * OpenAI-compatible endpoint, since it follows the session's agent state: LiveKit puts a realtime agent in
10
+ * `'thinking'` while its tools run.
11
+ *
12
+ * LiveKit plays the agent's audio only during replies, so satham's server-mixed ambience is not used in
13
+ * LiveKit: the room sound would stop between replies. `RealtimeModel` refuses `ambience`, and turns a
14
+ * preset agent's server ambience off; use this player instead.
15
+ */
16
+ import { voice } from '@livekit/agents';
17
+ import type { Room, TrackPublishOptions } from '@livekit/rtc-node';
18
+ import { TypingCue } from '@sathamai/sdk';
19
+ /** A file path, or one of LiveKit's built-in clips. */
20
+ export type Sound = string | voice.BuiltinAudioClip;
21
+ /**
22
+ * A file's RMS (linear, full scale 1.0): over the whole file, or over its active 20 ms frames (within 30 dB
23
+ * of the loudest), as satham's server measures room sound and typing.
24
+ */
25
+ export declare function measure(path: string, activeOnly: boolean): Promise<number>;
26
+ export interface AmbiencePlayerOptions {
27
+ /** The room sound, looped: a file path or a `BuiltinAudioClip` (such as `OFFICE_AMBIENCE`); none for typing alone. */
28
+ bed?: Sound | null;
29
+ /** 0 to 2; 1.0 puts the room sound at -35 dBFS RMS, a linear gain (default 1.0). */
30
+ strength?: number;
31
+ /** Keyboard typing while a tool call runs longer than 0.4 s (default true). */
32
+ typing?: boolean;
33
+ /** 0 to 2, the same scale, capped at `strength` (default 1.0). */
34
+ typingStrength?: number;
35
+ /** Typing takes (file paths or clips); by default `@sathamai/sdk`'s own. */
36
+ typingSounds?: Sound[];
37
+ /** How long a tool runs before typing starts (ms; default 400). */
38
+ typingAfterMs?: number;
39
+ }
40
+ /**
41
+ * Room sound and keyboard typing for a LiveKit `AgentSession`, on satham's scale.
42
+ *
43
+ * `await player.start({ room: ctx.room, agentSession: session })` after the session starts, and
44
+ * `await player.close()` at the end.
45
+ */
46
+ export declare class AmbiencePlayer {
47
+ #private;
48
+ readonly cue: TypingCue;
49
+ constructor(options?: AmbiencePlayerOptions);
50
+ start(options: {
51
+ room: Room;
52
+ agentSession: voice.AgentSession;
53
+ trackPublishOptions?: TrackPublishOptions;
54
+ }): Promise<void>;
55
+ /** Change the level or typing mid-call; a new strength restarts the room sound at its new level. */
56
+ update(changes: {
57
+ strength?: number;
58
+ typing?: boolean;
59
+ typingStrength?: number;
60
+ }): void;
61
+ close(): Promise<void>;
62
+ }
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Background sound for a LiveKit agent (agents-js), played by LiveKit's own `BackgroundAudioPlayer`.
3
+ *
4
+ * `AmbiencePlayer` publishes a second audio track in the room: an optional room sound (`bed`, a file or
5
+ * one of LiveKit's `BuiltinAudioClip`s), and keyboard typing while a tool call runs longer than 0.4 s, from
6
+ * the typing takes bundled with `@sathamai/sdk`. It is on satham's scale: strength 1.0 puts any sound at
7
+ * -35 dBFS RMS (each file is measured when the player starts), and typing is capped at the room sound's
8
+ * level. It works with any LiveKit realtime model, satham's or the OpenAI plugin pointed at satham's
9
+ * OpenAI-compatible endpoint, since it follows the session's agent state: LiveKit puts a realtime agent in
10
+ * `'thinking'` while its tools run.
11
+ *
12
+ * LiveKit plays the agent's audio only during replies, so satham's server-mixed ambience is not used in
13
+ * LiveKit: the room sound would stop between replies. `RealtimeModel` refuses `ambience`, and turns a
14
+ * preset agent's server ambience off; use this player instead.
15
+ */
16
+ import { audioFramesFromFile, voice } from '@livekit/agents';
17
+ import { checkStrength, gainFor, TYPING_AFTER_MS, TypingCue, typingSounds } from '@sathamai/sdk';
18
+ /**
19
+ * A file's RMS (linear, full scale 1.0): over the whole file, or over its active 20 ms frames (within 30 dB
20
+ * of the loudest), as satham's server measures room sound and typing.
21
+ */
22
+ export async function measure(path, activeOnly) {
23
+ const parts = [];
24
+ const reader = audioFramesFromFile(path, { sampleRate: 24_000, numChannels: 1 }).getReader();
25
+ for (;;) {
26
+ const { value, done } = await reader.read();
27
+ if (done)
28
+ break;
29
+ parts.push(value.data);
30
+ }
31
+ const total = parts.reduce((n, p) => n + p.length, 0);
32
+ if (!total)
33
+ return 0;
34
+ const x = new Float64Array(total);
35
+ let at = 0;
36
+ for (const p of parts) {
37
+ for (let i = 0; i < p.length; i++)
38
+ x[at + i] = p[i] / 32768;
39
+ at += p.length;
40
+ }
41
+ let sum = 0;
42
+ for (const v of x)
43
+ sum += v * v;
44
+ const whole = Math.sqrt(sum / total);
45
+ const frames = Math.floor(total / 480);
46
+ if (!activeOnly || !frames)
47
+ return whole;
48
+ const levels = [];
49
+ for (let f = 0; f < frames; f++) {
50
+ let s = 0;
51
+ for (let i = f * 480; i < (f + 1) * 480; i++)
52
+ s += x[i] ** 2;
53
+ levels.push(Math.sqrt(s / 480));
54
+ }
55
+ const floor = Math.max(...levels) * 10 ** (-30 / 20);
56
+ let activeSum = 0;
57
+ let activeCount = 0;
58
+ for (const level of levels) {
59
+ if (level >= floor) {
60
+ activeSum += level * level;
61
+ activeCount += 1;
62
+ }
63
+ }
64
+ return activeCount ? Math.sqrt(activeSum / activeCount) : whole;
65
+ }
66
+ function pathOf(sound) {
67
+ return Object.values(voice.BuiltinAudioClip).includes(sound)
68
+ ? voice.getBuiltinAudioPath(sound)
69
+ : String(sound);
70
+ }
71
+ /**
72
+ * Room sound and keyboard typing for a LiveKit `AgentSession`, on satham's scale.
73
+ *
74
+ * `await player.start({ room: ctx.room, agentSession: session })` after the session starts, and
75
+ * `await player.close()` at the end.
76
+ */
77
+ export class AmbiencePlayer {
78
+ cue;
79
+ #bed;
80
+ #strength;
81
+ #typing;
82
+ #typingStrength;
83
+ #typingPaths;
84
+ #rms = new Map();
85
+ #player = null;
86
+ #session = null;
87
+ #bedHandle = null;
88
+ #typingHandle = null;
89
+ #onState = (ev) => {
90
+ if (ev.newState === 'thinking' && this.#typing)
91
+ this.cue.toolStarted('thinking');
92
+ else
93
+ this.cue.interrupt();
94
+ };
95
+ constructor(options = {}) {
96
+ this.#bed = options.bed != null ? pathOf(options.bed) : null;
97
+ this.#strength = checkStrength(options.strength ?? 1, 'strength');
98
+ this.#typing = options.typing ?? true;
99
+ this.#typingStrength = checkStrength(options.typingStrength ?? 1, 'typing_strength');
100
+ this.#typingPaths = (options.typingSounds ?? typingSounds()).map(pathOf);
101
+ if (this.#typing && !this.#typingPaths.length)
102
+ throw new Error('typing needs at least one typing sound');
103
+ this.cue = new TypingCue((on) => this.#onTyping(on), {
104
+ afterMs: options.typingAfterMs ?? TYPING_AFTER_MS,
105
+ });
106
+ }
107
+ async start(options) {
108
+ await this.measureSounds();
109
+ const player = new voice.BackgroundAudioPlayer();
110
+ await player.start({ room: options.room, trackPublishOptions: options.trackPublishOptions });
111
+ this.attach(player, options.agentSession);
112
+ }
113
+ /** @internal Measure every sound's level (`start` does this). */
114
+ async measureSounds() {
115
+ const paths = [...(this.#bed ? [this.#bed] : []), ...this.#typingPaths];
116
+ const levels = await Promise.all(paths.map((p) => measure(p, p !== this.#bed)));
117
+ paths.forEach((p, i) => {
118
+ this.#rms.set(p, levels[i]);
119
+ });
120
+ }
121
+ /** @internal Play through `player`, following `session`'s agent state (`start` does this). */
122
+ attach(player, session) {
123
+ this.#player = player;
124
+ this.#session = session;
125
+ session?.on(voice.AgentSessionEventTypes.AgentStateChanged, this.#onState);
126
+ this.#playBed();
127
+ }
128
+ /** @internal Follow an agent state change (as the session reports it). */
129
+ onAgentState(ev) {
130
+ this.#onState(ev);
131
+ }
132
+ /** Change the level or typing mid-call; a new strength restarts the room sound at its new level. */
133
+ update(changes) {
134
+ if (changes.typingStrength !== undefined) {
135
+ this.#typingStrength = checkStrength(changes.typingStrength, 'typing_strength');
136
+ }
137
+ if (changes.typing !== undefined) {
138
+ this.#typing = changes.typing;
139
+ if (!this.#typing)
140
+ this.cue.interrupt();
141
+ }
142
+ if (changes.strength !== undefined) {
143
+ this.#strength = checkStrength(changes.strength, 'strength');
144
+ const old = this.#bedHandle;
145
+ this.#bedHandle = null;
146
+ this.#playBed();
147
+ old?.stop();
148
+ }
149
+ }
150
+ async close() {
151
+ this.cue.close();
152
+ this.#session?.off(voice.AgentSessionEventTypes.AgentStateChanged, this.#onState);
153
+ this.#session = null;
154
+ const player = this.#player;
155
+ this.#player = null;
156
+ await player?.close();
157
+ }
158
+ #playBed() {
159
+ if (!this.#player || !this.#bed || this.#strength <= 0)
160
+ return;
161
+ const volume = gainFor(this.#rms.get(this.#bed) ?? 0, this.#strength);
162
+ this.#bedHandle = this.#player.play({ source: this.#bed, volume }, true);
163
+ }
164
+ #onTyping(on) {
165
+ if (!on) {
166
+ this.#typingHandle?.stop();
167
+ this.#typingHandle = null;
168
+ return;
169
+ }
170
+ const level = Math.min(this.#typingStrength, this.#strength);
171
+ if (!this.#player || level <= 0 || this.#typingHandle)
172
+ return;
173
+ const configs = this.#typingPaths.map((p) => ({
174
+ source: p,
175
+ volume: gainFor(this.#rms.get(p) ?? 0, level),
176
+ probability: 1 / this.#typingPaths.length,
177
+ }));
178
+ this.#typingHandle = this.#player.play(configs, true);
179
+ }
180
+ }
package/dist/index.d.ts CHANGED
@@ -12,7 +12,12 @@
12
12
  * // Or your own STT and LLM, with satham's voices:
13
13
  * const tts = new satham.TTS({ voice: 'malar', language: 'ta' });
14
14
  * const pipeline = new voice.AgentSession({ stt, llm, tts });
15
+ *
16
+ * // Background sound in the room: a room sound, and typing while tools run.
17
+ * const ambience = new satham.AmbiencePlayer({ bed: voice.BuiltinAudioClip.OFFICE_AMBIENCE, strength: 1.0 });
18
+ * await ambience.start({ room: ctx.room, agentSession: session });
15
19
  * ```
16
20
  */
21
+ export { AmbiencePlayer, type AmbiencePlayerOptions, measure, type Sound } from './ambience.js';
17
22
  export { INPUT_SAMPLE_RATE, type OptionsUpdate, RealtimeModel, type RealtimeModelOptions, RealtimeSession, } from './realtime.js';
18
23
  export { ChunkedStream, TTS, type TTSOptions, type TTSVoiceOptions } from './tts.js';
package/dist/index.js CHANGED
@@ -12,7 +12,12 @@
12
12
  * // Or your own STT and LLM, with satham's voices:
13
13
  * const tts = new satham.TTS({ voice: 'malar', language: 'ta' });
14
14
  * const pipeline = new voice.AgentSession({ stt, llm, tts });
15
+ *
16
+ * // Background sound in the room: a room sound, and typing while tools run.
17
+ * const ambience = new satham.AmbiencePlayer({ bed: voice.BuiltinAudioClip.OFFICE_AMBIENCE, strength: 1.0 });
18
+ * await ambience.start({ room: ctx.room, agentSession: session });
15
19
  * ```
16
20
  */
21
+ export { AmbiencePlayer, measure } from './ambience.js';
17
22
  export { INPUT_SAMPLE_RATE, RealtimeModel, RealtimeSession, } from './realtime.js';
18
23
  export { ChunkedStream, TTS } from './tts.js';
@@ -20,7 +20,10 @@
20
20
  * - `llm.tool()` tools are sent as OpenAI-style function definitions; each call the agent makes is run
21
21
  * by LiveKit, and its result goes back to the server, which then replies unless the tool returned
22
22
  * nothing;
23
- * - a change of language is emitted as `session_updated`.
23
+ * - a change of language is emitted as `session_updated`;
24
+ * - background sound is played in the room by `AmbiencePlayer`, LiveKit's own player, not by the server
25
+ * (LiveKit plays the agent's audio only during replies): `ambience` with a sound is refused, and a
26
+ * preset agent's server ambience is turned off when its call starts.
24
27
  */
25
28
  import { llm } from '@livekit/agents';
26
29
  import { AudioFrame } from '@livekit/rtc-node';
package/dist/realtime.js CHANGED
@@ -20,11 +20,14 @@
20
20
  * - `llm.tool()` tools are sent as OpenAI-style function definitions; each call the agent makes is run
21
21
  * by LiveKit, and its result goes back to the server, which then replies unless the tool returned
22
22
  * nothing;
23
- * - a change of language is emitted as `session_updated`.
23
+ * - a change of language is emitted as `session_updated`;
24
+ * - background sound is played in the room by `AmbiencePlayer`, LiveKit's own player, not by the server
25
+ * (LiveKit plays the agent's audio only during replies): `ambience` with a sound is refused, and a
26
+ * preset agent's server ambience is turned off when its call starts.
24
27
  */
25
28
  import { AudioByteStream, llm, log, stream } from '@livekit/agents';
26
29
  import { AudioFrame, AudioResampler } from '@livekit/rtc-node';
27
- import { Client, responseCreate, responseSay, sessionUpdate, toolResult, toWire, } from '@sathamai/sdk';
30
+ import { Client, inEffect, refuseServerAmbience, responseCreate, responseSay, sessionUpdate, toolResult, toWire, } from '@sathamai/sdk';
28
31
  /** Caller audio goes to satham as 16 kHz mono 16-bit PCM. */
29
32
  export const INPUT_SAMPLE_RATE = 16_000;
30
33
  /** How long `generateReply` and `say` wait for the reply to start. */
@@ -72,6 +75,7 @@ export class RealtimeModel extends llm.RealtimeModel {
72
75
  #limitsLoaded = null;
73
76
  constructor(options = {}) {
74
77
  const controls = controlsOf(options);
78
+ refuseServerAmbience(controls, 'LiveKit', 'AmbiencePlayer from @sathamai/livekit-plugin');
75
79
  const modalities = controls.modalities ?? ['text', 'audio'];
76
80
  super({
77
81
  messageTruncation: false,
@@ -120,6 +124,7 @@ export class RealtimeModel extends llm.RealtimeModel {
120
124
  /** Change controls for new calls and every live one (`session.update`). */
121
125
  updateOptions(changes) {
122
126
  const controls = controlsOf(changes);
127
+ refuseServerAmbience(controls, 'LiveKit', 'AmbiencePlayer from @sathamai/livekit-plugin');
123
128
  toWire(controls, 'session.update', this.client.limits);
124
129
  Object.assign(this.controls, controls);
125
130
  if (changes.toolChoice !== undefined)
@@ -216,6 +221,11 @@ export class RealtimeSession extends llm.RealtimeSession {
216
221
  }
217
222
  if (call.language)
218
223
  this.language = call.language;
224
+ if (inEffect(call.started.ambience).sound) {
225
+ // A preset agent's room sound would stop between replies here: AmbiencePlayer plays it instead.
226
+ this.#logger.warn("the agent's server ambience is turned off in LiveKit; play background sound with AmbiencePlayer");
227
+ this.#send({ type: 'session.update', ambience: null });
228
+ }
219
229
  call.on('event', (event) => this.#onEvent(event));
220
230
  call.on('close', (code) => {
221
231
  this.#ended = true;
@@ -470,6 +480,7 @@ export class RealtimeSession extends llm.RealtimeSession {
470
480
  }
471
481
  /** Change the call's controls (`session.update`); before it starts, its start. */
472
482
  updateOptions(options) {
483
+ refuseServerAmbience(controlsOf(options), 'LiveKit', 'AmbiencePlayer from @sathamai/livekit-plugin');
473
484
  if (options.toolChoice !== undefined) {
474
485
  this.#toolChoice = options.toolChoice;
475
486
  if (this.#call)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sathamai/livekit-plugin",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "description": "satham realtime speech-to-speech for LiveKit Agents (Node.js)",
5
5
  "keywords": [
6
6
  "satham",
@@ -40,7 +40,7 @@
40
40
  "prepack": "npm run build"
41
41
  },
42
42
  "dependencies": {
43
- "@sathamai/sdk": "^0.1.4"
43
+ "@sathamai/sdk": "^0.1.5"
44
44
  },
45
45
  "peerDependencies": {
46
46
  "@livekit/agents": "~1.10.0",