@kuralle-syrinx/gemini 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kuralle
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
package/package.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "@kuralle-syrinx/gemini",
3
+ "version": "2.1.0",
4
+ "private": false,
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "main": "./src/index.ts",
8
+ "types": "./src/index.ts",
9
+ "dependencies": {
10
+ "@google/genai": "^1.0.0",
11
+ "@kuralle-syrinx/core": "2.1.0"
12
+ },
13
+ "devDependencies": {
14
+ "typescript": "^5.7.0",
15
+ "vitest": "^2.1.0"
16
+ },
17
+ "scripts": {
18
+ "typecheck": "tsc --noEmit",
19
+ "test": "vitest run"
20
+ }
21
+ }
@@ -0,0 +1,76 @@
1
+ // SPDX-License-Identifier: MIT
2
+
3
+ import { afterEach, describe, expect, it, vi } from "vitest";
4
+ import {
5
+ PipelineBusImpl,
6
+ Route,
7
+ type TextToSpeechAudioPacket,
8
+ type TtsErrorPacket,
9
+ } from "@kuralle-syrinx/core";
10
+ import { GeminiTTSPlugin } from "./index.js";
11
+
12
+ const generateContent = vi.fn();
13
+
14
+ vi.mock("@google/genai", () => ({
15
+ GoogleGenAI: vi.fn().mockImplementation(() => ({
16
+ models: { generateContent },
17
+ })),
18
+ }));
19
+
20
+ afterEach(() => {
21
+ generateContent.mockReset();
22
+ });
23
+
24
+ describe("GeminiTTSPlugin", () => {
25
+ it("emits tts.error for odd-length PCM16 without throwing into the bus pump", async () => {
26
+ generateContent.mockResolvedValue({
27
+ candidates: [{
28
+ content: {
29
+ parts: [{
30
+ inlineData: {
31
+ mimeType: "audio/pcm",
32
+ data: Buffer.from(new Uint8Array([1, 2, 3])).toString("base64"),
33
+ },
34
+ }],
35
+ },
36
+ }],
37
+ });
38
+
39
+ const bus = new PipelineBusImpl();
40
+ const started = bus.start();
41
+ const plugin = new GeminiTTSPlugin();
42
+ const audio: TextToSpeechAudioPacket[] = [];
43
+ const errors: TtsErrorPacket[] = [];
44
+ bus.on("tts.audio", (pkt) => {
45
+ audio.push(pkt as TextToSpeechAudioPacket);
46
+ });
47
+ bus.on("tts.error", (pkt) => {
48
+ errors.push(pkt as TtsErrorPacket);
49
+ });
50
+
51
+ await plugin.initialize(bus, { api_key: "test-gemini-key" });
52
+ bus.push(Route.Main, {
53
+ kind: "tts.done",
54
+ contextId: "turn-odd-pcm",
55
+ timestampMs: Date.now(),
56
+ text: "Hello.",
57
+ });
58
+ await new Promise((resolve) => setTimeout(resolve, 50));
59
+
60
+ expect(audio).toEqual([]);
61
+ expect(errors).toEqual([
62
+ expect.objectContaining({
63
+ kind: "tts.error",
64
+ contextId: "turn-odd-pcm",
65
+ component: "tts",
66
+ cause: expect.objectContaining({
67
+ message: expect.stringMatching(/even number of bytes/i),
68
+ }),
69
+ }),
70
+ ]);
71
+
72
+ await plugin.close();
73
+ bus.stop();
74
+ await started;
75
+ });
76
+ });
package/src/index.ts ADDED
@@ -0,0 +1,266 @@
1
+ // SPDX-License-Identifier: MIT
2
+ //
3
+ // Syrinx Kernel v2 — Gemini TTS Plugin
4
+ //
5
+ // Uses Google Gemini's multimodal API (`responseModalities: ['AUDIO']`) to
6
+ // synthesize speech. Non-streaming (chunked) — sends full text, receives
7
+ // complete audio. Modeled after LiveKit's google.gemini.TTS implementation.
8
+ //
9
+ // Reference: LiveKit agents-js plugins/google/src/beta/gemini_tts.ts
10
+ // Reference: Rapida transformer/google/tts.go (GCP TTS API, not Gemini)
11
+
12
+ import type { PipelineBus } from "@kuralle-syrinx/core";
13
+ import {
14
+ Route,
15
+ type AudioFormat,
16
+ type VoicePlugin,
17
+ type PluginConfig,
18
+ type TextToSpeechEndPacket,
19
+ assertAudioFormat,
20
+ assertAudioPayload,
21
+ requireStringConfig,
22
+ optionalStringConfig,
23
+ categorizeTtsError,
24
+ isRecoverable,
25
+ readRetryConfig,
26
+ waitForRetryDelay,
27
+ type RetryConfig,
28
+ } from "@kuralle-syrinx/core";
29
+
30
+ // =============================================================================
31
+ // Types
32
+ // =============================================================================
33
+
34
+ export type GeminiVoice =
35
+ | "Kore"
36
+ | "Puck"
37
+ | "Charon"
38
+ | "Fenrir"
39
+ | "Leda"
40
+ | "Aoede"
41
+ | "Zephyr"
42
+ | "Orus";
43
+
44
+ export type GeminiTTSModel =
45
+ | "gemini-3.1-flash-tts-preview"
46
+ | "gemini-2.5-flash-preview-tts"
47
+ | "gemini-2.5-pro-preview-tts";
48
+
49
+ const DEFAULT_MODEL: GeminiTTSModel = "gemini-3.1-flash-tts-preview";
50
+ const DEFAULT_VOICE: GeminiVoice = "Kore";
51
+ const SAMPLE_RATE = 24000;
52
+
53
+ // =============================================================================
54
+ // Plugin
55
+ // =============================================================================
56
+
57
+ export class GeminiTTSPlugin implements VoicePlugin {
58
+ private bus: PipelineBus | null = null;
59
+ private apiKey: string = "";
60
+ private model: string = DEFAULT_MODEL;
61
+ private voiceName: string = DEFAULT_VOICE;
62
+ private timeoutMs = 45_000;
63
+ private abortController: AbortController | null = null;
64
+ private textByContextId = new Map<string, string>();
65
+ private retryConfig: RetryConfig = readRetryConfig({});
66
+ private disposers: Array<() => void> = [];
67
+ private readonly audioFormat: AudioFormat = { encoding: "pcm_s16le", sampleRateHz: SAMPLE_RATE, channels: 1 };
68
+
69
+ async initialize(bus: PipelineBus, config: PluginConfig): Promise<void> {
70
+ this.bus = bus;
71
+ this.apiKey = requireStringConfig(config, "api_key");
72
+ this.model = optionalStringConfig(config, "model") ?? DEFAULT_MODEL;
73
+ this.voiceName = optionalStringConfig(config, "voice_name") ?? DEFAULT_VOICE;
74
+ this.timeoutMs = readPositiveInteger(config["timeout_ms"], 45_000);
75
+ this.retryConfig = readRetryConfig(config);
76
+ assertAudioFormat(this.audioFormat);
77
+
78
+ // Accumulate streaming text deltas; Gemini TTS returns chunked audio for
79
+ // complete text, not true token-by-token low-latency streaming.
80
+ this.disposers.push(
81
+ bus.on("tts.text", (pkt: unknown) => {
82
+ const textPkt = pkt as { text: string; contextId: string };
83
+ const current = this.textByContextId.get(textPkt.contextId) ?? "";
84
+ this.textByContextId.set(textPkt.contextId, current + textPkt.text);
85
+ }),
86
+
87
+ bus.on("tts.done", async (pkt: unknown) => {
88
+ const donePkt = pkt as { text: string; contextId: string };
89
+ const buffered = this.textByContextId.get(donePkt.contextId) ?? "";
90
+ this.textByContextId.delete(donePkt.contextId);
91
+ const text = donePkt.text || buffered;
92
+ if (!text.trim()) {
93
+ this.emitEnd(donePkt.contextId);
94
+ return;
95
+ }
96
+ await this.synthesize(text, donePkt.contextId);
97
+ }),
98
+
99
+ // Listen for TTS interrupts
100
+ bus.on("interrupt.tts", () => {
101
+ this.abortController?.abort();
102
+ this.abortController = null;
103
+ }),
104
+ );
105
+ }
106
+
107
+ private async synthesize(text: string, contextId: string): Promise<void> {
108
+ if (!this.bus) return;
109
+
110
+ this.abortController = new AbortController();
111
+ const signal = this.abortController.signal;
112
+
113
+ for (let attempt = 1; attempt <= this.retryConfig.maxAttempts; attempt += 1) {
114
+ try {
115
+ const audioChunks = await this.synthesizeOnce(text, contextId, signal);
116
+ if (!signal.aborted && audioChunks > 0) {
117
+ this.bus?.push(Route.Main, {
118
+ kind: "tts.end",
119
+ contextId,
120
+ timestampMs: Date.now(),
121
+ });
122
+ }
123
+ if (!signal.aborted && audioChunks === 0) {
124
+ throw new Error("Gemini TTS returned no audio chunks");
125
+ }
126
+ return;
127
+ } catch (err) {
128
+ if (signal.aborted) return;
129
+
130
+ const category = categorizeTtsError(err);
131
+ const recoverable = isRecoverable(category);
132
+ if (!recoverable || attempt >= this.retryConfig.maxAttempts) {
133
+ this.bus?.push(Route.Critical, {
134
+ kind: "tts.error",
135
+ contextId,
136
+ timestampMs: Date.now(),
137
+ component: "tts" as const,
138
+ category,
139
+ cause: err instanceof Error ? err : new Error(String(err)),
140
+ isRecoverable: recoverable,
141
+ });
142
+ return;
143
+ }
144
+
145
+ this.bus?.push(Route.Background, {
146
+ kind: "metric.conversation",
147
+ contextId,
148
+ timestampMs: Date.now(),
149
+ name: "tts.retry",
150
+ value: String(attempt + 1),
151
+ });
152
+ await waitForRetryDelay(attempt, this.retryConfig, signal);
153
+ }
154
+ }
155
+ }
156
+
157
+ private emitEnd(contextId: string): void {
158
+ this.bus?.push(Route.Main, {
159
+ kind: "tts.end",
160
+ contextId,
161
+ timestampMs: Date.now(),
162
+ } satisfies TextToSpeechEndPacket);
163
+ }
164
+
165
+ private async synthesizeOnce(text: string, contextId: string, signal: AbortSignal): Promise<number> {
166
+ // Dynamic import — @google/genai is heavy, only load when used
167
+ const { GoogleGenAI } = await import("@google/genai");
168
+
169
+ const client = new GoogleGenAI({ apiKey: this.apiKey });
170
+
171
+ const response = await withTimeout(
172
+ client.models.generateContent({
173
+ model: this.model,
174
+ contents: [{ parts: [{ text: `Read this aloud in a natural student-support phone voice: ${text}` }] }],
175
+ config: {
176
+ responseModalities: ["AUDIO"],
177
+ speechConfig: {
178
+ voiceConfig: {
179
+ prebuiltVoiceConfig: {
180
+ voiceName: this.voiceName,
181
+ },
182
+ },
183
+ },
184
+ abortSignal: signal,
185
+ },
186
+ }),
187
+ this.timeoutMs,
188
+ signal,
189
+ );
190
+
191
+ let audioChunks = 0;
192
+ const candidate = response.candidates?.[0];
193
+ if (!candidate?.content?.parts) return audioChunks;
194
+
195
+ for (const part of candidate.content.parts) {
196
+ if (signal.aborted) return audioChunks;
197
+
198
+ if (part.inlineData?.data && part.inlineData.mimeType?.startsWith("audio/")) {
199
+ const audioBytes = Buffer.from(part.inlineData.data, "base64");
200
+ const audioUint8 = new Uint8Array(audioBytes);
201
+ assertAudioPayload(this.audioFormat, audioUint8);
202
+
203
+ this.bus?.push(Route.Main, {
204
+ kind: "tts.audio",
205
+ contextId,
206
+ timestampMs: Date.now(),
207
+ audio: audioUint8,
208
+ sampleRateHz: SAMPLE_RATE,
209
+ });
210
+ audioChunks++;
211
+ }
212
+ }
213
+
214
+ return audioChunks;
215
+ }
216
+
217
+ /** Flush/cancel current synthesis (called on interrupt). */
218
+ flush(): void {
219
+ this.abortController?.abort();
220
+ this.abortController = null;
221
+ }
222
+
223
+ async close(): Promise<void> {
224
+ this.abortController?.abort();
225
+ for (const dispose of this.disposers.splice(0)) dispose();
226
+ this.textByContextId.clear();
227
+ this.bus = null;
228
+ }
229
+ }
230
+
231
+ async function withTimeout<T>(promise: Promise<T>, timeoutMs: number, signal: AbortSignal): Promise<T> {
232
+ return await new Promise<T>((resolve, reject) => {
233
+ if (signal.aborted) {
234
+ reject(new Error("Gemini TTS aborted"));
235
+ return;
236
+ }
237
+
238
+ const timeout = setTimeout(() => {
239
+ reject(new Error(`Gemini TTS request timeout after ${String(timeoutMs)}ms`));
240
+ }, timeoutMs);
241
+ const onAbort = (): void => {
242
+ clearTimeout(timeout);
243
+ reject(new Error("Gemini TTS aborted"));
244
+ };
245
+
246
+ signal.addEventListener("abort", onAbort, { once: true });
247
+ promise.then(
248
+ (value) => {
249
+ clearTimeout(timeout);
250
+ signal.removeEventListener("abort", onAbort);
251
+ resolve(value);
252
+ },
253
+ (err: unknown) => {
254
+ clearTimeout(timeout);
255
+ signal.removeEventListener("abort", onAbort);
256
+ reject(err);
257
+ },
258
+ );
259
+ });
260
+ }
261
+
262
+ function readPositiveInteger(value: unknown, fallback: number): number {
263
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
264
+ const integer = Math.floor(value);
265
+ return integer > 0 ? integer : fallback;
266
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "lib": ["ES2022"],
7
+ "strict": true,
8
+ "noUncheckedIndexedAccess": true,
9
+ "noImplicitReturns": true,
10
+ "declaration": true,
11
+ "declarationMap": true,
12
+ "sourceMap": true,
13
+ "outDir": "./dist",
14
+ "rootDir": "./src",
15
+ "esModuleInterop": true,
16
+ "skipLibCheck": true,
17
+ "forceConsistentCasingInFileNames": true
18
+ },
19
+ "include": ["src/**/*.ts"],
20
+ "exclude": ["node_modules", "dist"]
21
+ }