@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.
- package/LICENSE +201 -0
- package/dist/index.cjs +38 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +5 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +16 -0
- package/dist/index.js.map +1 -0
- package/dist/stt.cjs +372 -0
- package/dist/stt.cjs.map +1 -0
- package/dist/stt.d.cts +116 -0
- package/dist/stt.d.ts +116 -0
- package/dist/stt.d.ts.map +1 -0
- package/dist/stt.js +358 -0
- package/dist/stt.js.map +1 -0
- package/dist/tts.cjs +609 -0
- package/dist/tts.cjs.map +1 -0
- package/dist/tts.d.cts +102 -0
- package/dist/tts.d.ts +102 -0
- package/dist/tts.d.ts.map +1 -0
- package/dist/tts.js +596 -0
- package/dist/tts.js.map +1 -0
- package/dist/tts.test.cjs +17 -0
- package/dist/tts.test.cjs.map +1 -0
- package/dist/tts.test.js +16 -0
- package/dist/tts.test.js.map +1 -0
- package/package.json +53 -0
- package/src/index.ts +21 -0
- package/src/stt.ts +521 -0
- package/src/tts.test.ts +19 -0
- package/src/tts.ts +852 -0
package/dist/stt.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/stt.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2026 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport {\n type APIConnectOptions,\n type AudioBuffer,\n AudioByteStream,\n Future,\n Task,\n createTimedString,\n log,\n mergeFrames,\n normalizeLanguage,\n shortuuid,\n stt,\n waitForAbort,\n} from '@livekit/agents';\nimport { WebSocket } from 'ws';\n\nconst DEFAULT_MODEL = 'inworld/inworld-stt-1';\nconst DEFAULT_LANGUAGE = 'en-US';\nconst DEFAULT_SAMPLE_RATE = 16000;\nconst DEFAULT_NUM_CHANNELS = 1;\nconst DEFAULT_BASE_URL = 'https://api.inworld.ai/';\nconst DEFAULT_WS_URL = 'wss://api.inworld.ai/';\nconst WS_ENDPOINT = 'stt/v1/transcribe:streamBidirectional';\nconst REST_ENDPOINT = 'stt/v1/transcribe';\nconst AUDIO_DURATION_REPORT_INTERVAL = 5;\n\n/** Supported Inworld STT model identifiers. */\nexport type STTModels = 'inworld/inworld-stt-1' | string;\n\n/** Per-word timestamp entry returned by the Inworld STT API. */\nexport interface WordTimestamp {\n word: string;\n confidence?: number;\n /** Start offset in seconds (streaming WebSocket). */\n startTime?: number;\n /** Start offset in milliseconds (batch REST). */\n startTimeMs?: number;\n /** End offset in seconds (streaming WebSocket). */\n endTime?: number;\n /** End offset in milliseconds (batch REST). */\n endTimeMs?: number;\n}\n\n/**\n * Acoustic voice profile returned alongside the transcript when\n * `enableVoiceProfile` is `true`. Each dimension is an array of\n * `{label, confidence}` candidates ordered by descending confidence.\n *\n * @remarks The response schema is not publicly documented by Inworld;\n * additional dimension keys may appear at runtime.\n */\nexport interface VoiceProfile {\n emotion?: { label: string; confidence: number }[];\n accent?: { label: string; confidence: number }[];\n age?: { label: string; confidence: number }[];\n pitch?: { label: string; confidence: number }[];\n vocalStyle?: { label: string; confidence: number }[];\n [key: string]: unknown;\n}\n\n/** Billing and model metadata returned in batch REST responses. */\nexport interface TranscriptionUsage {\n /** Duration of audio that was transcribed, in milliseconds. */\n transcribedAudioMs?: number;\n modelId?: string;\n}\n\n/** Configuration options for {@link STT}. */\nexport interface STTOptions {\n /** Inworld API key. Defaults to `$INWORLD_API_KEY`. */\n apiKey?: string;\n /** Model to use. Default: `'inworld/inworld-stt-1'`. */\n model: STTModels;\n /** BCP-47 language tag. Default: `'en-US'`. */\n language: string;\n /** Input audio sample rate in Hz. Default: `16000`. */\n sampleRate: number;\n /** Number of audio channels. Default: `1`. */\n numChannels: number;\n /** Enable acoustic voice profiling (emotion, accent, age, pitch, style). Default: `true`. */\n enableVoiceProfile: boolean;\n /** Number of top candidates to return per voice profile dimension. Default: `1`. */\n voiceProfileTopN: number;\n /** VAD activity threshold (0–1). Omit to use the server default. */\n vadThreshold?: number;\n /** Minimum silence in ms before committing end-of-turn when confidence is high. Default: `200`. */\n minEndOfTurnSilenceWhenConfident: number;\n /** Confidence threshold for end-of-turn detection. Default: `0.3`. */\n endOfTurnConfidenceThreshold: number;\n /** Base URL for the REST API. Default: `'https://api.inworld.ai/'`. */\n baseURL: string;\n /** Base URL for the WebSocket API. Default: `'wss://api.inworld.ai/'`. */\n wsURL: string;\n}\n\nconst defaultSTTOptions: STTOptions = {\n apiKey: process.env.INWORLD_API_KEY,\n model: DEFAULT_MODEL,\n language: DEFAULT_LANGUAGE,\n sampleRate: DEFAULT_SAMPLE_RATE,\n numChannels: DEFAULT_NUM_CHANNELS,\n enableVoiceProfile: true,\n voiceProfileTopN: 1,\n minEndOfTurnSilenceWhenConfident: 200,\n endOfTurnConfidenceThreshold: 0.3,\n baseURL: DEFAULT_BASE_URL,\n wsURL: DEFAULT_WS_URL,\n};\n\n/**\n * Inworld STT — supports both streaming (bidirectional WebSocket) and batch (REST) modes.\n *\n * When `enableVoiceProfile` is `true` (the default), each recognized transcript includes an\n * acoustic {@link VoiceProfile} in `SpeechData.metadata.voiceProfile`.\n *\n * @example\n * ```ts\n * const sttInstance = new STT({ enableVoiceProfile: true });\n * session = new AgentSession({ stt: sttInstance, ... });\n * ```\n */\nexport class STT extends stt.STT {\n #opts: STTOptions;\n #logger = log();\n label = 'inworld.STT';\n\n get model(): string {\n return this.#opts.model;\n }\n\n get provider(): string {\n return 'Inworld';\n }\n\n /**\n * @param opts - Partial {@link STTOptions}. `apiKey` defaults to `$INWORLD_API_KEY`.\n */\n constructor(opts: Partial<STTOptions> = {}) {\n super({\n streaming: true,\n interimResults: true,\n alignedTranscript: false,\n });\n\n const apiKey = opts.apiKey ?? defaultSTTOptions.apiKey;\n if (!apiKey) {\n throw new Error('Inworld API key is required, whether as an argument or as $INWORLD_API_KEY');\n }\n\n this.#opts = { ...defaultSTTOptions, ...opts, apiKey };\n }\n\n async _recognize(buffer: AudioBuffer): Promise<stt.SpeechEvent> {\n const frame = mergeFrames(buffer);\n const b64 = Buffer.from(\n frame.data.buffer,\n frame.data.byteOffset,\n frame.data.byteLength,\n ).toString('base64');\n\n const url = new URL(REST_ENDPOINT, this.#opts.baseURL);\n const response = await fetch(url.toString(), {\n method: 'POST',\n headers: {\n Authorization: `Basic ${this.#opts.apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n transcribeConfig: {\n modelId: this.#opts.model,\n audioEncoding: 'LINEAR16',\n sampleRateHertz: this.#opts.sampleRate,\n numberOfChannels: this.#opts.numChannels,\n language: this.#opts.language,\n voiceProfileConfig: {\n enableVoiceProfile: this.#opts.enableVoiceProfile,\n topN: this.#opts.voiceProfileTopN,\n },\n },\n audioData: { content: b64 },\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Inworld STT API error ${response.status}: ${await response.text()}`);\n }\n\n const result = (await response.json()) as {\n transcription: {\n transcript: string;\n isFinal: boolean;\n wordTimestamps?: WordTimestamp[];\n voiceProfile?: VoiceProfile;\n };\n usage?: TranscriptionUsage;\n };\n\n const { transcript, wordTimestamps, voiceProfile } = result.transcription;\n const metadata = voiceProfile ? { voiceProfile: voiceProfile } : undefined;\n\n return {\n type: stt.SpeechEventType.FINAL_TRANSCRIPT,\n alternatives: [\n {\n text: transcript,\n language: normalizeLanguage(this.#opts.language),\n startTime: 0,\n endTime: 0,\n confidence: 1,\n words: wordTimestampsToTimedStrings(wordTimestamps ?? []),\n metadata,\n },\n ],\n };\n }\n\n updateOptions(opts: Partial<STTOptions>): void {\n this.#opts = { ...this.#opts, ...opts };\n }\n\n stream(options?: { connOptions?: APIConnectOptions }): SpeechStream {\n return new SpeechStream(this, this.#opts, options?.connOptions);\n }\n\n async close(): Promise<void> {}\n}\n\nexport class SpeechStream extends stt.SpeechStream {\n #opts: STTOptions;\n #logger = log();\n #speaking = false;\n #resetWS = new Future();\n #requestId = shortuuid('stt_');\n #audioDuration = 0;\n #lastAudioReport = 0;\n label = 'inworld.SpeechStream';\n\n constructor(sttInstance: STT, opts: STTOptions, connOptions?: APIConnectOptions) {\n super(sttInstance, opts.sampleRate, connOptions);\n this.#opts = opts;\n }\n\n updateOptions(opts: Partial<STTOptions>): void {\n this.#opts = { ...this.#opts, ...opts };\n this.#resetWS.resolve();\n }\n\n protected async run(): Promise<void> {\n const maxRetry = 32;\n let retries = 0;\n\n while (!this.input.closed && !this.closed) {\n const wsUrl = new URL(WS_ENDPOINT, this.#opts.wsURL);\n const ws = new WebSocket(wsUrl.toString(), {\n headers: { Authorization: `Basic ${this.#opts.apiKey}` },\n });\n\n try {\n await new Promise<void>((resolve, reject) => {\n ws.on('open', () => resolve());\n ws.on('error', (err) => reject(err));\n ws.on('close', (code) => reject(new Error(`WebSocket closed with code ${code}`)));\n });\n\n retries = 0;\n await this.#runWS(ws);\n } catch (e) {\n if (!this.closed && !this.input.closed) {\n if (retries >= maxRetry) {\n throw new Error(`Failed to connect to Inworld STT after ${retries} attempts: ${e}`);\n }\n\n const delay = Math.min(retries * 5, 10);\n retries++;\n this.#logger.warn(\n `Failed to connect to Inworld STT, retrying in ${delay}s: ${e} (${retries}/${maxRetry})`,\n );\n await new Promise((resolve) => setTimeout(resolve, delay * 1000));\n } else {\n this.#logger.warn(\n `Inworld STT disconnected, connection is closed: ${e} (inputClosed: ${this.input.closed}, isClosed: ${this.closed})`,\n );\n }\n }\n }\n\n this.closed = true;\n }\n\n async #runWS(ws: WebSocket): Promise<void> {\n this.#resetWS = new Future();\n let closing = false;\n\n ws.send(\n JSON.stringify({\n transcribeConfig: {\n modelId: this.#opts.model,\n audioEncoding: 'LINEAR16',\n sampleRateHertz: this.#opts.sampleRate,\n numberOfChannels: this.#opts.numChannels,\n language: this.#opts.language,\n voiceProfileConfig: {\n enableVoiceProfile: this.#opts.enableVoiceProfile,\n topN: this.#opts.voiceProfileTopN,\n },\n endOfTurnConfidenceThreshold: this.#opts.endOfTurnConfidenceThreshold,\n inworldSttV1Config: {\n minEndOfTurnSilenceWhenConfident: this.#opts.minEndOfTurnSilenceWhenConfident,\n ...(this.#opts.vadThreshold !== undefined\n ? { vadThreshold: this.#opts.vadThreshold }\n : {}),\n },\n },\n }),\n );\n\n const wsMonitor = Task.from(async (controller) => {\n const closed = new Promise<void>((_, reject) => {\n ws.once('close', (code, reason) => {\n if (!closing) {\n this.#logger.error(`Inworld STT WebSocket closed with code ${code}: ${reason}`);\n reject(new Error('WebSocket closed'));\n }\n });\n });\n await Promise.race([closed, waitForAbort(controller.signal)]);\n });\n\n const sendTask = async () => {\n const samples100Ms = Math.floor(this.#opts.sampleRate / 10);\n const stream = new AudioByteStream(\n this.#opts.sampleRate,\n this.#opts.numChannels,\n samples100Ms,\n );\n\n const abortPromise = waitForAbort(this.abortSignal);\n\n try {\n while (!this.closed) {\n const result = await Promise.race([this.input.next(), abortPromise]);\n\n if (result === undefined) return;\n if (result.done) break;\n\n const data = result.value;\n const frames =\n data === SpeechStream.FLUSH_SENTINEL\n ? stream.flush()\n : stream.write(data.data.buffer as ArrayBuffer);\n\n for await (const frame of frames) {\n const frameDuration = frame.samplesPerChannel / frame.sampleRate;\n this.#audioDuration += frameDuration;\n this.#maybeReportUsage();\n\n const b64 = Buffer.from(\n frame.data.buffer,\n frame.data.byteOffset,\n frame.data.byteLength,\n ).toString('base64');\n ws.send(JSON.stringify({ audioChunk: { content: b64 } }));\n }\n }\n } finally {\n closing = true;\n ws.send(JSON.stringify({ endTurn: {} }));\n ws.send(JSON.stringify({ closeStream: {} }));\n wsMonitor.cancel();\n }\n };\n\n const listenTask = Task.from(async (controller) => {\n const listenMessage = new Promise<void>((resolve, reject) => {\n ws.on('message', (msg) => {\n try {\n const json = JSON.parse(msg.toString()) as {\n result?: {\n speechStarted?: unknown;\n transcription?: {\n transcript: string;\n isFinal: boolean;\n wordTimestamps?: WordTimestamp[];\n voiceProfile?: VoiceProfile;\n };\n };\n error?: { message: string };\n };\n\n if (json.error) {\n reject(new Error(`Inworld STT error: ${json.error.message}`));\n return;\n }\n\n const result = json.result;\n if (!result) return;\n\n if (result.speechStarted !== undefined) {\n if (!this.#speaking) {\n this.#speaking = true;\n this.queue.put({ type: stt.SpeechEventType.START_OF_SPEECH });\n }\n return;\n }\n\n if (result.transcription) {\n const { transcript, isFinal, wordTimestamps, voiceProfile } = result.transcription;\n const metadata = voiceProfile ? { voiceProfile: voiceProfile } : undefined;\n\n if (!this.#speaking && transcript) {\n this.#speaking = true;\n this.queue.put({ type: stt.SpeechEventType.START_OF_SPEECH });\n }\n\n if (isFinal) {\n if (transcript) {\n this.queue.put({\n type: stt.SpeechEventType.FINAL_TRANSCRIPT,\n requestId: this.#requestId,\n alternatives: [\n {\n text: transcript,\n language: normalizeLanguage(this.#opts.language),\n startTime: this.startTimeOffset,\n endTime: this.startTimeOffset,\n confidence: 1,\n words: wordTimestampsToTimedStrings(\n wordTimestamps ?? [],\n this.startTimeOffset,\n ),\n metadata,\n },\n ],\n });\n }\n if (this.#speaking) {\n this.#speaking = false;\n this.queue.put({ type: stt.SpeechEventType.END_OF_SPEECH });\n }\n } else if (transcript) {\n this.queue.put({\n type: stt.SpeechEventType.INTERIM_TRANSCRIPT,\n requestId: this.#requestId,\n alternatives: [\n {\n text: transcript,\n language: normalizeLanguage(this.#opts.language),\n startTime: this.startTimeOffset,\n endTime: this.startTimeOffset,\n confidence: 0,\n words: wordTimestampsToTimedStrings(\n wordTimestamps ?? [],\n this.startTimeOffset,\n ),\n metadata,\n },\n ],\n });\n }\n }\n\n if (this.closed || closing) {\n resolve();\n }\n } catch (err) {\n reject(err);\n }\n });\n });\n\n await Promise.race([listenMessage, waitForAbort(controller.signal)]);\n }, this.abortController);\n\n await Promise.race([\n this.#resetWS.await,\n Promise.all([sendTask(), listenTask.result, wsMonitor.result]),\n ]);\n closing = true;\n ws.close();\n }\n\n #maybeReportUsage(): void {\n const elapsed = this.#audioDuration - this.#lastAudioReport;\n if (elapsed >= AUDIO_DURATION_REPORT_INTERVAL) {\n this.#lastAudioReport = this.#audioDuration;\n this.queue.put({\n type: stt.SpeechEventType.RECOGNITION_USAGE,\n requestId: this.#requestId,\n recognitionUsage: { audioDuration: elapsed },\n });\n }\n }\n}\n\nfunction wordTimestampsToTimedStrings(\n words: WordTimestamp[],\n startTimeOffset = 0,\n): ReturnType<typeof createTimedString>[] {\n return words.map((w) => {\n // REST endpoint uses startTimeMs/endTimeMs (ms); streaming uses startTime/endTime (s).\n const startTime =\n w.startTimeMs !== undefined\n ? w.startTimeMs / 1000 + startTimeOffset\n : (w.startTime ?? 0) + startTimeOffset;\n const endTime =\n w.endTimeMs !== undefined\n ? w.endTimeMs / 1000 + startTimeOffset\n : (w.endTime ?? 0) + startTimeOffset;\n\n return createTimedString({\n text: w.word,\n startTime,\n endTime,\n startTimeOffset,\n confidence: w.confidence ?? 0,\n });\n });\n}\n"],"mappings":"AAGA;AAAA,EAGE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iBAAiB;AAE1B,MAAM,gBAAgB;AACtB,MAAM,mBAAmB;AACzB,MAAM,sBAAsB;AAC5B,MAAM,uBAAuB;AAC7B,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AACvB,MAAM,cAAc;AACpB,MAAM,gBAAgB;AACtB,MAAM,iCAAiC;AAuEvC,MAAM,oBAAgC;AAAA,EACpC,QAAQ,QAAQ,IAAI;AAAA,EACpB,OAAO;AAAA,EACP,UAAU;AAAA,EACV,YAAY;AAAA,EACZ,aAAa;AAAA,EACb,oBAAoB;AAAA,EACpB,kBAAkB;AAAA,EAClB,kCAAkC;AAAA,EAClC,8BAA8B;AAAA,EAC9B,SAAS;AAAA,EACT,OAAO;AACT;AAcO,MAAM,YAAY,IAAI,IAAI;AAAA,EAC/B;AAAA,EACA,UAAU,IAAI;AAAA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yDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var tts_exports = {};
|
|
20
|
+
__export(tts_exports, {
|
|
21
|
+
TTS: () => TTS
|
|
22
|
+
});
|
|
23
|
+
module.exports = __toCommonJS(tts_exports);
|
|
24
|
+
var import_agents = require("@livekit/agents");
|
|
25
|
+
var import_node_crypto = require("node:crypto");
|
|
26
|
+
var import_ws = require("ws");
|
|
27
|
+
const USER_AGENT = "livekit-agents-js";
|
|
28
|
+
const DEFAULT_BIT_RATE = 64e3;
|
|
29
|
+
const DEFAULT_ENCODING = "PCM";
|
|
30
|
+
const DEFAULT_MODEL = "inworld-tts-2";
|
|
31
|
+
const DEFAULT_SAMPLE_RATE = 24e3;
|
|
32
|
+
const DEFAULT_URL = "https://api.inworld.ai/";
|
|
33
|
+
const DEFAULT_WS_URL = "wss://api.inworld.ai/";
|
|
34
|
+
const DEFAULT_VOICE = "Jason";
|
|
35
|
+
const DEFAULT_TEMPERATURE = 1.1;
|
|
36
|
+
const DEFAULT_TIMESTAMP_TRANSPORT_STRATEGY = "ASYNC";
|
|
37
|
+
const DEFAULT_SPEAKING_RATE = 1;
|
|
38
|
+
const DEFAULT_BUFFER_CHAR_THRESHOLD = 100;
|
|
39
|
+
const DEFAULT_MAX_BUFFER_DELAY_MS = 3e3;
|
|
40
|
+
const NUM_CHANNELS = 1;
|
|
41
|
+
const defaultTTSOptionsBase = {
|
|
42
|
+
apiKey: process.env.INWORLD_API_KEY,
|
|
43
|
+
voice: DEFAULT_VOICE,
|
|
44
|
+
model: DEFAULT_MODEL,
|
|
45
|
+
encoding: DEFAULT_ENCODING,
|
|
46
|
+
bitRate: DEFAULT_BIT_RATE,
|
|
47
|
+
sampleRate: DEFAULT_SAMPLE_RATE,
|
|
48
|
+
speakingRate: DEFAULT_SPEAKING_RATE,
|
|
49
|
+
temperature: DEFAULT_TEMPERATURE,
|
|
50
|
+
timestampTransportStrategy: DEFAULT_TIMESTAMP_TRANSPORT_STRATEGY,
|
|
51
|
+
bufferCharThreshold: DEFAULT_BUFFER_CHAR_THRESHOLD,
|
|
52
|
+
maxBufferDelayMs: DEFAULT_MAX_BUFFER_DELAY_MS,
|
|
53
|
+
baseURL: DEFAULT_URL,
|
|
54
|
+
wsURL: DEFAULT_WS_URL
|
|
55
|
+
};
|
|
56
|
+
const CONNECT_TIMEOUT_MS = 1e4;
|
|
57
|
+
const RETRYABLE_STATUS_CODES = /* @__PURE__ */ new Set([4, 8, 14]);
|
|
58
|
+
class WSConnectionPool {
|
|
59
|
+
#ws;
|
|
60
|
+
#url;
|
|
61
|
+
#auth;
|
|
62
|
+
#connecting;
|
|
63
|
+
#listeners = /* @__PURE__ */ new Map();
|
|
64
|
+
#logger = (0, import_agents.log)();
|
|
65
|
+
constructor(url, auth) {
|
|
66
|
+
this.#url = url;
|
|
67
|
+
this.#auth = auth;
|
|
68
|
+
}
|
|
69
|
+
async getConnection() {
|
|
70
|
+
if (this.#ws && this.#ws.readyState === import_ws.WebSocket.OPEN) {
|
|
71
|
+
return this.#ws;
|
|
72
|
+
}
|
|
73
|
+
if (this.#connecting) {
|
|
74
|
+
return this.#connecting;
|
|
75
|
+
}
|
|
76
|
+
this.#connecting = this.#attemptConnection();
|
|
77
|
+
return this.#connecting;
|
|
78
|
+
}
|
|
79
|
+
#attemptConnection() {
|
|
80
|
+
return new Promise((resolve, reject) => {
|
|
81
|
+
var _a;
|
|
82
|
+
const wsUrl = new URL("tts/v1/voice:streamBidirectional", this.#url);
|
|
83
|
+
if (wsUrl.protocol === "https:") wsUrl.protocol = "wss:";
|
|
84
|
+
else if (wsUrl.protocol === "http:") wsUrl.protocol = "ws:";
|
|
85
|
+
const requestId = (0, import_node_crypto.randomUUID)();
|
|
86
|
+
const ws = new import_ws.WebSocket(wsUrl.toString(), {
|
|
87
|
+
headers: {
|
|
88
|
+
Authorization: this.#auth,
|
|
89
|
+
"X-User-Agent": USER_AGENT,
|
|
90
|
+
"X-Request-Id": requestId
|
|
91
|
+
},
|
|
92
|
+
// Backstop slightly above our own timer so the explicit timer below is
|
|
93
|
+
// the one that fires, yielding a semantically correct APITimeoutError.
|
|
94
|
+
handshakeTimeout: CONNECT_TIMEOUT_MS + 1e3
|
|
95
|
+
});
|
|
96
|
+
let settled = false;
|
|
97
|
+
const handshakeTimer = setTimeout(() => {
|
|
98
|
+
if (settled) return;
|
|
99
|
+
settled = true;
|
|
100
|
+
this.#connecting = void 0;
|
|
101
|
+
ws.terminate();
|
|
102
|
+
reject(
|
|
103
|
+
new import_agents.APITimeoutError({
|
|
104
|
+
message: `Inworld WebSocket handshake timed out after ${CONNECT_TIMEOUT_MS}ms`
|
|
105
|
+
})
|
|
106
|
+
);
|
|
107
|
+
}, CONNECT_TIMEOUT_MS);
|
|
108
|
+
(_a = handshakeTimer.unref) == null ? void 0 : _a.call(handshakeTimer);
|
|
109
|
+
ws.on("open", () => {
|
|
110
|
+
if (settled) return;
|
|
111
|
+
settled = true;
|
|
112
|
+
clearTimeout(handshakeTimer);
|
|
113
|
+
this.#ws = ws;
|
|
114
|
+
this.#connecting = void 0;
|
|
115
|
+
this.#logger.debug({ requestId }, "Established Inworld TTS WebSocket connection");
|
|
116
|
+
resolve(ws);
|
|
117
|
+
});
|
|
118
|
+
ws.on("error", (err) => {
|
|
119
|
+
if (!settled) {
|
|
120
|
+
settled = true;
|
|
121
|
+
clearTimeout(handshakeTimer);
|
|
122
|
+
this.#connecting = void 0;
|
|
123
|
+
reject(
|
|
124
|
+
new import_agents.APIConnectionError({
|
|
125
|
+
message: `Failed to connect to Inworld: ${(0, import_agents.asError)(err).message}`
|
|
126
|
+
})
|
|
127
|
+
);
|
|
128
|
+
} else {
|
|
129
|
+
this.#logger.error({ err, requestId }, "Inworld WebSocket error");
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
ws.on("close", () => {
|
|
133
|
+
this.#ws = void 0;
|
|
134
|
+
this.#connecting = void 0;
|
|
135
|
+
});
|
|
136
|
+
ws.on("message", (data) => {
|
|
137
|
+
try {
|
|
138
|
+
const json = JSON.parse(data.toString());
|
|
139
|
+
const result = json.result;
|
|
140
|
+
if (result) {
|
|
141
|
+
const contextId = result.contextId || json.contextId;
|
|
142
|
+
if (contextId && this.#listeners.has(contextId)) {
|
|
143
|
+
this.#listeners.get(contextId)(json);
|
|
144
|
+
}
|
|
145
|
+
} else if (json.error) {
|
|
146
|
+
this.#logger.warn({ error: json.error }, "Inworld received error message");
|
|
147
|
+
}
|
|
148
|
+
} catch (e) {
|
|
149
|
+
this.#logger.warn({ error: e }, "Failed to parse Inworld WebSocket message");
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
registerListener(contextId, cb) {
|
|
155
|
+
this.#listeners.set(contextId, cb);
|
|
156
|
+
}
|
|
157
|
+
unregisterListener(contextId) {
|
|
158
|
+
this.#listeners.delete(contextId);
|
|
159
|
+
}
|
|
160
|
+
close() {
|
|
161
|
+
if (this.#ws) {
|
|
162
|
+
this.#ws.close();
|
|
163
|
+
this.#ws = void 0;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
class TTS extends import_agents.tts.TTS {
|
|
168
|
+
#opts;
|
|
169
|
+
#pool;
|
|
170
|
+
#authorization;
|
|
171
|
+
label = "inworld.TTS";
|
|
172
|
+
constructor(opts = {}) {
|
|
173
|
+
const mergedOpts = { ...defaultTTSOptionsBase, ...opts };
|
|
174
|
+
if (!mergedOpts.apiKey) {
|
|
175
|
+
throw new Error("Inworld API key required. Set INWORLD_API_KEY or provide apiKey.");
|
|
176
|
+
}
|
|
177
|
+
super(mergedOpts.sampleRate, NUM_CHANNELS, {
|
|
178
|
+
streaming: true,
|
|
179
|
+
alignedTranscript: !!mergedOpts.timestampType
|
|
180
|
+
});
|
|
181
|
+
this.#opts = mergedOpts;
|
|
182
|
+
if (!this.#opts.tokenizer) {
|
|
183
|
+
this.#opts.tokenizer = new import_agents.tokenize.basic.SentenceTokenizer({ retainFormat: true });
|
|
184
|
+
}
|
|
185
|
+
this.#authorization = `Basic ${mergedOpts.apiKey}`;
|
|
186
|
+
this.#pool = new WSConnectionPool(this.#opts.wsURL, this.#authorization);
|
|
187
|
+
}
|
|
188
|
+
get pool() {
|
|
189
|
+
return this.#pool;
|
|
190
|
+
}
|
|
191
|
+
get authorization() {
|
|
192
|
+
return this.#authorization;
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* List all available voices in the workspace associated with the API key.
|
|
196
|
+
* @param language - Optional ISO 639-1 language code to filter voices (e.g., 'en', 'es', 'fr')
|
|
197
|
+
*/
|
|
198
|
+
async listVoices(language) {
|
|
199
|
+
const url = new URL("tts/v1/voices", this.#opts.baseURL);
|
|
200
|
+
if (language) {
|
|
201
|
+
url.searchParams.set("filter", `language=${language}`);
|
|
202
|
+
}
|
|
203
|
+
const requestId = (0, import_node_crypto.randomUUID)();
|
|
204
|
+
const response = await fetch(url.toString(), {
|
|
205
|
+
method: "GET",
|
|
206
|
+
headers: {
|
|
207
|
+
Authorization: this.#authorization,
|
|
208
|
+
"X-User-Agent": USER_AGENT,
|
|
209
|
+
"X-Request-Id": requestId
|
|
210
|
+
}
|
|
211
|
+
});
|
|
212
|
+
if (!response.ok) {
|
|
213
|
+
const errorBody = await response.json().catch(() => ({}));
|
|
214
|
+
throw new Error(
|
|
215
|
+
`Inworld API error: ${response.status} ${response.statusText}${errorBody.message ? ` - ${errorBody.message}` : ""} (request_id=${requestId})`
|
|
216
|
+
);
|
|
217
|
+
}
|
|
218
|
+
const data = await response.json();
|
|
219
|
+
return data.voices;
|
|
220
|
+
}
|
|
221
|
+
synthesize(text, connOptions, abortSignal) {
|
|
222
|
+
return new ChunkedStream(this, text, this.#opts, connOptions, abortSignal);
|
|
223
|
+
}
|
|
224
|
+
stream(options) {
|
|
225
|
+
return new SynthesizeStream(this, this.#opts, options == null ? void 0 : options.connOptions);
|
|
226
|
+
}
|
|
227
|
+
updateOptions(opts) {
|
|
228
|
+
this.#opts = { ...this.#opts, ...opts };
|
|
229
|
+
if (opts.apiKey) {
|
|
230
|
+
this.#authorization = `Basic ${opts.apiKey}`;
|
|
231
|
+
this.#pool.close();
|
|
232
|
+
this.#pool = new WSConnectionPool(this.#opts.wsURL, this.#authorization);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
async close() {
|
|
236
|
+
this.#pool.close();
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
class ChunkedStream extends import_agents.tts.ChunkedStream {
|
|
240
|
+
#opts;
|
|
241
|
+
#tts;
|
|
242
|
+
label = "inworld.ChunkedStream";
|
|
243
|
+
constructor(ttsInstance, text, opts, connOptions, abortSignal) {
|
|
244
|
+
super(text, ttsInstance, connOptions, abortSignal);
|
|
245
|
+
this.#tts = ttsInstance;
|
|
246
|
+
this.#opts = opts;
|
|
247
|
+
}
|
|
248
|
+
async run() {
|
|
249
|
+
const audioConfig = {
|
|
250
|
+
audioEncoding: this.#opts.encoding,
|
|
251
|
+
bitrate: this.#opts.bitRate,
|
|
252
|
+
sampleRateHertz: this.#opts.sampleRate,
|
|
253
|
+
temperature: this.#opts.temperature,
|
|
254
|
+
speakingRate: this.#opts.speakingRate
|
|
255
|
+
};
|
|
256
|
+
const bodyParams = {
|
|
257
|
+
text: this.inputText,
|
|
258
|
+
voiceId: this.#opts.voice,
|
|
259
|
+
modelId: this.#opts.model,
|
|
260
|
+
audioConfig,
|
|
261
|
+
temperature: this.#opts.temperature,
|
|
262
|
+
language: this.#opts.language,
|
|
263
|
+
timestampType: this.#opts.timestampType,
|
|
264
|
+
applyTextNormalization: this.#opts.textNormalization,
|
|
265
|
+
deliveryMode: this.#opts.deliveryMode,
|
|
266
|
+
timestampTransportStrategy: this.#opts.timestampTransportStrategy
|
|
267
|
+
};
|
|
268
|
+
const url = new URL("tts/v1/voice:stream", this.#opts.baseURL);
|
|
269
|
+
const requestId = (0, import_node_crypto.randomUUID)();
|
|
270
|
+
let response;
|
|
271
|
+
try {
|
|
272
|
+
response = await fetch(url.toString(), {
|
|
273
|
+
method: "POST",
|
|
274
|
+
headers: {
|
|
275
|
+
Authorization: this.#tts.authorization,
|
|
276
|
+
"Content-Type": "application/json",
|
|
277
|
+
"X-User-Agent": USER_AGENT,
|
|
278
|
+
"X-Request-Id": requestId
|
|
279
|
+
},
|
|
280
|
+
body: JSON.stringify(bodyParams),
|
|
281
|
+
signal: this.abortSignal
|
|
282
|
+
});
|
|
283
|
+
} catch (e) {
|
|
284
|
+
if (e instanceof Error && e.name === "AbortError") {
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
throw e;
|
|
288
|
+
}
|
|
289
|
+
if (!response.ok) {
|
|
290
|
+
throw new Error(
|
|
291
|
+
`Inworld API error: ${response.status} ${response.statusText} (request_id=${requestId})`
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
if (!response.body) {
|
|
295
|
+
throw new Error("No response body");
|
|
296
|
+
}
|
|
297
|
+
const reader = response.body.getReader();
|
|
298
|
+
const decoder = new TextDecoder();
|
|
299
|
+
let buffer = "";
|
|
300
|
+
const segmentId = (0, import_agents.shortuuid)();
|
|
301
|
+
const bstream = new import_agents.AudioByteStream(this.#opts.sampleRate, NUM_CHANNELS);
|
|
302
|
+
while (true) {
|
|
303
|
+
const { done, value } = await reader.read();
|
|
304
|
+
if (done) break;
|
|
305
|
+
buffer += decoder.decode(value, { stream: true });
|
|
306
|
+
const lines = buffer.split("\n");
|
|
307
|
+
buffer = lines.pop() || "";
|
|
308
|
+
for (const line of lines) {
|
|
309
|
+
if (line.trim()) {
|
|
310
|
+
try {
|
|
311
|
+
const data = JSON.parse(line);
|
|
312
|
+
if (data.result) {
|
|
313
|
+
if (data.result.audioContent) {
|
|
314
|
+
const audio = Buffer.from(data.result.audioContent, "base64");
|
|
315
|
+
let pcmData = audio;
|
|
316
|
+
if (audio.length > 44 && audio.subarray(0, 4).toString() === "RIFF") {
|
|
317
|
+
pcmData = audio.subarray(44);
|
|
318
|
+
}
|
|
319
|
+
for (const frame of bstream.write(
|
|
320
|
+
pcmData.buffer.slice(pcmData.byteOffset, pcmData.byteOffset + pcmData.byteLength)
|
|
321
|
+
)) {
|
|
322
|
+
this.queue.put({
|
|
323
|
+
requestId: segmentId,
|
|
324
|
+
segmentId,
|
|
325
|
+
frame,
|
|
326
|
+
final: false
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
} else if (data.error) {
|
|
331
|
+
throw new Error(data.error.message);
|
|
332
|
+
}
|
|
333
|
+
} catch (e) {
|
|
334
|
+
(0, import_agents.log)().warn({ error: e, line }, "Failed to parse Inworld chunk");
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
for (const frame of bstream.flush()) {
|
|
340
|
+
this.queue.put({
|
|
341
|
+
requestId: segmentId,
|
|
342
|
+
segmentId,
|
|
343
|
+
frame,
|
|
344
|
+
final: false
|
|
345
|
+
});
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
class SynthesizeStream extends import_agents.tts.SynthesizeStream {
|
|
350
|
+
#opts;
|
|
351
|
+
#tts;
|
|
352
|
+
#contextId;
|
|
353
|
+
// Cumulative timestamp tracking for monotonic timestamps across generations.
|
|
354
|
+
// When auto_mode is enabled or flush_context() is called, the server resets
|
|
355
|
+
// timestamps to 0 after each generation. We add cumulativeTime to maintain
|
|
356
|
+
// monotonically increasing timestamps within an agent turn.
|
|
357
|
+
#cumulativeTime = 0;
|
|
358
|
+
#generationEndTime = 0;
|
|
359
|
+
label = "inworld.SynthesizeStream";
|
|
360
|
+
constructor(ttsInstance, opts, connOptions) {
|
|
361
|
+
super(ttsInstance, connOptions);
|
|
362
|
+
this.#tts = ttsInstance;
|
|
363
|
+
this.#opts = opts;
|
|
364
|
+
this.#contextId = (0, import_agents.shortuuid)();
|
|
365
|
+
}
|
|
366
|
+
async run() {
|
|
367
|
+
this.#contextId = (0, import_agents.shortuuid)();
|
|
368
|
+
this.#cumulativeTime = 0;
|
|
369
|
+
this.#generationEndTime = 0;
|
|
370
|
+
const ws = await this.#tts.pool.getConnection();
|
|
371
|
+
const bstream = new import_agents.AudioByteStream(this.#opts.sampleRate, NUM_CHANNELS);
|
|
372
|
+
const tokenizerStream = this.#opts.tokenizer.stream();
|
|
373
|
+
let resolveProcessing;
|
|
374
|
+
let rejectProcessing;
|
|
375
|
+
const processing = new Promise((resolve, reject) => {
|
|
376
|
+
resolveProcessing = resolve;
|
|
377
|
+
rejectProcessing = reject;
|
|
378
|
+
});
|
|
379
|
+
processing.catch(() => {
|
|
380
|
+
});
|
|
381
|
+
const onClose = () => {
|
|
382
|
+
rejectProcessing(new import_agents.APIConnectionError({ message: "Inworld WebSocket closed" }));
|
|
383
|
+
};
|
|
384
|
+
ws.on("close", onClose);
|
|
385
|
+
let lastFrame;
|
|
386
|
+
let pendingTimedTranscripts = [];
|
|
387
|
+
const sendLastFrame = (final) => {
|
|
388
|
+
if (lastFrame && !this.queue.closed) {
|
|
389
|
+
this.queue.put({
|
|
390
|
+
requestId: this.#contextId,
|
|
391
|
+
segmentId: this.#contextId,
|
|
392
|
+
frame: lastFrame,
|
|
393
|
+
final,
|
|
394
|
+
timedTranscripts: pendingTimedTranscripts.length > 0 ? pendingTimedTranscripts : void 0
|
|
395
|
+
});
|
|
396
|
+
lastFrame = void 0;
|
|
397
|
+
pendingTimedTranscripts = [];
|
|
398
|
+
}
|
|
399
|
+
};
|
|
400
|
+
const handleMessage = (msg) => {
|
|
401
|
+
const result = msg.result;
|
|
402
|
+
if (!result) return;
|
|
403
|
+
if (result.contextCreated) {
|
|
404
|
+
} else if (result.contextClosed) {
|
|
405
|
+
resolveProcessing();
|
|
406
|
+
} else if (result.flushCompleted) {
|
|
407
|
+
this.#cumulativeTime = this.#generationEndTime;
|
|
408
|
+
} else if (result.audioChunk) {
|
|
409
|
+
if (result.audioChunk.timestampInfo) {
|
|
410
|
+
const tsInfo = result.audioChunk.timestampInfo;
|
|
411
|
+
if (tsInfo.wordAlignment) {
|
|
412
|
+
const words = tsInfo.wordAlignment.words || [];
|
|
413
|
+
const rawStarts = tsInfo.wordAlignment.wordStartTimeSeconds || [];
|
|
414
|
+
const rawEnds = tsInfo.wordAlignment.wordEndTimeSeconds || [];
|
|
415
|
+
const starts = rawStarts.map((t) => t + this.#cumulativeTime);
|
|
416
|
+
const ends = rawEnds.map((t) => t + this.#cumulativeTime);
|
|
417
|
+
if (ends.length > 0) {
|
|
418
|
+
this.#generationEndTime = Math.max(this.#generationEndTime, ends[ends.length - 1]);
|
|
419
|
+
}
|
|
420
|
+
for (let i = 0; i < words.length; i++) {
|
|
421
|
+
if (words[i] !== void 0 && starts[i] !== void 0 && ends[i] !== void 0) {
|
|
422
|
+
pendingTimedTranscripts.push(
|
|
423
|
+
(0, import_agents.createTimedString)({
|
|
424
|
+
text: words[i],
|
|
425
|
+
startTime: starts[i],
|
|
426
|
+
endTime: ends[i]
|
|
427
|
+
})
|
|
428
|
+
);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
this.#tts.emit("alignment", {
|
|
432
|
+
requestId: this.#contextId,
|
|
433
|
+
segmentId: this.#contextId,
|
|
434
|
+
wordAlignment: { words, starts, ends }
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
if (tsInfo.characterAlignment) {
|
|
438
|
+
const chars = tsInfo.characterAlignment.characters || [];
|
|
439
|
+
const rawStarts = tsInfo.characterAlignment.characterStartTimeSeconds || [];
|
|
440
|
+
const rawEnds = tsInfo.characterAlignment.characterEndTimeSeconds || [];
|
|
441
|
+
const starts = rawStarts.map((t) => t + this.#cumulativeTime);
|
|
442
|
+
const ends = rawEnds.map((t) => t + this.#cumulativeTime);
|
|
443
|
+
if (ends.length > 0) {
|
|
444
|
+
this.#generationEndTime = Math.max(this.#generationEndTime, ends[ends.length - 1]);
|
|
445
|
+
}
|
|
446
|
+
for (let i = 0; i < chars.length; i++) {
|
|
447
|
+
if (chars[i] !== void 0 && starts[i] !== void 0 && ends[i] !== void 0) {
|
|
448
|
+
pendingTimedTranscripts.push(
|
|
449
|
+
(0, import_agents.createTimedString)({
|
|
450
|
+
text: chars[i],
|
|
451
|
+
startTime: starts[i],
|
|
452
|
+
endTime: ends[i]
|
|
453
|
+
})
|
|
454
|
+
);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
this.#tts.emit("alignment", {
|
|
458
|
+
requestId: this.#contextId,
|
|
459
|
+
segmentId: this.#contextId,
|
|
460
|
+
characterAlignment: { chars, starts, ends }
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
if (result.audioChunk.audioContent) {
|
|
465
|
+
const b64Content = result.audioChunk.audioContent || result.audioContent;
|
|
466
|
+
if (b64Content) {
|
|
467
|
+
const audio = Buffer.from(b64Content, "base64");
|
|
468
|
+
let pcmData = audio;
|
|
469
|
+
if (audio.length > 44 && audio.subarray(0, 4).toString() === "RIFF") {
|
|
470
|
+
pcmData = audio.subarray(44);
|
|
471
|
+
}
|
|
472
|
+
for (const frame of bstream.write(
|
|
473
|
+
pcmData.buffer.slice(pcmData.byteOffset, pcmData.byteOffset + pcmData.byteLength)
|
|
474
|
+
)) {
|
|
475
|
+
sendLastFrame(false);
|
|
476
|
+
lastFrame = frame;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
} else if (result.status && result.status.code !== 0) {
|
|
481
|
+
rejectProcessing(
|
|
482
|
+
new import_agents.APIStatusError({
|
|
483
|
+
message: `Inworld stream error: ${result.status.message}`,
|
|
484
|
+
options: {
|
|
485
|
+
statusCode: result.status.code,
|
|
486
|
+
retryable: RETRYABLE_STATUS_CODES.has(result.status.code)
|
|
487
|
+
}
|
|
488
|
+
})
|
|
489
|
+
);
|
|
490
|
+
}
|
|
491
|
+
};
|
|
492
|
+
this.#tts.pool.registerListener(this.#contextId, handleMessage);
|
|
493
|
+
const sendLoop = async () => {
|
|
494
|
+
for await (const ev of tokenizerStream) {
|
|
495
|
+
await this.#sendText(ws, ev.token);
|
|
496
|
+
}
|
|
497
|
+
};
|
|
498
|
+
const sendPromise = sendLoop();
|
|
499
|
+
try {
|
|
500
|
+
await this.#createContext(ws);
|
|
501
|
+
for await (const text of this.input) {
|
|
502
|
+
if (text === import_agents.tts.SynthesizeStream.FLUSH_SENTINEL) {
|
|
503
|
+
tokenizerStream.flush();
|
|
504
|
+
} else {
|
|
505
|
+
tokenizerStream.pushText(text);
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
tokenizerStream.endInput();
|
|
509
|
+
await sendPromise;
|
|
510
|
+
await this.#flushContext(ws);
|
|
511
|
+
await this.#closeContext(ws);
|
|
512
|
+
const waitTimeoutMs = this.connOptions.timeoutMs + 6e4;
|
|
513
|
+
let timer;
|
|
514
|
+
const timeout = new Promise((_, reject) => {
|
|
515
|
+
var _a;
|
|
516
|
+
timer = setTimeout(() => {
|
|
517
|
+
reject(
|
|
518
|
+
new import_agents.APITimeoutError({
|
|
519
|
+
message: `Inworld synthesis timed out after ${waitTimeoutMs}ms`
|
|
520
|
+
})
|
|
521
|
+
);
|
|
522
|
+
}, waitTimeoutMs);
|
|
523
|
+
(_a = timer.unref) == null ? void 0 : _a.call(timer);
|
|
524
|
+
});
|
|
525
|
+
try {
|
|
526
|
+
await Promise.race([processing, timeout]);
|
|
527
|
+
} finally {
|
|
528
|
+
if (timer) clearTimeout(timer);
|
|
529
|
+
}
|
|
530
|
+
for (const frame of bstream.flush()) {
|
|
531
|
+
sendLastFrame(false);
|
|
532
|
+
lastFrame = frame;
|
|
533
|
+
}
|
|
534
|
+
sendLastFrame(true);
|
|
535
|
+
} catch (e) {
|
|
536
|
+
(0, import_agents.log)().error({ error: e }, "Error in SynthesizeStream run");
|
|
537
|
+
throw e;
|
|
538
|
+
} finally {
|
|
539
|
+
ws.off("close", onClose);
|
|
540
|
+
this.#tts.pool.unregisterListener(this.#contextId);
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
#send(ws, data) {
|
|
544
|
+
return new Promise((resolve, reject) => {
|
|
545
|
+
if (ws.readyState !== import_ws.WebSocket.OPEN) {
|
|
546
|
+
reject(new import_agents.APIConnectionError({ message: "Inworld WebSocket not open" }));
|
|
547
|
+
return;
|
|
548
|
+
}
|
|
549
|
+
ws.send(JSON.stringify(data), (err) => {
|
|
550
|
+
if (err) {
|
|
551
|
+
reject(
|
|
552
|
+
new import_agents.APIConnectionError({
|
|
553
|
+
message: `Inworld WebSocket send failed: ${(0, import_agents.asError)(err).message}`
|
|
554
|
+
})
|
|
555
|
+
);
|
|
556
|
+
} else {
|
|
557
|
+
resolve();
|
|
558
|
+
}
|
|
559
|
+
});
|
|
560
|
+
});
|
|
561
|
+
}
|
|
562
|
+
#createContext(ws) {
|
|
563
|
+
const config = {
|
|
564
|
+
voiceId: this.#opts.voice,
|
|
565
|
+
modelId: this.#opts.model,
|
|
566
|
+
audioConfig: {
|
|
567
|
+
audioEncoding: this.#opts.encoding,
|
|
568
|
+
sampleRateHertz: this.#opts.sampleRate,
|
|
569
|
+
bitrate: this.#opts.bitRate,
|
|
570
|
+
speakingRate: this.#opts.speakingRate
|
|
571
|
+
},
|
|
572
|
+
temperature: this.#opts.temperature,
|
|
573
|
+
language: this.#opts.language,
|
|
574
|
+
bufferCharThreshold: this.#opts.bufferCharThreshold,
|
|
575
|
+
maxBufferDelayMs: this.#opts.maxBufferDelayMs,
|
|
576
|
+
timestampType: this.#opts.timestampType,
|
|
577
|
+
applyTextNormalization: this.#opts.textNormalization,
|
|
578
|
+
deliveryMode: this.#opts.deliveryMode,
|
|
579
|
+
timestampTransportStrategy: this.#opts.timestampTransportStrategy,
|
|
580
|
+
// Always enable auto_mode since we use sentence tokenizer and don't expose
|
|
581
|
+
// mid-stream flush_context control to users yet
|
|
582
|
+
autoMode: true
|
|
583
|
+
};
|
|
584
|
+
return this.#send(ws, { create: config, contextId: this.#contextId });
|
|
585
|
+
}
|
|
586
|
+
#sendText(ws, text) {
|
|
587
|
+
return this.#send(ws, {
|
|
588
|
+
send_text: { text },
|
|
589
|
+
contextId: this.#contextId
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
#flushContext(ws) {
|
|
593
|
+
return this.#send(ws, {
|
|
594
|
+
flush_context: {},
|
|
595
|
+
contextId: this.#contextId
|
|
596
|
+
});
|
|
597
|
+
}
|
|
598
|
+
#closeContext(ws) {
|
|
599
|
+
return this.#send(ws, {
|
|
600
|
+
close_context: {},
|
|
601
|
+
contextId: this.#contextId
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
606
|
+
0 && (module.exports = {
|
|
607
|
+
TTS
|
|
608
|
+
});
|
|
609
|
+
//# sourceMappingURL=tts.cjs.map
|