@livekit/agents-plugin-inworld 1.9.4 → 1.10.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.
@@ -0,0 +1,140 @@
1
+ import { initializeLogger } from "@livekit/agents";
2
+ import { EventEmitter, once } from "node:events";
3
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4
+ import * as ws from "ws";
5
+ import { TTS } from "./tts.js";
6
+ const endpoint = vi.hoisted(() => ({ url: "" }));
7
+ vi.mock("ws", async (importOriginal) => {
8
+ const original = await importOriginal();
9
+ return {
10
+ ...original,
11
+ WebSocket: class extends original.WebSocket {
12
+ constructor(_url, options) {
13
+ super(endpoint.url, options);
14
+ }
15
+ }
16
+ };
17
+ });
18
+ let server;
19
+ let received;
20
+ const events = new EventEmitter();
21
+ function kinds() {
22
+ return received.map((m) => Object.keys(m).find((k) => k !== "contextId"));
23
+ }
24
+ async function waitFor(kind) {
25
+ while (!kinds().includes(kind)) await once(events, "message");
26
+ }
27
+ async function startServer({ answerClose }) {
28
+ received = [];
29
+ server = new ws.WebSocketServer({ host: "127.0.0.1", port: 0 });
30
+ server.on("connection", (socket) => {
31
+ socket.on("message", (data) => {
32
+ const msg = JSON.parse(data.toString());
33
+ received.push(msg);
34
+ events.emit("message");
35
+ const reply = (result) => socket.send(JSON.stringify({ result: { contextId: msg.contextId, ...result } }));
36
+ if ("create" in msg) reply({ contextCreated: {} });
37
+ if ("cancel_context" in msg || "close_context" in msg && answerClose) {
38
+ reply({ contextClosed: {} });
39
+ }
40
+ });
41
+ });
42
+ await once(server, "listening");
43
+ const address = server.address();
44
+ if (address === null || typeof address === "string") throw new Error("expected TCP address");
45
+ endpoint.url = `ws://127.0.0.1:${address.port}`;
46
+ }
47
+ function startStream() {
48
+ const provider = new TTS({ apiKey: "test", wsURL: endpoint.url });
49
+ return provider.stream({ connOptions: { maxRetry: 0, retryIntervalMs: 1, timeoutMs: 1e3 } });
50
+ }
51
+ beforeEach(() => {
52
+ initializeLogger({ pretty: false, level: "silent" });
53
+ });
54
+ afterEach(async () => {
55
+ vi.restoreAllMocks();
56
+ for (const client of server.clients) client.terminate();
57
+ await new Promise((resolve) => server.close(() => resolve()));
58
+ });
59
+ function holdSend(kind, forward) {
60
+ const original = ws.WebSocket.prototype.send;
61
+ let release;
62
+ const held = new Promise((resolve) => release = resolve);
63
+ let holding = true;
64
+ vi.spyOn(ws.WebSocket.prototype, "send").mockImplementation(function(data, ...rest) {
65
+ const cb = rest.find((r) => typeof r === "function");
66
+ if (holding && cb && String(data).includes(`"${kind}"`)) {
67
+ holding = false;
68
+ if (forward) original.call(this, data);
69
+ release(cb);
70
+ return;
71
+ }
72
+ return original.call(this, data, ...rest);
73
+ });
74
+ return held;
75
+ }
76
+ describe("inworld TTS context lifecycle", () => {
77
+ it("closes the context when the input ends", async () => {
78
+ await startServer({ answerClose: true });
79
+ const stream = startStream();
80
+ stream.pushText("Hello there.");
81
+ stream.endInput();
82
+ for await (const _ of stream) {
83
+ }
84
+ expect(kinds()).toEqual(["create", "send_text", "flush_context", "close_context"]);
85
+ });
86
+ it("cancels the context when the stream is closed mid-reply", async () => {
87
+ await startServer({ answerClose: true });
88
+ const stream = startStream();
89
+ stream.pushText("Hello there. How are you doing today? ");
90
+ stream.flush();
91
+ await waitFor("send_text");
92
+ stream.close();
93
+ await waitFor("cancel_context");
94
+ expect(kinds()).not.toContain("close_context");
95
+ expect(new Set(received.map((m) => m.contextId)).size).toBe(1);
96
+ });
97
+ it("cancels a closing context when the stream is closed", async () => {
98
+ await startServer({ answerClose: false });
99
+ const stream = startStream();
100
+ stream.pushText("Hello there. How are you doing today?");
101
+ stream.endInput();
102
+ await waitFor("close_context");
103
+ stream.close();
104
+ await waitFor("cancel_context");
105
+ expect(kinds().slice(-2)).toEqual(["close_context", "cancel_context"]);
106
+ });
107
+ it("cancels without closing when the stream is closed during the flush", async () => {
108
+ await startServer({ answerClose: false });
109
+ const flushSent = holdSend("flush_context", true);
110
+ const stream = startStream();
111
+ stream.pushText("Hello there. How are you doing today?");
112
+ stream.endInput();
113
+ const settleFlush = await flushSent;
114
+ stream.close();
115
+ settleFlush();
116
+ await waitFor("cancel_context");
117
+ expect(kinds()).toContain("flush_context");
118
+ expect(kinds()).not.toContain("close_context");
119
+ });
120
+ it("ignores a text send that fails after the stream is closed", async () => {
121
+ await startServer({ answerClose: true });
122
+ const unhandled = vi.fn();
123
+ process.on("unhandledRejection", unhandled);
124
+ try {
125
+ const textSent = holdSend("send_text", false);
126
+ const stream = startStream();
127
+ stream.pushText("Hello there. How are you doing today? ");
128
+ stream.flush();
129
+ const failText = await textSent;
130
+ stream.close();
131
+ await waitFor("cancel_context");
132
+ failText(new Error("send failed"));
133
+ await new Promise((resolve) => setTimeout(resolve, 50));
134
+ expect(unhandled).not.toHaveBeenCalled();
135
+ } finally {
136
+ process.off("unhandledRejection", unhandled);
137
+ }
138
+ });
139
+ });
140
+ //# sourceMappingURL=tts_context.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/tts_context.test.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2026 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { initializeLogger } from '@livekit/agents';\nimport { EventEmitter, once } from 'node:events';\nimport { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';\nimport * as ws from 'ws';\nimport { TTS } from './tts.js';\n\nconst endpoint = vi.hoisted(() => ({ url: '' }));\nvi.mock('ws', async (importOriginal) => {\n const original = await importOriginal<typeof ws>();\n return {\n ...original,\n WebSocket: class extends original.WebSocket {\n constructor(_url: string, options: ws.ClientOptions) {\n super(endpoint.url, options);\n }\n },\n };\n});\n\ntype Message = { contextId: string } & Record<string, unknown>;\n\nlet server: ws.WebSocketServer;\nlet received: Message[];\nconst events = new EventEmitter();\n\nfunction kinds() {\n return received.map((m) => Object.keys(m).find((k) => k !== 'contextId'));\n}\n\nasync function waitFor(kind: string) {\n while (!kinds().includes(kind)) await once(events, 'message');\n}\n\nasync function startServer({ answerClose }: { answerClose: boolean }) {\n received = [];\n server = new ws.WebSocketServer({ host: '127.0.0.1', port: 0 });\n server.on('connection', (socket) => {\n socket.on('message', (data) => {\n const msg = JSON.parse(data.toString()) as Message;\n received.push(msg);\n events.emit('message');\n const reply = (result: object) =>\n socket.send(JSON.stringify({ result: { contextId: msg.contextId, ...result } }));\n if ('create' in msg) reply({ contextCreated: {} });\n if ('cancel_context' in msg || ('close_context' in msg && answerClose)) {\n reply({ contextClosed: {} });\n }\n });\n });\n await once(server, 'listening');\n const address = server.address();\n if (address === null || typeof address === 'string') throw new Error('expected TCP address');\n endpoint.url = `ws://127.0.0.1:${address.port}`;\n}\n\nfunction startStream() {\n const provider = new TTS({ apiKey: 'test', wsURL: endpoint.url });\n return provider.stream({ connOptions: { maxRetry: 0, retryIntervalMs: 1, timeoutMs: 1000 } });\n}\n\nbeforeEach(() => {\n initializeLogger({ pretty: false, level: 'silent' });\n});\n\nafterEach(async () => {\n vi.restoreAllMocks();\n for (const client of server.clients) client.terminate();\n await new Promise<void>((resolve) => server.close(() => resolve()));\n});\n\ntype SendCallback = (err?: Error) => void;\n\n// Holds the client's send callback for the first payload of `kind`, so a test can\n// settle that send after closing the stream.\nfunction holdSend(kind: string, forward: boolean) {\n const original = ws.WebSocket.prototype.send;\n let release!: (cb: SendCallback) => void;\n const held = new Promise<SendCallback>((resolve) => (release = resolve));\n let holding = true;\n vi.spyOn(ws.WebSocket.prototype, 'send').mockImplementation(function (\n this: ws.WebSocket,\n data: unknown,\n ...rest: unknown[]\n ) {\n const cb = rest.find((r): r is SendCallback => typeof r === 'function');\n if (holding && cb && String(data).includes(`\"${kind}\"`)) {\n holding = false;\n if (forward) original.call(this, data as string);\n release(cb);\n return;\n }\n return (original as (...args: unknown[]) => void).call(this, data, ...rest);\n });\n return held;\n}\n\ndescribe('inworld TTS context lifecycle', () => {\n it('closes the context when the input ends', async () => {\n await startServer({ answerClose: true });\n const stream = startStream();\n stream.pushText('Hello there.');\n stream.endInput();\n for await (const _ of stream) {\n /* drain */\n }\n\n expect(kinds()).toEqual(['create', 'send_text', 'flush_context', 'close_context']);\n });\n\n it('cancels the context when the stream is closed mid-reply', async () => {\n await startServer({ answerClose: true });\n const stream = startStream();\n stream.pushText('Hello there. How are you doing today? ');\n stream.flush();\n await waitFor('send_text');\n stream.close();\n await waitFor('cancel_context');\n\n expect(kinds()).not.toContain('close_context');\n expect(new Set(received.map((m) => m.contextId)).size).toBe(1);\n });\n\n it('cancels a closing context when the stream is closed', async () => {\n await startServer({ answerClose: false });\n const stream = startStream();\n stream.pushText('Hello there. How are you doing today?');\n stream.endInput();\n await waitFor('close_context');\n stream.close();\n await waitFor('cancel_context');\n\n expect(kinds().slice(-2)).toEqual(['close_context', 'cancel_context']);\n });\n\n it('cancels without closing when the stream is closed during the flush', async () => {\n await startServer({ answerClose: false });\n const flushSent = holdSend('flush_context', true);\n const stream = startStream();\n stream.pushText('Hello there. How are you doing today?');\n stream.endInput();\n const settleFlush = await flushSent;\n stream.close();\n settleFlush();\n await waitFor('cancel_context');\n\n expect(kinds()).toContain('flush_context');\n expect(kinds()).not.toContain('close_context');\n });\n\n it('ignores a text send that fails after the stream is closed', async () => {\n await startServer({ answerClose: true });\n const unhandled = vi.fn();\n process.on('unhandledRejection', unhandled);\n try {\n const textSent = holdSend('send_text', false);\n const stream = startStream();\n stream.pushText('Hello there. How are you doing today? ');\n stream.flush();\n const failText = await textSent;\n stream.close();\n await waitFor('cancel_context');\n failText(new Error('send failed'));\n await new Promise((resolve) => setTimeout(resolve, 50));\n\n expect(unhandled).not.toHaveBeenCalled();\n } finally {\n process.off('unhandledRejection', unhandled);\n }\n });\n});\n"],"mappings":"AAGA,SAAS,wBAAwB;AACjC,SAAS,cAAc,YAAY;AACnC,SAAS,WAAW,YAAY,UAAU,QAAQ,IAAI,UAAU;AAChE,YAAY,QAAQ;AACpB,SAAS,WAAW;AAEpB,MAAM,WAAW,GAAG,QAAQ,OAAO,EA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1E,UAAM,YAAY,EAAE,aAAa,KAAK,CAAC;AACvC,UAAM,YAAY,GAAG,GAAG;AACxB,YAAQ,GAAG,sBAAsB,SAAS;AAC1C,QAAI;AACF,YAAM,WAAW,SAAS,aAAa,KAAK;AAC5C,YAAM,SAAS,YAAY;AAC3B,aAAO,SAAS,wCAAwC;AACxD,aAAO,MAAM;AACb,YAAM,WAAW,MAAM;AACvB,aAAO,MAAM;AACb,YAAM,QAAQ,gBAAgB;AAC9B,eAAS,IAAI,MAAM,aAAa,CAAC;AACjC,YAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AAEtD,aAAO,SAAS,EAAE,IAAI,iBAAiB;AAAA,IACzC,UAAE;AACA,cAAQ,IAAI,sBAAsB,SAAS;AAAA,IAC7C;AAAA,EACF,CAAC;AACH,CAAC;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@livekit/agents-plugin-inworld",
3
- "version": "1.9.4",
3
+ "version": "1.10.0",
4
4
  "description": "Inworld plugin for LiveKit Node Agents",
5
5
  "main": "dist/index.js",
6
6
  "require": "dist/index.cjs",
@@ -28,21 +28,21 @@
28
28
  "README.md"
29
29
  ],
30
30
  "devDependencies": {
31
- "@livekit/rtc-node": "^1.1.0",
31
+ "@livekit/rtc-node": "^1.2.2",
32
32
  "@microsoft/api-extractor": "^7.58.12",
33
33
  "@types/ws": "^8.5.10",
34
34
  "tsup": "^8.3.5",
35
35
  "typescript": "^5.0.0",
36
- "@livekit/agents": "1.9.4",
37
- "@livekit/agents-plugin-openai": "1.9.4",
38
- "@livekit/agents-plugins-test": "1.9.4"
36
+ "@livekit/agents": "1.10.0",
37
+ "@livekit/agents-plugin-openai": "1.10.0",
38
+ "@livekit/agents-plugins-test": "1.10.0"
39
39
  },
40
40
  "dependencies": {
41
41
  "ws": "^8.21.0"
42
42
  },
43
43
  "peerDependencies": {
44
- "@livekit/rtc-node": "^1.1.0",
45
- "@livekit/agents": "1.9.4"
44
+ "@livekit/rtc-node": "^1.2.2",
45
+ "@livekit/agents": "1.10.0"
46
46
  },
47
47
  "scripts": {
48
48
  "build": "tsup --onSuccess \"pnpm build:types\"",
package/src/tts.ts CHANGED
@@ -31,7 +31,7 @@ const DEFAULT_VOICE = 'Jason';
31
31
  const DEFAULT_TEMPERATURE = 1.1;
32
32
  const DEFAULT_TIMESTAMP_TRANSPORT_STRATEGY = 'ASYNC';
33
33
  const DEFAULT_SPEAKING_RATE = 1.0;
34
- const DEFAULT_BUFFER_CHAR_THRESHOLD = 100;
34
+ const DEFAULT_BUFFER_CHAR_THRESHOLD = 250;
35
35
  const DEFAULT_MAX_BUFFER_DELAY_MS = 3000;
36
36
  const NUM_CHANNELS = 1;
37
37
 
@@ -44,6 +44,7 @@ export type TimestampTransportStrategy =
44
44
  | 'SYNC'
45
45
  | 'ASYNC';
46
46
  export type DeliveryMode = 'DELIVERY_MODE_UNSPECIFIED' | 'STABLE' | 'BALANCED' | 'CREATIVE';
47
+ type AutoModeStrategy = 'CLIENT_SEGMENTED' | 'SENTENCE_BOUNDARY';
47
48
 
48
49
  export interface TTSOptions {
49
50
  apiKey?: string;
@@ -61,10 +62,19 @@ export interface TTSOptions {
61
62
  /** Controls output variation on inworld-tts-2 only. */
62
63
  deliveryMode?: DeliveryMode;
63
64
  timestampTransportStrategy?: TimestampTransportStrategy;
64
- bufferCharThreshold: number;
65
+ /**
66
+ * Buffered characters that trigger synthesis. Defaults to 250, or to the server default when the
67
+ * server splits sentences.
68
+ */
69
+ bufferCharThreshold?: number;
65
70
  maxBufferDelayMs: number;
66
71
  baseURL: string;
67
72
  wsURL: string;
73
+ /**
74
+ * Splits streamed text into sentences before sending. When unset, inworld-tts-2 models stream
75
+ * text as it arrives and the server splits it at sentence boundaries; other models use the blingfire
76
+ * sentence tokenizer.
77
+ */
68
78
  tokenizer?: tokenize.SentenceTokenizer;
69
79
  }
70
80
 
@@ -96,13 +106,14 @@ interface CreateContextConfig {
96
106
  audioConfig: AudioConfig;
97
107
  temperature: number;
98
108
  language?: string;
99
- bufferCharThreshold: number;
109
+ bufferCharThreshold?: number;
100
110
  maxBufferDelayMs: number;
101
111
  timestampType?: TimestampType;
102
112
  applyTextNormalization?: TextNormalization;
103
113
  deliveryMode?: DeliveryMode;
104
114
  timestampTransportStrategy?: TimestampTransportStrategy;
105
115
  autoMode?: boolean;
116
+ autoModeStrategy?: AutoModeStrategy;
106
117
  }
107
118
 
108
119
  interface WordAlignment {
@@ -165,12 +176,16 @@ const defaultTTSOptionsBase: Omit<TTSOptions, 'tokenizer'> = {
165
176
  speakingRate: DEFAULT_SPEAKING_RATE,
166
177
  temperature: DEFAULT_TEMPERATURE,
167
178
  timestampTransportStrategy: DEFAULT_TIMESTAMP_TRANSPORT_STRATEGY as TimestampTransportStrategy,
168
- bufferCharThreshold: DEFAULT_BUFFER_CHAR_THRESHOLD,
169
179
  maxBufferDelayMs: DEFAULT_MAX_BUFFER_DELAY_MS,
170
180
  baseURL: DEFAULT_URL,
171
181
  wsURL: DEFAULT_WS_URL,
172
182
  };
173
183
 
184
+ const defaultTokenizer = new tokenize.blingfire.SentenceTokenizer({ retainFormat: true });
185
+
186
+ // The SENTENCE_BOUNDARY auto-mode strategy is only served by inworld-tts-2 models.
187
+ const supportsSentenceBoundary = (model: string) => model.startsWith('inworld-tts-2');
188
+
174
189
  const CONNECT_TIMEOUT_MS = 10_000; // WebSocket handshake timeout
175
190
 
176
191
  // Transient gRPC-style status codes worth retrying; everything else is treated as
@@ -324,9 +339,6 @@ export class TTS extends tts.TTS {
324
339
  });
325
340
 
326
341
  this.#opts = mergedOpts as TTSOptions;
327
- if (!this.#opts.tokenizer) {
328
- this.#opts.tokenizer = new tokenize.blingfire.SentenceTokenizer({ retainFormat: true });
329
- }
330
342
  this.#authorization = `Basic ${mergedOpts.apiKey}`;
331
343
  this.#pool = new WSConnectionPool(this.#opts.wsURL, this.#authorization);
332
344
  }
@@ -569,7 +581,11 @@ class SynthesizeStream extends tts.SynthesizeStream {
569
581
  const pool = this.#tts.pool;
570
582
  const ws = await pool.getConnection();
571
583
  const bstream = new AudioByteStream(this.#opts.sampleRate, NUM_CHANNELS);
572
- const tokenizerStream = this.#opts.tokenizer!.stream();
584
+ const autoModeStrategy: AutoModeStrategy =
585
+ !this.#opts.tokenizer && supportsSentenceBoundary(this.#opts.model)
586
+ ? 'SENTENCE_BOUNDARY'
587
+ : 'CLIENT_SEGMENTED';
588
+ const tokenizerStream = (this.#opts.tokenizer ?? defaultTokenizer).stream();
573
589
 
574
590
  let resolveProcessing: () => void;
575
591
  let rejectProcessing: (err: Error) => void;
@@ -733,27 +749,61 @@ class SynthesizeStream extends tts.SynthesizeStream {
733
749
 
734
750
  pool.registerListener(this.#contextId, handleMessage);
735
751
 
752
+ // Closing the stream also closes its input, so the input loop below ends and
753
+ // the reply is abandoned: the context is cancelled instead of closed.
754
+ const aborted = new Promise<void>((resolve) => {
755
+ if (this.abortSignal.aborted) resolve();
756
+ else this.abortSignal.addEventListener('abort', () => resolve(), { once: true });
757
+ });
758
+
736
759
  const sendLoop = async () => {
737
760
  for await (const ev of tokenizerStream) {
761
+ if (this.abortSignal.aborted) break;
738
762
  await this.#sendText(ws, ev.token);
739
763
  }
740
764
  };
741
765
  const sendPromise = sendLoop();
766
+ // An aborted stream returns without awaiting the sender, so a send that fails
767
+ // afterwards must not become an unhandled rejection.
768
+ sendPromise.catch(() => {});
742
769
 
743
770
  try {
744
- await this.#createContext(ws);
771
+ await this.#createContext(ws, autoModeStrategy);
745
772
 
746
773
  for await (const text of this.input) {
747
- if (text === tts.SynthesizeStream.FLUSH_SENTINEL) {
774
+ if (autoModeStrategy === 'SENTENCE_BOUNDARY') {
775
+ // the server buffers partial sentences until it finds a boundary
776
+ if (text === tts.SynthesizeStream.FLUSH_SENTINEL) {
777
+ await this.#flushContext(ws);
778
+ } else if (text) {
779
+ await this.#sendText(ws, text);
780
+ }
781
+ } else if (text === tts.SynthesizeStream.FLUSH_SENTINEL) {
748
782
  tokenizerStream.flush();
749
783
  } else {
750
784
  tokenizerStream.pushText(text);
751
785
  }
752
786
  }
787
+ if (this.abortSignal.aborted) {
788
+ tokenizerStream.close();
789
+ await this.#cancelContext(ws);
790
+ return;
791
+ }
753
792
  tokenizerStream.endInput();
754
793
  await sendPromise;
794
+ if (this.abortSignal.aborted) {
795
+ await this.#cancelContext(ws);
796
+ return;
797
+ }
755
798
 
756
- await this.#flushContext(ws);
799
+ // endInput() already flushed the server-segmented stream
800
+ if (autoModeStrategy === 'CLIENT_SEGMENTED') {
801
+ await this.#flushContext(ws);
802
+ }
803
+ if (this.abortSignal.aborted) {
804
+ await this.#cancelContext(ws);
805
+ return;
806
+ }
757
807
  await this.#closeContext(ws);
758
808
 
759
809
  // Wait for the server to finish the context, but bound it so a stalled
@@ -772,10 +822,17 @@ class SynthesizeStream extends tts.SynthesizeStream {
772
822
  timer.unref?.();
773
823
  });
774
824
  try {
775
- await Promise.race([processing, timeout]);
825
+ await Promise.race([processing, timeout, aborted]);
826
+ } catch (e) {
827
+ if (e instanceof APITimeoutError) await this.#cancelContext(ws);
828
+ throw e;
776
829
  } finally {
777
830
  if (timer) clearTimeout(timer);
778
831
  }
832
+ if (this.abortSignal.aborted) {
833
+ await this.#cancelContext(ws);
834
+ return;
835
+ }
779
836
 
780
837
  // Flush remaining frames
781
838
  for (const frame of bstream.flush()) {
@@ -812,7 +869,7 @@ class SynthesizeStream extends tts.SynthesizeStream {
812
869
  });
813
870
  }
814
871
 
815
- #createContext(ws: WebSocket): Promise<void> {
872
+ #createContext(ws: WebSocket, autoModeStrategy: AutoModeStrategy): Promise<void> {
816
873
  const config: CreateContextConfig = {
817
874
  voiceId: this.#opts.voice,
818
875
  modelId: this.#opts.model,
@@ -824,16 +881,20 @@ class SynthesizeStream extends tts.SynthesizeStream {
824
881
  },
825
882
  temperature: this.#opts.temperature,
826
883
  language: this.#opts.language,
827
- bufferCharThreshold: this.#opts.bufferCharThreshold,
884
+ // with SENTENCE_BOUNDARY the threshold also cuts long sentences, so only a set value is sent
885
+ bufferCharThreshold:
886
+ this.#opts.bufferCharThreshold ??
887
+ (autoModeStrategy === 'SENTENCE_BOUNDARY' ? undefined : DEFAULT_BUFFER_CHAR_THRESHOLD),
828
888
  maxBufferDelayMs: this.#opts.maxBufferDelayMs,
829
889
  timestampType: this.#opts.timestampType,
830
890
  applyTextNormalization: this.#opts.textNormalization,
831
891
  deliveryMode: this.#opts.deliveryMode,
832
892
  timestampTransportStrategy: this.#opts.timestampTransportStrategy,
833
- // Always enable auto_mode since we use sentence tokenizer and don't expose
834
- // mid-stream flush_context control to users yet
835
893
  autoMode: true,
836
894
  };
895
+ if (autoModeStrategy === 'SENTENCE_BOUNDARY') {
896
+ config.autoModeStrategy = autoModeStrategy;
897
+ }
837
898
 
838
899
  return this.#send(ws, { create: config, contextId: this.#contextId });
839
900
  }
@@ -859,4 +920,13 @@ class SynthesizeStream extends tts.SynthesizeStream {
859
920
  contextId: this.#contextId,
860
921
  });
861
922
  }
923
+
924
+ // Stops the context and discards text the server has not synthesized yet.
925
+ async #cancelContext(ws: WebSocket): Promise<void> {
926
+ try {
927
+ await this.#send(ws, { cancel_context: {}, contextId: this.#contextId });
928
+ } catch (e) {
929
+ log().debug({ error: e }, 'Failed to cancel Inworld context');
930
+ }
931
+ }
862
932
  }
@@ -0,0 +1,105 @@
1
+ // SPDX-FileCopyrightText: 2026 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import { initializeLogger, tokenize } from '@livekit/agents';
5
+ import { once } from 'node:events';
6
+ import { afterEach, beforeAll, describe, expect, it } from 'vitest';
7
+ import { WebSocketServer } from 'ws';
8
+ import { TTS, type TTSOptions } from './tts.js';
9
+
10
+ type Message = Record<string, Record<string, unknown> | string>;
11
+
12
+ let server: WebSocketServer | undefined;
13
+ let provider: TTS | undefined;
14
+
15
+ beforeAll(() => {
16
+ initializeLogger({ pretty: false, level: 'silent' });
17
+ });
18
+
19
+ afterEach(async () => {
20
+ await provider?.close();
21
+ provider = undefined;
22
+ if (server) {
23
+ for (const client of server.clients) client.terminate();
24
+ await new Promise<void>((resolve) => server!.close(() => resolve()));
25
+ server = undefined;
26
+ }
27
+ });
28
+
29
+ // Runs one stream against a fake Inworld server and returns the messages it received.
30
+ async function synthesize(opts: Partial<TTSOptions>, input: string[]): Promise<Message[]> {
31
+ server = new WebSocketServer({ host: '127.0.0.1', port: 0 });
32
+ await once(server, 'listening');
33
+ const address = server.address();
34
+ if (address === null || typeof address === 'string') throw new Error('expected TCP address');
35
+
36
+ const received: Message[] = [];
37
+ server.on('connection', (socket) => {
38
+ socket.on('message', (data) => {
39
+ const msg = JSON.parse(data.toString()) as Message;
40
+ received.push(msg);
41
+ if ('close_context' in msg) {
42
+ const contextId = msg.contextId;
43
+ const audioContent = Buffer.alloc(4800).toString('base64');
44
+ socket.send(JSON.stringify({ result: { contextId, audioChunk: { audioContent } } }));
45
+ socket.send(JSON.stringify({ result: { contextId, contextClosed: {} } }));
46
+ }
47
+ });
48
+ });
49
+
50
+ provider = new TTS({ apiKey: 'test', wsURL: `ws://127.0.0.1:${address.port}/`, ...opts });
51
+ const stream = provider.stream();
52
+ for (const text of input) stream.pushText(text);
53
+ stream.endInput();
54
+ for await (const _ of stream) {
55
+ /* drain */
56
+ }
57
+ return received;
58
+ }
59
+
60
+ const tokens = ['Hello', ' there.', ' How', ' are', ' you?'];
61
+
62
+ describe('Inworld auto mode strategy', () => {
63
+ it('streams raw text with SENTENCE_BOUNDARY on inworld-tts-2', async () => {
64
+ const received = await synthesize({ model: 'inworld-tts-2' }, tokens);
65
+
66
+ const create = received[0]!.create as Record<string, unknown>;
67
+ expect(create.autoMode).toBe(true);
68
+ expect(create.autoModeStrategy).toBe('SENTENCE_BOUNDARY');
69
+ expect(create).not.toHaveProperty('bufferCharThreshold');
70
+ expect(received.slice(1).map((m) => Object.keys(m)[0])).toEqual([
71
+ ...tokens.map(() => 'send_text'),
72
+ 'flush_context',
73
+ 'close_context',
74
+ ]);
75
+ expect(received.slice(1, 6).map((m) => (m.send_text as { text: string }).text)).toEqual(tokens);
76
+ });
77
+
78
+ it('keeps client segmentation with a custom tokenizer', async () => {
79
+ const received = await synthesize(
80
+ {
81
+ model: 'inworld-tts-2',
82
+ tokenizer: new tokenize.basic.SentenceTokenizer({ minSentenceLength: 1 }),
83
+ },
84
+ tokens,
85
+ );
86
+
87
+ expect(received[0]!.create).not.toHaveProperty('autoModeStrategy');
88
+ expect(received[0]!.create).toHaveProperty('bufferCharThreshold', 250);
89
+ const texts = received.filter((m) => 'send_text' in m);
90
+ expect(texts.length).toBeLessThan(tokens.length);
91
+ });
92
+
93
+ it('sends a set bufferCharThreshold with SENTENCE_BOUNDARY', async () => {
94
+ const received = await synthesize({ model: 'inworld-tts-2', bufferCharThreshold: 400 }, tokens);
95
+
96
+ expect(received[0]!.create).toHaveProperty('autoModeStrategy', 'SENTENCE_BOUNDARY');
97
+ expect(received[0]!.create).toHaveProperty('bufferCharThreshold', 400);
98
+ });
99
+
100
+ it('keeps client segmentation on models without sentence boundary support', async () => {
101
+ const received = await synthesize({ model: 'inworld-tts-1.5-max' }, tokens);
102
+
103
+ expect(received[0]!.create).not.toHaveProperty('autoModeStrategy');
104
+ });
105
+ });