@livekit/agents-plugin-inworld 0.0.0-next-20260624041820

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.
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var import_agents_plugin_openai = require("@livekit/agents-plugin-openai");
3
+ var import_agents_plugins_test = require("@livekit/agents-plugins-test");
4
+ var import_vitest = require("vitest");
5
+ var import_tts = require("./tts.cjs");
6
+ const hasInworldConfig = Boolean(process.env.INWORLD_API_KEY && process.env.OPENAI_API_KEY);
7
+ if (hasInworldConfig) {
8
+ (0, import_vitest.describe)("Inworld", async () => {
9
+ await (0, import_agents_plugins_test.tts)(new import_tts.TTS(), new import_agents_plugin_openai.STT());
10
+ });
11
+ } else {
12
+ (0, import_vitest.describe)("Inworld", () => {
13
+ import_vitest.it.skip("requires INWORLD_API_KEY and OPENAI_API_KEY", () => {
14
+ });
15
+ });
16
+ }
17
+ //# sourceMappingURL=tts.test.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/tts.test.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { STT } from '@livekit/agents-plugin-openai';\nimport { tts } from '@livekit/agents-plugins-test';\nimport { describe, it } from 'vitest';\nimport { TTS } from './tts.js';\n\nconst hasInworldConfig = Boolean(process.env.INWORLD_API_KEY && process.env.OPENAI_API_KEY);\n\nif (hasInworldConfig) {\n describe('Inworld', async () => {\n await tts(new TTS(), new STT());\n });\n} else {\n describe('Inworld', () => {\n it.skip('requires INWORLD_API_KEY and OPENAI_API_KEY', () => {});\n });\n}\n"],"mappings":";AAGA,kCAAoB;AACpB,iCAAoB;AACpB,oBAA6B;AAC7B,iBAAoB;AAEpB,MAAM,mBAAmB,QAAQ,QAAQ,IAAI,mBAAmB,QAAQ,IAAI,cAAc;AAE1F,IAAI,kBAAkB;AACpB,8BAAS,WAAW,YAAY;AAC9B,cAAM,gCAAI,IAAI,eAAI,GAAG,IAAI,gCAAI,CAAC;AAAA,EAChC,CAAC;AACH,OAAO;AACL,8BAAS,WAAW,MAAM;AACxB,qBAAG,KAAK,+CAA+C,MAAM;AAAA,IAAC,CAAC;AAAA,EACjE,CAAC;AACH;","names":[]}
@@ -0,0 +1,16 @@
1
+ import { STT } from "@livekit/agents-plugin-openai";
2
+ import { tts } from "@livekit/agents-plugins-test";
3
+ import { describe, it } from "vitest";
4
+ import { TTS } from "./tts.js";
5
+ const hasInworldConfig = Boolean(process.env.INWORLD_API_KEY && process.env.OPENAI_API_KEY);
6
+ if (hasInworldConfig) {
7
+ describe("Inworld", async () => {
8
+ await tts(new TTS(), new STT());
9
+ });
10
+ } else {
11
+ describe("Inworld", () => {
12
+ it.skip("requires INWORLD_API_KEY and OPENAI_API_KEY", () => {
13
+ });
14
+ });
15
+ }
16
+ //# sourceMappingURL=tts.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/tts.test.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { STT } from '@livekit/agents-plugin-openai';\nimport { tts } from '@livekit/agents-plugins-test';\nimport { describe, it } from 'vitest';\nimport { TTS } from './tts.js';\n\nconst hasInworldConfig = Boolean(process.env.INWORLD_API_KEY && process.env.OPENAI_API_KEY);\n\nif (hasInworldConfig) {\n describe('Inworld', async () => {\n await tts(new TTS(), new STT());\n });\n} else {\n describe('Inworld', () => {\n it.skip('requires INWORLD_API_KEY and OPENAI_API_KEY', () => {});\n });\n}\n"],"mappings":"AAGA,SAAS,WAAW;AACpB,SAAS,WAAW;AACpB,SAAS,UAAU,UAAU;AAC7B,SAAS,WAAW;AAEpB,MAAM,mBAAmB,QAAQ,QAAQ,IAAI,mBAAmB,QAAQ,IAAI,cAAc;AAE1F,IAAI,kBAAkB;AACpB,WAAS,WAAW,YAAY;AAC9B,UAAM,IAAI,IAAI,IAAI,GAAG,IAAI,IAAI,CAAC;AAAA,EAChC,CAAC;AACH,OAAO;AACL,WAAS,WAAW,MAAM;AACxB,OAAG,KAAK,+CAA+C,MAAM;AAAA,IAAC,CAAC;AAAA,EACjE,CAAC;AACH;","names":[]}
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@livekit/agents-plugin-inworld",
3
+ "version": "0.0.0-next-20260624041820",
4
+ "description": "Inworld plugin for LiveKit Node Agents",
5
+ "main": "dist/index.js",
6
+ "require": "dist/index.cjs",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ "import": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ },
13
+ "require": {
14
+ "types": "./dist/index.d.cts",
15
+ "default": "./dist/index.cjs"
16
+ }
17
+ },
18
+ "author": "LiveKit",
19
+ "type": "module",
20
+ "repository": "git@github.com:livekit/agents-js.git",
21
+ "license": "Apache-2.0",
22
+ "files": [
23
+ "dist",
24
+ "src",
25
+ "README.md"
26
+ ],
27
+ "devDependencies": {
28
+ "@livekit/rtc-node": "^0.13.29",
29
+ "@microsoft/api-extractor": "^7.35.0",
30
+ "@types/ws": "^8.5.10",
31
+ "tsup": "^8.3.5",
32
+ "typescript": "^5.0.0",
33
+ "@livekit/agents": "0.0.0-next-20260624041820",
34
+ "@livekit/agents-plugin-openai": "0.0.0-next-20260624041820",
35
+ "@livekit/agents-plugins-test": "0.0.0-next-20260624041820"
36
+ },
37
+ "dependencies": {
38
+ "ws": "^8.18.0"
39
+ },
40
+ "peerDependencies": {
41
+ "@livekit/rtc-node": "^0.13.29",
42
+ "@livekit/agents": "0.0.0-next-20260624041820"
43
+ },
44
+ "scripts": {
45
+ "build": "tsup --onSuccess \"pnpm build:types\"",
46
+ "build:types": "tsc --declaration --emitDeclarationOnly && node ../../scripts/copyDeclarationOutput.js",
47
+ "clean": "rm -rf dist",
48
+ "clean:build": "pnpm clean && pnpm build",
49
+ "lint": "eslint -f unix \"src/**/*.{ts,js}\"",
50
+ "api:check": "api-extractor run --typescript-compiler-folder ../../node_modules/typescript",
51
+ "api:update": "api-extractor run --local --typescript-compiler-folder ../../node_modules/typescript --verbose"
52
+ }
53
+ }
package/src/index.ts ADDED
@@ -0,0 +1,21 @@
1
+ // SPDX-FileCopyrightText: 2024 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import { Plugin } from '@livekit/agents';
5
+ import './stt.js';
6
+ import './tts.js';
7
+
8
+ export * from './stt.js';
9
+ export * from './tts.js';
10
+
11
+ class InworldPlugin extends Plugin {
12
+ constructor() {
13
+ super({
14
+ title: 'Inworld',
15
+ version: __PACKAGE_VERSION__,
16
+ package: __PACKAGE_NAME__,
17
+ });
18
+ }
19
+ }
20
+
21
+ Plugin.registerPlugin(new InworldPlugin());
package/src/stt.ts ADDED
@@ -0,0 +1,521 @@
1
+ // SPDX-FileCopyrightText: 2026 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import {
5
+ type APIConnectOptions,
6
+ type AudioBuffer,
7
+ AudioByteStream,
8
+ Future,
9
+ Task,
10
+ createTimedString,
11
+ log,
12
+ mergeFrames,
13
+ normalizeLanguage,
14
+ shortuuid,
15
+ stt,
16
+ waitForAbort,
17
+ } from '@livekit/agents';
18
+ import { WebSocket } from 'ws';
19
+
20
+ const DEFAULT_MODEL = 'inworld/inworld-stt-1';
21
+ const DEFAULT_LANGUAGE = 'en-US';
22
+ const DEFAULT_SAMPLE_RATE = 16000;
23
+ const DEFAULT_NUM_CHANNELS = 1;
24
+ const DEFAULT_BASE_URL = 'https://api.inworld.ai/';
25
+ const DEFAULT_WS_URL = 'wss://api.inworld.ai/';
26
+ const WS_ENDPOINT = 'stt/v1/transcribe:streamBidirectional';
27
+ const REST_ENDPOINT = 'stt/v1/transcribe';
28
+ const AUDIO_DURATION_REPORT_INTERVAL = 5;
29
+
30
+ /** Supported Inworld STT model identifiers. */
31
+ export type STTModels = 'inworld/inworld-stt-1' | string;
32
+
33
+ /** Per-word timestamp entry returned by the Inworld STT API. */
34
+ export interface WordTimestamp {
35
+ word: string;
36
+ confidence?: number;
37
+ /** Start offset in seconds (streaming WebSocket). */
38
+ startTime?: number;
39
+ /** Start offset in milliseconds (batch REST). */
40
+ startTimeMs?: number;
41
+ /** End offset in seconds (streaming WebSocket). */
42
+ endTime?: number;
43
+ /** End offset in milliseconds (batch REST). */
44
+ endTimeMs?: number;
45
+ }
46
+
47
+ /**
48
+ * Acoustic voice profile returned alongside the transcript when
49
+ * `enableVoiceProfile` is `true`. Each dimension is an array of
50
+ * `{label, confidence}` candidates ordered by descending confidence.
51
+ *
52
+ * @remarks The response schema is not publicly documented by Inworld;
53
+ * additional dimension keys may appear at runtime.
54
+ */
55
+ export interface VoiceProfile {
56
+ emotion?: { label: string; confidence: number }[];
57
+ accent?: { label: string; confidence: number }[];
58
+ age?: { label: string; confidence: number }[];
59
+ pitch?: { label: string; confidence: number }[];
60
+ vocalStyle?: { label: string; confidence: number }[];
61
+ [key: string]: unknown;
62
+ }
63
+
64
+ /** Billing and model metadata returned in batch REST responses. */
65
+ export interface TranscriptionUsage {
66
+ /** Duration of audio that was transcribed, in milliseconds. */
67
+ transcribedAudioMs?: number;
68
+ modelId?: string;
69
+ }
70
+
71
+ /** Configuration options for {@link STT}. */
72
+ export interface STTOptions {
73
+ /** Inworld API key. Defaults to `$INWORLD_API_KEY`. */
74
+ apiKey?: string;
75
+ /** Model to use. Default: `'inworld/inworld-stt-1'`. */
76
+ model: STTModels;
77
+ /** BCP-47 language tag. Default: `'en-US'`. */
78
+ language: string;
79
+ /** Input audio sample rate in Hz. Default: `16000`. */
80
+ sampleRate: number;
81
+ /** Number of audio channels. Default: `1`. */
82
+ numChannels: number;
83
+ /** Enable acoustic voice profiling (emotion, accent, age, pitch, style). Default: `true`. */
84
+ enableVoiceProfile: boolean;
85
+ /** Number of top candidates to return per voice profile dimension. Default: `1`. */
86
+ voiceProfileTopN: number;
87
+ /** VAD activity threshold (0–1). Omit to use the server default. */
88
+ vadThreshold?: number;
89
+ /** Minimum silence in ms before committing end-of-turn when confidence is high. Default: `200`. */
90
+ minEndOfTurnSilenceWhenConfident: number;
91
+ /** Confidence threshold for end-of-turn detection. Default: `0.3`. */
92
+ endOfTurnConfidenceThreshold: number;
93
+ /** Base URL for the REST API. Default: `'https://api.inworld.ai/'`. */
94
+ baseURL: string;
95
+ /** Base URL for the WebSocket API. Default: `'wss://api.inworld.ai/'`. */
96
+ wsURL: string;
97
+ }
98
+
99
+ const defaultSTTOptions: STTOptions = {
100
+ apiKey: process.env.INWORLD_API_KEY,
101
+ model: DEFAULT_MODEL,
102
+ language: DEFAULT_LANGUAGE,
103
+ sampleRate: DEFAULT_SAMPLE_RATE,
104
+ numChannels: DEFAULT_NUM_CHANNELS,
105
+ enableVoiceProfile: true,
106
+ voiceProfileTopN: 1,
107
+ minEndOfTurnSilenceWhenConfident: 200,
108
+ endOfTurnConfidenceThreshold: 0.3,
109
+ baseURL: DEFAULT_BASE_URL,
110
+ wsURL: DEFAULT_WS_URL,
111
+ };
112
+
113
+ /**
114
+ * Inworld STT — supports both streaming (bidirectional WebSocket) and batch (REST) modes.
115
+ *
116
+ * When `enableVoiceProfile` is `true` (the default), each recognized transcript includes an
117
+ * acoustic {@link VoiceProfile} in `SpeechData.metadata.voiceProfile`.
118
+ *
119
+ * @example
120
+ * ```ts
121
+ * const sttInstance = new STT({ enableVoiceProfile: true });
122
+ * session = new AgentSession({ stt: sttInstance, ... });
123
+ * ```
124
+ */
125
+ export class STT extends stt.STT {
126
+ #opts: STTOptions;
127
+ #logger = log();
128
+ label = 'inworld.STT';
129
+
130
+ get model(): string {
131
+ return this.#opts.model;
132
+ }
133
+
134
+ get provider(): string {
135
+ return 'Inworld';
136
+ }
137
+
138
+ /**
139
+ * @param opts - Partial {@link STTOptions}. `apiKey` defaults to `$INWORLD_API_KEY`.
140
+ */
141
+ constructor(opts: Partial<STTOptions> = {}) {
142
+ super({
143
+ streaming: true,
144
+ interimResults: true,
145
+ alignedTranscript: false,
146
+ });
147
+
148
+ const apiKey = opts.apiKey ?? defaultSTTOptions.apiKey;
149
+ if (!apiKey) {
150
+ throw new Error('Inworld API key is required, whether as an argument or as $INWORLD_API_KEY');
151
+ }
152
+
153
+ this.#opts = { ...defaultSTTOptions, ...opts, apiKey };
154
+ }
155
+
156
+ async _recognize(buffer: AudioBuffer): Promise<stt.SpeechEvent> {
157
+ const frame = mergeFrames(buffer);
158
+ const b64 = Buffer.from(
159
+ frame.data.buffer,
160
+ frame.data.byteOffset,
161
+ frame.data.byteLength,
162
+ ).toString('base64');
163
+
164
+ const url = new URL(REST_ENDPOINT, this.#opts.baseURL);
165
+ const response = await fetch(url.toString(), {
166
+ method: 'POST',
167
+ headers: {
168
+ Authorization: `Basic ${this.#opts.apiKey}`,
169
+ 'Content-Type': 'application/json',
170
+ },
171
+ body: JSON.stringify({
172
+ transcribeConfig: {
173
+ modelId: this.#opts.model,
174
+ audioEncoding: 'LINEAR16',
175
+ sampleRateHertz: this.#opts.sampleRate,
176
+ numberOfChannels: this.#opts.numChannels,
177
+ language: this.#opts.language,
178
+ voiceProfileConfig: {
179
+ enableVoiceProfile: this.#opts.enableVoiceProfile,
180
+ topN: this.#opts.voiceProfileTopN,
181
+ },
182
+ },
183
+ audioData: { content: b64 },
184
+ }),
185
+ });
186
+
187
+ if (!response.ok) {
188
+ throw new Error(`Inworld STT API error ${response.status}: ${await response.text()}`);
189
+ }
190
+
191
+ const result = (await response.json()) as {
192
+ transcription: {
193
+ transcript: string;
194
+ isFinal: boolean;
195
+ wordTimestamps?: WordTimestamp[];
196
+ voiceProfile?: VoiceProfile;
197
+ };
198
+ usage?: TranscriptionUsage;
199
+ };
200
+
201
+ const { transcript, wordTimestamps, voiceProfile } = result.transcription;
202
+ const metadata = voiceProfile ? { voiceProfile: voiceProfile } : undefined;
203
+
204
+ return {
205
+ type: stt.SpeechEventType.FINAL_TRANSCRIPT,
206
+ alternatives: [
207
+ {
208
+ text: transcript,
209
+ language: normalizeLanguage(this.#opts.language),
210
+ startTime: 0,
211
+ endTime: 0,
212
+ confidence: 1,
213
+ words: wordTimestampsToTimedStrings(wordTimestamps ?? []),
214
+ metadata,
215
+ },
216
+ ],
217
+ };
218
+ }
219
+
220
+ updateOptions(opts: Partial<STTOptions>): void {
221
+ this.#opts = { ...this.#opts, ...opts };
222
+ }
223
+
224
+ stream(options?: { connOptions?: APIConnectOptions }): SpeechStream {
225
+ return new SpeechStream(this, this.#opts, options?.connOptions);
226
+ }
227
+
228
+ async close(): Promise<void> {}
229
+ }
230
+
231
+ export class SpeechStream extends stt.SpeechStream {
232
+ #opts: STTOptions;
233
+ #logger = log();
234
+ #speaking = false;
235
+ #resetWS = new Future();
236
+ #requestId = shortuuid('stt_');
237
+ #audioDuration = 0;
238
+ #lastAudioReport = 0;
239
+ label = 'inworld.SpeechStream';
240
+
241
+ constructor(sttInstance: STT, opts: STTOptions, connOptions?: APIConnectOptions) {
242
+ super(sttInstance, opts.sampleRate, connOptions);
243
+ this.#opts = opts;
244
+ }
245
+
246
+ updateOptions(opts: Partial<STTOptions>): void {
247
+ this.#opts = { ...this.#opts, ...opts };
248
+ this.#resetWS.resolve();
249
+ }
250
+
251
+ protected async run(): Promise<void> {
252
+ const maxRetry = 32;
253
+ let retries = 0;
254
+
255
+ while (!this.input.closed && !this.closed) {
256
+ const wsUrl = new URL(WS_ENDPOINT, this.#opts.wsURL);
257
+ const ws = new WebSocket(wsUrl.toString(), {
258
+ headers: { Authorization: `Basic ${this.#opts.apiKey}` },
259
+ });
260
+
261
+ try {
262
+ await new Promise<void>((resolve, reject) => {
263
+ ws.on('open', () => resolve());
264
+ ws.on('error', (err) => reject(err));
265
+ ws.on('close', (code) => reject(new Error(`WebSocket closed with code ${code}`)));
266
+ });
267
+
268
+ retries = 0;
269
+ await this.#runWS(ws);
270
+ } catch (e) {
271
+ if (!this.closed && !this.input.closed) {
272
+ if (retries >= maxRetry) {
273
+ throw new Error(`Failed to connect to Inworld STT after ${retries} attempts: ${e}`);
274
+ }
275
+
276
+ const delay = Math.min(retries * 5, 10);
277
+ retries++;
278
+ this.#logger.warn(
279
+ `Failed to connect to Inworld STT, retrying in ${delay}s: ${e} (${retries}/${maxRetry})`,
280
+ );
281
+ await new Promise((resolve) => setTimeout(resolve, delay * 1000));
282
+ } else {
283
+ this.#logger.warn(
284
+ `Inworld STT disconnected, connection is closed: ${e} (inputClosed: ${this.input.closed}, isClosed: ${this.closed})`,
285
+ );
286
+ }
287
+ }
288
+ }
289
+
290
+ this.closed = true;
291
+ }
292
+
293
+ async #runWS(ws: WebSocket): Promise<void> {
294
+ this.#resetWS = new Future();
295
+ let closing = false;
296
+
297
+ ws.send(
298
+ JSON.stringify({
299
+ transcribeConfig: {
300
+ modelId: this.#opts.model,
301
+ audioEncoding: 'LINEAR16',
302
+ sampleRateHertz: this.#opts.sampleRate,
303
+ numberOfChannels: this.#opts.numChannels,
304
+ language: this.#opts.language,
305
+ voiceProfileConfig: {
306
+ enableVoiceProfile: this.#opts.enableVoiceProfile,
307
+ topN: this.#opts.voiceProfileTopN,
308
+ },
309
+ endOfTurnConfidenceThreshold: this.#opts.endOfTurnConfidenceThreshold,
310
+ inworldSttV1Config: {
311
+ minEndOfTurnSilenceWhenConfident: this.#opts.minEndOfTurnSilenceWhenConfident,
312
+ ...(this.#opts.vadThreshold !== undefined
313
+ ? { vadThreshold: this.#opts.vadThreshold }
314
+ : {}),
315
+ },
316
+ },
317
+ }),
318
+ );
319
+
320
+ const wsMonitor = Task.from(async (controller) => {
321
+ const closed = new Promise<void>((_, reject) => {
322
+ ws.once('close', (code, reason) => {
323
+ if (!closing) {
324
+ this.#logger.error(`Inworld STT WebSocket closed with code ${code}: ${reason}`);
325
+ reject(new Error('WebSocket closed'));
326
+ }
327
+ });
328
+ });
329
+ await Promise.race([closed, waitForAbort(controller.signal)]);
330
+ });
331
+
332
+ const sendTask = async () => {
333
+ const samples100Ms = Math.floor(this.#opts.sampleRate / 10);
334
+ const stream = new AudioByteStream(
335
+ this.#opts.sampleRate,
336
+ this.#opts.numChannels,
337
+ samples100Ms,
338
+ );
339
+
340
+ const abortPromise = waitForAbort(this.abortSignal);
341
+
342
+ try {
343
+ while (!this.closed) {
344
+ const result = await Promise.race([this.input.next(), abortPromise]);
345
+
346
+ if (result === undefined) return;
347
+ if (result.done) break;
348
+
349
+ const data = result.value;
350
+ const frames =
351
+ data === SpeechStream.FLUSH_SENTINEL
352
+ ? stream.flush()
353
+ : stream.write(data.data.buffer as ArrayBuffer);
354
+
355
+ for await (const frame of frames) {
356
+ const frameDuration = frame.samplesPerChannel / frame.sampleRate;
357
+ this.#audioDuration += frameDuration;
358
+ this.#maybeReportUsage();
359
+
360
+ const b64 = Buffer.from(
361
+ frame.data.buffer,
362
+ frame.data.byteOffset,
363
+ frame.data.byteLength,
364
+ ).toString('base64');
365
+ ws.send(JSON.stringify({ audioChunk: { content: b64 } }));
366
+ }
367
+ }
368
+ } finally {
369
+ closing = true;
370
+ ws.send(JSON.stringify({ endTurn: {} }));
371
+ ws.send(JSON.stringify({ closeStream: {} }));
372
+ wsMonitor.cancel();
373
+ }
374
+ };
375
+
376
+ const listenTask = Task.from(async (controller) => {
377
+ const listenMessage = new Promise<void>((resolve, reject) => {
378
+ ws.on('message', (msg) => {
379
+ try {
380
+ const json = JSON.parse(msg.toString()) as {
381
+ result?: {
382
+ speechStarted?: unknown;
383
+ transcription?: {
384
+ transcript: string;
385
+ isFinal: boolean;
386
+ wordTimestamps?: WordTimestamp[];
387
+ voiceProfile?: VoiceProfile;
388
+ };
389
+ };
390
+ error?: { message: string };
391
+ };
392
+
393
+ if (json.error) {
394
+ reject(new Error(`Inworld STT error: ${json.error.message}`));
395
+ return;
396
+ }
397
+
398
+ const result = json.result;
399
+ if (!result) return;
400
+
401
+ if (result.speechStarted !== undefined) {
402
+ if (!this.#speaking) {
403
+ this.#speaking = true;
404
+ this.queue.put({ type: stt.SpeechEventType.START_OF_SPEECH });
405
+ }
406
+ return;
407
+ }
408
+
409
+ if (result.transcription) {
410
+ const { transcript, isFinal, wordTimestamps, voiceProfile } = result.transcription;
411
+ const metadata = voiceProfile ? { voiceProfile: voiceProfile } : undefined;
412
+
413
+ if (!this.#speaking && transcript) {
414
+ this.#speaking = true;
415
+ this.queue.put({ type: stt.SpeechEventType.START_OF_SPEECH });
416
+ }
417
+
418
+ if (isFinal) {
419
+ if (transcript) {
420
+ this.queue.put({
421
+ type: stt.SpeechEventType.FINAL_TRANSCRIPT,
422
+ requestId: this.#requestId,
423
+ alternatives: [
424
+ {
425
+ text: transcript,
426
+ language: normalizeLanguage(this.#opts.language),
427
+ startTime: this.startTimeOffset,
428
+ endTime: this.startTimeOffset,
429
+ confidence: 1,
430
+ words: wordTimestampsToTimedStrings(
431
+ wordTimestamps ?? [],
432
+ this.startTimeOffset,
433
+ ),
434
+ metadata,
435
+ },
436
+ ],
437
+ });
438
+ }
439
+ if (this.#speaking) {
440
+ this.#speaking = false;
441
+ this.queue.put({ type: stt.SpeechEventType.END_OF_SPEECH });
442
+ }
443
+ } else if (transcript) {
444
+ this.queue.put({
445
+ type: stt.SpeechEventType.INTERIM_TRANSCRIPT,
446
+ requestId: this.#requestId,
447
+ alternatives: [
448
+ {
449
+ text: transcript,
450
+ language: normalizeLanguage(this.#opts.language),
451
+ startTime: this.startTimeOffset,
452
+ endTime: this.startTimeOffset,
453
+ confidence: 0,
454
+ words: wordTimestampsToTimedStrings(
455
+ wordTimestamps ?? [],
456
+ this.startTimeOffset,
457
+ ),
458
+ metadata,
459
+ },
460
+ ],
461
+ });
462
+ }
463
+ }
464
+
465
+ if (this.closed || closing) {
466
+ resolve();
467
+ }
468
+ } catch (err) {
469
+ reject(err);
470
+ }
471
+ });
472
+ });
473
+
474
+ await Promise.race([listenMessage, waitForAbort(controller.signal)]);
475
+ }, this.abortController);
476
+
477
+ await Promise.race([
478
+ this.#resetWS.await,
479
+ Promise.all([sendTask(), listenTask.result, wsMonitor.result]),
480
+ ]);
481
+ closing = true;
482
+ ws.close();
483
+ }
484
+
485
+ #maybeReportUsage(): void {
486
+ const elapsed = this.#audioDuration - this.#lastAudioReport;
487
+ if (elapsed >= AUDIO_DURATION_REPORT_INTERVAL) {
488
+ this.#lastAudioReport = this.#audioDuration;
489
+ this.queue.put({
490
+ type: stt.SpeechEventType.RECOGNITION_USAGE,
491
+ requestId: this.#requestId,
492
+ recognitionUsage: { audioDuration: elapsed },
493
+ });
494
+ }
495
+ }
496
+ }
497
+
498
+ function wordTimestampsToTimedStrings(
499
+ words: WordTimestamp[],
500
+ startTimeOffset = 0,
501
+ ): ReturnType<typeof createTimedString>[] {
502
+ return words.map((w) => {
503
+ // REST endpoint uses startTimeMs/endTimeMs (ms); streaming uses startTime/endTime (s).
504
+ const startTime =
505
+ w.startTimeMs !== undefined
506
+ ? w.startTimeMs / 1000 + startTimeOffset
507
+ : (w.startTime ?? 0) + startTimeOffset;
508
+ const endTime =
509
+ w.endTimeMs !== undefined
510
+ ? w.endTimeMs / 1000 + startTimeOffset
511
+ : (w.endTime ?? 0) + startTimeOffset;
512
+
513
+ return createTimedString({
514
+ text: w.word,
515
+ startTime,
516
+ endTime,
517
+ startTimeOffset,
518
+ confidence: w.confidence ?? 0,
519
+ });
520
+ });
521
+ }
@@ -0,0 +1,19 @@
1
+ // SPDX-FileCopyrightText: 2025 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import { STT } from '@livekit/agents-plugin-openai';
5
+ import { tts } from '@livekit/agents-plugins-test';
6
+ import { describe, it } from 'vitest';
7
+ import { TTS } from './tts.js';
8
+
9
+ const hasInworldConfig = Boolean(process.env.INWORLD_API_KEY && process.env.OPENAI_API_KEY);
10
+
11
+ if (hasInworldConfig) {
12
+ describe('Inworld', async () => {
13
+ await tts(new TTS(), new STT());
14
+ });
15
+ } else {
16
+ describe('Inworld', () => {
17
+ it.skip('requires INWORLD_API_KEY and OPENAI_API_KEY', () => {});
18
+ });
19
+ }