-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtts.ts
More file actions
2374 lines (2073 loc) · 76.2 KB
/
tts.ts
File metadata and controls
2374 lines (2073 loc) · 76.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* TTS (Text-to-Speech) Plugin for OpenCode
*
* Reads the final answer aloud when the agent finishes.
* Supports multiple TTS engines:
* - coqui: Coqui TTS - supports multiple models (bark, xtts_v2, tortoise, etc.)
* - chatterbox: High-quality neural TTS (auto-installed in virtualenv)
* - os: Native OS TTS (macOS `say` command)
*
* Toggle TTS on/off:
* /tts - toggle
* /tts on - enable (short mode)
* /tts off - disable
* /tts short - short mode (task summary only)
* /tts long - long mode (full response)
*
* Short mode: "Task completed in [directory]: [short summary]"
* Long mode: Full assistant response spoken
*
* Configure in ~/.config/opencode/tts.json:
* { "enabled": true, "mode": "short", "engine": "coqui", "coqui": { "model": "bark" } }
*
* Or set environment variables:
* TTS_DISABLED=1 - disable TTS
* TTS_ENGINE=coqui - use Coqui TTS
* TTS_ENGINE=os - use OS TTS
*/
import type { Plugin } from "@opencode-ai/plugin"
import { exec, spawn } from "child_process"
import { promisify } from "util"
import { readFile, writeFile, access, unlink, mkdir, open, readdir, appendFile } from "fs/promises"
import { join } from "path"
import { homedir, tmpdir, platform } from "os"
import * as net from "net"
// Lazy Sentry helper — reports errors without crashing if @sentry/node is unavailable
async function reportError(err: unknown, context?: Record<string, string>): Promise<void> {
try {
const Sentry = await import("@sentry/node")
if (!Sentry.isInitialized()) return
Sentry.captureException(err, context ? { tags: context } : undefined)
} catch {}
}
const execAsync = promisify(exec)
// Debug logging — writes to opencode-helpers/tts.log.
// Never write to stdout/stderr — it corrupts the OpenCode TUI.
const TTS_LOG_PATH = join(homedir(), ".config", "opencode", "opencode-helpers", "tts.log")
async function ttsLog(...args: any[]) {
const msg = args.map(a => typeof a === "string" ? a : JSON.stringify(a)).join(" ")
const ts = new Date().toISOString()
try { await appendFile(TTS_LOG_PATH, `[${ts}] [TTS] ${msg}\n`) } catch {}
}
// Maximum characters to read (to avoid very long speeches)
const MAX_SPEECH_LENGTH = 1000
// Track sessions we've already spoken for
const spokenSessions = new Set<string>()
// Config file path for persistent TTS settings
const TTS_CONFIG_PATH = join(homedir(), ".config", "opencode", "tts.json")
// Global playback process tracking
let currentPlaybackProcess: ReturnType<typeof exec> | null = null
/**
* Stop currently playing audio immediately
*/
function stopCurrentPlayback() {
if (currentPlaybackProcess) {
try {
currentPlaybackProcess.kill()
} catch {}
currentPlaybackProcess = null
}
}
// ==================== GLOBAL CONSTANTS ====================
const TTS_STOP_SIGNAL_PATH = join(homedir(), ".config", "opencode", "tts_stop_signal");
// ... (other global constants)
// ==================== STOP SIGNAL FUNCTIONS ====================
/**
* Creates a global stop signal to halt all active TTS operations.
* This is used to interrupt speech immediately when the user commands it.
*/
async function triggerGlobalStop(): Promise<void> {
try {
const content = JSON.stringify({
timestamp: Date.now(),
triggeredBy: process.pid
});
await writeFile(TTS_STOP_SIGNAL_PATH, content);
} catch (e) {
// silent — console.error corrupts the OpenCode TUI
}
}
/**
* Checks if a stop signal has been triggered recently.
* @returns true if TTS should stop
*/
async function shouldStop(): Promise<boolean> {
try {
const content = await readFile(TTS_STOP_SIGNAL_PATH, "utf-8");
const signal = JSON.parse(content);
// Consider the signal active for 2 seconds
return Date.now() - signal.timestamp < 2000;
} catch {
return false;
}
}
/**
* Clears the stop signal.
*/
async function clearStopSignal(): Promise<void> {
try {
await unlink(TTS_STOP_SIGNAL_PATH);
} catch {}
}
/**
* Execute command and track process for cancellation.
* Enhanced to respect global stop signal.
*/
async function execAndTrack(command: string): Promise<void> {
return new Promise((resolve, reject) => {
// If TTS is disabled or stop signal is active, don't start playback
if (process.env.TTS_DISABLED === "1") {
resolve();
return;
}
// Check global stop signal before starting
// We can't use await here easily inside the Promise executor without wrapping
// so we'll just check the env var which is the primary disable mechanism
// For the file-based check, we rely on the caller (playAudioFile)
const proc = exec(command);
currentPlaybackProcess = proc;
// Poll for stop signal while playing
const stopCheckInterval = setInterval(async () => {
if (await shouldStop()) {
if (currentPlaybackProcess === proc) {
try {
proc.kill(); // Kill the process immediately
} catch {}
currentPlaybackProcess = null;
}
clearInterval(stopCheckInterval);
// We resolve successfully because "stopping" is a valid completion state for the user
resolve();
}
}, 100);
proc.on("exit", (code) => {
clearInterval(stopCheckInterval);
if (currentPlaybackProcess === proc) {
currentPlaybackProcess = null;
}
if (code === 0 || code === null) { // null if killed
resolve();
} else {
// If killed by us (signal), treat as success
// But we can't easily distinguish signal kill from error here without more state
// For 'afplay'/'paplay', a kill usually results in a non-zero exit code or null
// We'll treat errors as warnings but resolve to not break the flow
resolve();
}
});
proc.on("error", (err) => {
clearInterval(stopCheckInterval);
if (currentPlaybackProcess === proc) {
currentPlaybackProcess = null;
}
// Log error but resolve to prevent crashing the plugin
// silent — console.error corrupts the OpenCode TUI
resolve();
});
});
}
/**
* Play audio file using platform-specific command
*/
async function playAudioFile(audioPath: string): Promise<void> {
// Check if TTS is enabled before playing
const enabled = await isEnabled();
if (!enabled) return;
// Check for global stop signal
if (await shouldStop()) return;
if (platform() === "darwin") {
await execAndTrack(`afplay "${audioPath}"`);
} else {
try {
await execAndTrack(`paplay "${audioPath}"`);
} catch {
await execAndTrack(`aplay "${audioPath}"`);
}
}
}
const SPEECH_LOCK_PATH = join(homedir(), ".config", "opencode", "speech.lock")
const SPEECH_LOCK_TIMEOUT = 300000 // Max speech duration (5 minutes)
const SPEECH_LOCK_HEARTBEAT_INTERVAL = 10000 // Refresh lock timestamp every 10s
const SPEECH_QUEUE_DIR = join(homedir(), ".config", "opencode", "speech-queue")
// Unique identifier for this process instance
const PROCESS_ID = `${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`
// Reflection coordination - wait for reflection verdict before speaking
const REFLECTION_VERDICT_WAIT_MS = 10_000 // Max wait time for reflection verdict
const REFLECTION_POLL_INTERVAL_MS = 500 // Poll interval for verdict file
// TTS Engine types
type TTSEngine = "coqui" | "chatterbox" | "os"
// Coqui TTS model types
// - bark: Multilingual neural TTS (slower, higher quality)
// - xtts_v2: XTTS v2 with voice cloning support
// - tortoise: Very high quality but slow
// - vits: Fast VITS model (LJSpeech single speaker)
// - vctk_vits: VCTK multi-speaker VITS (supports speaker selection, e.g., p226)
// - jenny: Jenny voice model
type CoquiModel = "bark" | "xtts_v2" | "tortoise" | "vits" | "vctk_vits" | "jenny"
type TTSMode = "short" | "long"
interface TTSConfig {
enabled?: boolean
mode?: TTSMode
engine?: TTSEngine
// OS TTS options (macOS/Linux)
os?: {
voice?: string // Voice name (e.g., "Samantha", "Alex"). Run `say -v ?` on macOS to list voices
rate?: number // Speaking rate in words per minute (default: 200)
}
// Coqui TTS options (supports bark, xtts_v2, tortoise, vits, vctk_vits, etc.)
coqui?: {
model?: CoquiModel // Model to use: "vctk_vits" (recommended), "xtts_v2", "vits", etc.
device?: "cuda" | "cpu" | "mps" // GPU, CPU, or Apple Silicon (default: auto-detect)
// XTTS-specific options
voiceRef?: string // Path to reference voice clip for cloning (XTTS)
language?: string // Language code for XTTS (default: "en")
speaker?: string // Speaker name/ID (e.g., "p226" for vctk_vits, "Ana Florence" for xtts)
serverMode?: boolean // Keep model loaded for fast subsequent requests (default: true)
}
// Chatterbox-specific options
chatterbox?: {
device?: "cuda" | "cpu" | "mps" // GPU, CPU, or Apple Silicon (default: auto-detect)
voiceRef?: string // Path to reference voice clip for cloning (REQUIRED for custom voice)
exaggeration?: number // Emotion exaggeration (0.0-1.0)
useTurbo?: boolean // Use Turbo model for 10x faster inference
serverMode?: boolean // Keep model loaded for fast subsequent requests (default: true)
}
// Reflection coordination options
reflection?: {
waitForVerdict?: boolean // Wait for reflection verdict before speaking (default: true)
maxWaitMs?: number // Max wait time for verdict (default: 10000ms)
requireVerdict?: boolean // Require verdict before speaking (default: true)
}
}
// ==================== HELPERS BASE DIRECTORY ====================
const HELPERS_DIR = join(homedir(), ".config", "opencode", "opencode-helpers")
// ==================== CHATTERBOX ====================
const CHATTERBOX_DIR = join(HELPERS_DIR, "chatterbox")
const CHATTERBOX_VENV = join(CHATTERBOX_DIR, "venv")
const CHATTERBOX_SCRIPT = join(CHATTERBOX_DIR, "tts.py")
const CHATTERBOX_SERVER_SCRIPT = join(CHATTERBOX_DIR, "tts_server.py")
const CHATTERBOX_SOCKET = join(CHATTERBOX_DIR, "tts.sock")
const CHATTERBOX_LOCK = join(CHATTERBOX_DIR, "server.lock")
const CHATTERBOX_PID = join(CHATTERBOX_DIR, "server.pid")
let chatterboxInstalled: boolean | null = null
let chatterboxSetupAttempted = false
// ==================== COQUI TTS ====================
const COQUI_DIR = join(HELPERS_DIR, "coqui")
const COQUI_VENV = join(COQUI_DIR, "venv")
const COQUI_SCRIPT = join(COQUI_DIR, "tts.py")
const COQUI_SERVER_SCRIPT = join(COQUI_DIR, "tts_server.py")
const COQUI_SOCKET = join(COQUI_DIR, "tts.sock")
const COQUI_LOCK = join(COQUI_DIR, "server.lock")
const COQUI_PID = join(COQUI_DIR, "server.pid")
let coquiInstalled: boolean | null = null
let coquiSetupAttempted = false
// ==================== REFLECTION COORDINATION ====================
interface ReflectionVerdict {
sessionId: string
complete: boolean
severity: string
timestamp: number
}
interface ReflectionMetrics {
missingVerdictCount: number
lastMissingAt?: number
}
async function updateReflectionMetrics(directory: string): Promise<ReflectionMetrics> {
const reflectionDir = join(directory, ".reflection")
const metricsPath = join(reflectionDir, "reflection_metrics.json")
let metrics: ReflectionMetrics = { missingVerdictCount: 0 }
try {
const content = await readFile(metricsPath, "utf-8")
metrics = JSON.parse(content) as ReflectionMetrics
} catch {
// No existing metrics
}
metrics.missingVerdictCount = (metrics.missingVerdictCount || 0) + 1
metrics.lastMissingAt = Date.now()
try {
await mkdir(reflectionDir, { recursive: true })
await writeFile(metricsPath, JSON.stringify(metrics, null, 2))
} catch {}
return metrics
}
/**
* Wait for and read the reflection verdict for a session.
* Returns the verdict if found within timeout, or null if no verdict.
*
* @param directory - Workspace directory (contains .reflection/)
* @param sessionId - Session ID to check verdict for
* @param maxWaitMs - Maximum time to wait for verdict
* @param debugLog - Debug logging function
*/
async function waitForReflectionVerdict(
directory: string,
sessionId: string,
maxWaitMs: number,
debugLog: (msg: string) => Promise<void>
): Promise<ReflectionVerdict | null> {
const reflectionDir = join(directory, ".reflection")
const signalPath = join(reflectionDir, `verdict_${sessionId.slice(0, 8)}.json`)
const startTime = Date.now()
await debugLog(`Waiting for reflection verdict: ${signalPath}`)
while (Date.now() - startTime < maxWaitMs) {
try {
const content = await readFile(signalPath, "utf-8")
const verdict = JSON.parse(content) as ReflectionVerdict
// Check if this verdict is recent (within the last 30 seconds)
// This prevents using stale verdicts from previous sessions
const age = Date.now() - verdict.timestamp
if (age < 30_000) {
await debugLog(`Found verdict: complete=${verdict.complete}, severity=${verdict.severity}, age=${age}ms`)
return verdict
} else {
await debugLog(`Found stale verdict (age=${age}ms), ignoring`)
}
} catch {
// File doesn't exist yet, keep waiting
}
await new Promise(resolve => setTimeout(resolve, REFLECTION_POLL_INTERVAL_MS))
}
await debugLog(`No reflection verdict found within ${maxWaitMs}ms`)
return null
}
/**
* Load TTS configuration from file
*/
async function loadConfig(): Promise<TTSConfig> {
try {
const content = await readFile(TTS_CONFIG_PATH, "utf-8")
return JSON.parse(content)
} catch {
return {
enabled: true,
mode: "short",
engine: "coqui",
coqui: {
model: "vctk_vits",
device: "mps",
speaker: "p226",
serverMode: true
},
os: {
voice: "Samantha",
rate: 200
}
}
}
}
/**
* Save TTS configuration to file
*/
async function saveConfig(config: TTSConfig): Promise<void> {
try {
// Ensure config directory exists
const configDir = join(homedir(), ".config", "opencode")
await mkdir(configDir, { recursive: true })
await writeFile(TTS_CONFIG_PATH, JSON.stringify(config, null, 2))
} catch (e) {
// silent — console.error corrupts the OpenCode TUI
}
}
/**
* Toggle TTS enabled state
* @returns new enabled state
*/
async function toggleTTS(): Promise<boolean> {
const config = await loadConfig()
config.enabled = !config.enabled
await saveConfig(config)
return config.enabled
}
/**
* Set TTS enabled state
* @param enabled - whether to enable TTS
*/
async function setTTSEnabled(enabled: boolean): Promise<void> {
const config = await loadConfig()
config.enabled = enabled
await saveConfig(config)
// If disabled, stop current playback immediately
if (!enabled) {
stopCurrentPlayback()
}
}
/**
* Check if TTS is enabled
*/
async function isEnabled(): Promise<boolean> {
if (process.env.TTS_DISABLED === "1") return false
const config = await loadConfig()
return config.enabled !== false
}
async function getMode(): Promise<TTSMode> {
const config = await loadConfig()
return config.mode || "short"
}
async function setMode(mode: TTSMode): Promise<void> {
const config = await loadConfig()
config.mode = mode
await saveConfig(config)
}
/**
* Get the TTS engine to use
*/
async function getEngine(): Promise<TTSEngine> {
if (process.env.TTS_ENGINE === "os") return "os"
if (process.env.TTS_ENGINE === "coqui") return "coqui"
if (process.env.TTS_ENGINE === "chatterbox") return "chatterbox"
const config = await loadConfig()
return config.engine || "coqui"
}
// ==================== SPEECH LOCK (Cross-Process Queue) ====================
/**
* Speech queue implementation using file-based locking.
* Ensures multiple OpenCode sessions speak one at a time in FIFO order.
*
* How it works:
* 1. Each speech request creates a ticket file in SPEECH_QUEUE_DIR with timestamp
* 2. Process waits until its ticket is the oldest (first in queue)
* 3. Process acquires the lock, speaks, then releases lock and removes ticket
* 4. Stale tickets (older than SPEECH_LOCK_TIMEOUT) are auto-cleaned
*/
interface SpeechTicket {
processId: string
timestamp: number
sessionId: string
}
interface SpeechLock {
processId: string
ticketId: string
timestamp: number
}
async function ensureQueueDir(): Promise<void> {
try {
await mkdir(SPEECH_QUEUE_DIR, { recursive: true })
} catch {}
}
async function createSpeechTicket(sessionId: string): Promise<string> {
await ensureQueueDir()
const timestamp = Date.now()
const ticketId = `${timestamp}-${PROCESS_ID}-${sessionId}`
const ticketPath = join(SPEECH_QUEUE_DIR, `${ticketId}.ticket`)
const ticket: SpeechTicket = {
processId: PROCESS_ID,
timestamp,
sessionId
}
await writeFile(ticketPath, JSON.stringify(ticket))
return ticketId
}
async function removeSpeechTicket(ticketId: string): Promise<void> {
const ticketPath = join(SPEECH_QUEUE_DIR, `${ticketId}.ticket`)
await unlink(ticketPath).catch(() => {})
}
async function getQueuedTickets(): Promise<{ id: string; ticket: SpeechTicket }[]> {
await ensureQueueDir()
// readdir is now statically imported
try {
const files = await readdir(SPEECH_QUEUE_DIR)
const tickets: { id: string; ticket: SpeechTicket }[] = []
for (const file of files) {
if (!file.endsWith(".ticket")) continue
const ticketId = file.replace(".ticket", "")
const ticketPath = join(SPEECH_QUEUE_DIR, file)
try {
const content = await readFile(ticketPath, "utf-8")
const ticket = JSON.parse(content) as SpeechTicket
// Clean up stale tickets (older than timeout)
if (Date.now() - ticket.timestamp > SPEECH_LOCK_TIMEOUT) {
await unlink(ticketPath).catch(() => {})
continue
}
tickets.push({ id: ticketId, ticket })
} catch {
// Invalid ticket, remove it
await unlink(ticketPath).catch(() => {})
}
}
// Sort by timestamp (FIFO)
tickets.sort((a, b) => a.ticket.timestamp - b.ticket.timestamp)
return tickets
} catch {
return []
}
}
function isProcessAlive(processId: string): boolean {
const pid = Number(processId.split("-")[0])
if (!Number.isFinite(pid) || pid <= 0) return false
try {
process.kill(pid, 0)
return true
} catch {
return false
}
}
async function isMyTurn(ticketId: string): Promise<boolean> {
const tickets = await getQueuedTickets()
if (tickets.length === 0) return false
return tickets[0].id === ticketId
}
async function acquireSpeechLock(ticketId: string): Promise<boolean> {
// Only acquire lock if it's our turn in the queue
if (!(await isMyTurn(ticketId))) {
return false
}
const lockContent = JSON.stringify({
processId: PROCESS_ID,
ticketId,
timestamp: Date.now()
})
try {
// open is now statically imported
const handle = await open(SPEECH_LOCK_PATH, "wx")
await handle.writeFile(lockContent)
await handle.close()
return true
} catch (e: any) {
if (e.code === "EEXIST") {
// Lock exists - check if it's stale
try {
const content = await readFile(SPEECH_LOCK_PATH, "utf-8")
const lock = JSON.parse(content) as SpeechLock
const lockProcessId = typeof lock.processId === "string" ? lock.processId : null
if (lockProcessId && !isProcessAlive(lockProcessId)) {
await unlink(SPEECH_LOCK_PATH).catch(() => {})
return acquireSpeechLock(ticketId)
}
if (Date.now() - lock.timestamp > SPEECH_LOCK_TIMEOUT) {
// Stale lock, remove it and try again
await unlink(SPEECH_LOCK_PATH).catch(() => {})
return acquireSpeechLock(ticketId)
}
} catch {
// Corrupted lock file, remove and retry
await unlink(SPEECH_LOCK_PATH).catch(() => {})
return acquireSpeechLock(ticketId)
}
}
return false
}
}
async function releaseSpeechLock(ticketId: string): Promise<void> {
// Only release if we own the lock
try {
const content = await readFile(SPEECH_LOCK_PATH, "utf-8")
const lock = JSON.parse(content) as SpeechLock
if (lock.processId === PROCESS_ID && lock.ticketId === ticketId) {
await unlink(SPEECH_LOCK_PATH).catch(() => {})
}
} catch {
// Lock doesn't exist or is corrupted, nothing to release
}
}
async function waitForSpeechTurn(ticketId: string, timeoutMs: number = 180000): Promise<boolean> {
const startTime = Date.now()
while (Date.now() - startTime < timeoutMs) {
// First wait for our turn in the queue
if (await isMyTurn(ticketId)) {
// Then try to acquire the lock
if (await acquireSpeechLock(ticketId)) {
return true
}
}
// Wait before retrying
await new Promise(r => setTimeout(r, 500))
}
// Timeout - remove our ticket and give up
await removeSpeechTicket(ticketId)
return false
}
// ==================== UTILITY FUNCTIONS ====================
async function findPython311(): Promise<string | null> {
const candidates = ["python3.11", "/opt/homebrew/bin/python3.11", "/usr/local/bin/python3.11"]
for (const py of candidates) {
try {
const { stdout } = await execAsync(`${py} --version 2>/dev/null`)
if (stdout.includes("3.11")) return py
} catch {
// Try next
}
}
return null
}
async function findPython3(): Promise<string | null> {
// Coqui TTS requires Python 3.9-3.11 (not 3.12+)
const candidates = [
"python3.11", "python3.10", "python3.9",
"/opt/homebrew/bin/python3.11", "/opt/homebrew/bin/python3.10", "/opt/homebrew/bin/python3.9",
"/usr/local/bin/python3.11", "/usr/local/bin/python3.10", "/usr/local/bin/python3.9"
]
for (const py of candidates) {
try {
const { stdout } = await execAsync(`${py} --version 2>/dev/null`)
if (stdout.includes("Python 3.11") || stdout.includes("Python 3.10") || stdout.includes("Python 3.9")) {
return py
}
} catch {
// Try next
}
}
return null
}
// ==================== CHATTERBOX SETUP ====================
async function setupChatterbox(): Promise<boolean> {
if (chatterboxSetupAttempted) return chatterboxInstalled === true
chatterboxSetupAttempted = true
const python = await findPython311()
if (!python) return false
try {
await mkdir(CHATTERBOX_DIR, { recursive: true })
const venvPython = join(CHATTERBOX_VENV, "bin", "python")
try {
await access(venvPython)
const { stdout } = await execAsync(`"${venvPython}" -c "import chatterbox; print('ok')"`, { timeout: 10000 })
if (stdout.includes("ok")) {
await ensureChatterboxScript()
chatterboxInstalled = true
return true
}
} catch {
// Need to create/setup venv
}
await execAsync(`"${python}" -m venv "${CHATTERBOX_VENV}"`, { timeout: 60000 })
const pip = join(CHATTERBOX_VENV, "bin", "pip")
await execAsync(`"${pip}" install --upgrade pip`, { timeout: 120000 })
await execAsync(`"${pip}" install chatterbox-tts`, { timeout: 600000 })
await ensureChatterboxScript()
chatterboxInstalled = true
return true
} catch (e: any) {
reportError(e, { plugin: "tts", op: "chatterbox-setup" })
chatterboxInstalled = false
return false
}
}
async function ensureChatterboxScript(): Promise<void> {
const script = `#!/usr/bin/env python3
"""Chatterbox TTS helper script for OpenCode."""
import sys
import argparse
def main():
parser = argparse.ArgumentParser(description="Chatterbox TTS")
parser.add_argument("text", help="Text to synthesize")
parser.add_argument("--output", "-o", required=True, help="Output WAV file")
parser.add_argument("--device", default="cuda", choices=["cuda", "mps", "cpu"])
parser.add_argument("--voice", help="Reference voice audio path")
parser.add_argument("--exaggeration", type=float, default=0.5)
parser.add_argument("--turbo", action="store_true", help="Use Turbo model")
args = parser.parse_args()
try:
import torch
import torchaudio as ta
device = args.device
if device == "cuda" and not torch.cuda.is_available():
device = "mps" if torch.backends.mps.is_available() else "cpu"
elif device == "mps" and not torch.backends.mps.is_available():
device = "cpu"
if args.turbo:
from chatterbox.tts_turbo import ChatterboxTurboTTS
model = ChatterboxTurboTTS.from_pretrained(device=device)
else:
from chatterbox.tts import ChatterboxTTS
model = ChatterboxTTS.from_pretrained(device=device)
if args.voice:
wav = model.generate(args.text, audio_prompt_path=args.voice, exaggeration=args.exaggeration)
else:
wav = model.generate(args.text, exaggeration=args.exaggeration)
ta.save(args.output, wav, model.sr)
except Exception as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
`
await writeFile(CHATTERBOX_SCRIPT, script, { mode: 0o755 })
}
async function ensureChatterboxServerScript(): Promise<void> {
const script = `#!/usr/bin/env python3
"""Chatterbox TTS Server for OpenCode."""
import sys
import os
import json
import socket
import argparse
def main():
parser = argparse.ArgumentParser(description="Chatterbox TTS Server")
parser.add_argument("--socket", required=True, help="Unix socket path")
parser.add_argument("--device", default="cuda", choices=["cuda", "cpu", "mps"])
parser.add_argument("--turbo", action="store_true", help="Use Turbo model")
parser.add_argument("--voice", help="Default reference voice audio path")
args = parser.parse_args()
import torch
import torchaudio as ta
device = args.device
if device == "cuda" and not torch.cuda.is_available():
if torch.backends.mps.is_available():
device = "mps"
else:
device = "cpu"
print(f"Loading model on {device}...", file=sys.stderr)
if args.turbo:
from chatterbox.tts_turbo import ChatterboxTurboTTS
model = ChatterboxTurboTTS.from_pretrained(device=device)
else:
from chatterbox.tts import ChatterboxTTS
model = ChatterboxTTS.from_pretrained(device=device)
default_voice = args.voice
if os.path.exists(args.socket):
os.unlink(args.socket)
server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
server.bind(args.socket)
server.listen(1)
os.chmod(args.socket, 0o600)
print(f"TTS server ready on {args.socket}", file=sys.stderr)
sys.stderr.flush()
while True:
try:
conn, _ = server.accept()
data = b""
while True:
chunk = conn.recv(4096)
if not chunk:
break
data += chunk
if b"\\n" in data:
break
request = json.loads(data.decode().strip())
text = request.get("text", "")
output = request.get("output", "/tmp/tts_output.wav")
voice = request.get("voice") or default_voice
exaggeration = request.get("exaggeration", 0.5)
if voice:
wav = model.generate(text, audio_prompt_path=voice, exaggeration=exaggeration)
else:
wav = model.generate(text, exaggeration=exaggeration)
ta.save(output, wav, model.sr)
conn.sendall(json.dumps({"success": True, "output": output}).encode() + b"\\n")
conn.close()
except Exception as e:
try:
conn.sendall(json.dumps({"success": False, "error": str(e)}).encode() + b"\\n")
conn.close()
except:
pass
if __name__ == "__main__":
main()
`
await writeFile(CHATTERBOX_SERVER_SCRIPT, script, { mode: 0o755 })
}
async function isChatterboxServerRunning(): Promise<boolean> {
try {
await access(CHATTERBOX_SOCKET)
// net is now statically imported
return new Promise((resolve) => {
const client = net.createConnection(CHATTERBOX_SOCKET, () => {
client.destroy()
resolve(true)
})
client.on("error", () => resolve(false))
setTimeout(() => {
client.destroy()
resolve(false)
}, 1000)
})
} catch {
return false
}
}
async function acquireChatterboxLock(): Promise<boolean> {
const lockContent = `${process.pid}\n${Date.now()}`
try {
// open is now statically imported
const handle = await open(CHATTERBOX_LOCK, "wx")
await handle.writeFile(lockContent)
await handle.close()
return true
} catch (e: any) {
if (e.code === "EEXIST") {
try {
const content = await readFile(CHATTERBOX_LOCK, "utf-8")
const timestamp = parseInt(content.split("\n")[1] || "0", 10)
if (Date.now() - timestamp > 120000) {
await unlink(CHATTERBOX_LOCK)
return acquireChatterboxLock()
}
} catch {
await unlink(CHATTERBOX_LOCK).catch(() => {})
return acquireChatterboxLock()
}
}
return false
}
}
async function releaseChatterboxLock(): Promise<void> {
await unlink(CHATTERBOX_LOCK).catch(() => {})
}
async function startChatterboxServer(config: TTSConfig): Promise<boolean> {
if (await isChatterboxServerRunning()) {
return true
}
if (!(await acquireChatterboxLock())) {
const startTime = Date.now()
while (Date.now() - startTime < 120000) {
await new Promise(r => setTimeout(r, 1000))
if (await isChatterboxServerRunning()) {
return true
}
}
return false
}
try {
if (await isChatterboxServerRunning()) {
return true
}
await ensureChatterboxServerScript()
const venvPython = join(CHATTERBOX_VENV, "bin", "python")
const opts = config.chatterbox || {}
const device = opts.device || "cuda"
const args = [
CHATTERBOX_SERVER_SCRIPT,
"--socket", CHATTERBOX_SOCKET,
"--device", device,
]
if (opts.useTurbo) {
args.push("--turbo")
}
if (opts.voiceRef) {
args.push("--voice", opts.voiceRef)
}
try {
await unlink(CHATTERBOX_SOCKET)
} catch {}
const serverProcess = spawn(venvPython, args, {
stdio: ["ignore", "pipe", "pipe"],
detached: true,
})
if (serverProcess.pid) {
await writeFile(CHATTERBOX_PID, String(serverProcess.pid))
}
serverProcess.unref()
const startTime = Date.now()
while (Date.now() - startTime < 120000) {
if (await isChatterboxServerRunning()) {
return true
}
await new Promise(r => setTimeout(r, 500))
}
return false
} finally {
await releaseChatterboxLock()
}
}