-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.ts
More file actions
1103 lines (972 loc) · 36 KB
/
plugin.ts
File metadata and controls
1103 lines (972 loc) · 36 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
import type { Plugin, PluginInput } from "@opencode-ai/plugin"
import { homedir } from "os"
import { join, dirname } from "path"
import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync } from "fs"
import { execSync } from "child_process"
import { fileURLToPath } from "url"
import { loadThemes, getThemeNames, getTheme, reloadThemes, resolveSoundPath, type SoundTheme } from "./lib/themes.js"
import { playSound as playSoundLib, isDebugMode, isTestMode } from "./lib/sound-player.js"
import {
PLUGIN_DIR,
USER_THEMES_DIR,
BUNDLED_THEMES_DIR,
} from "./lib/paths.js"
// =============================================================================
// CONFIGURATION
// =============================================================================
// State directory for instance tracking and TTY profiles
const STATE_DIR = join(homedir(), ".config/opencode/.opencode-sfx")
const INSTANCE_ID = process.pid.toString()
// Environment variable for explicit profile selection
const ENV_PROFILE = "OCSFX_THEME"
// Per-directory profile file (optional, for per-project explicit config)
const PROFILE_FILE = ".ocsfx"
// TTY-to-profile mapping stored in home directory
const TTY_PROFILES_FILE = join(STATE_DIR, "tty-profiles.json")
// =============================================================================
// WINDOW FOCUS DETECTION & TMUX ALERT
// =============================================================================
// Cached window info captured at startup
let cachedWeztermPaneId: number | null = null
let cachedTmuxWindowName: string | null = null
let hasAlert = false
const ALERT_PREFIX = process.env.OCSFX_ALERT ?? "!! "
// Capture our window info at startup (call this once during plugin init)
function captureWindowInfo(): void {
// Capture WezTerm pane ID from environment
if (process.env.WEZTERM_PANE !== undefined) {
cachedWeztermPaneId = parseInt(process.env.WEZTERM_PANE, 10)
if (isNaN(cachedWeztermPaneId)) cachedWeztermPaneId = null
}
// Capture tmux window name
if (process.env.TMUX && process.env.TMUX_PANE) {
try {
cachedTmuxWindowName = execSync(
`tmux display-message -t "${process.env.TMUX_PANE}" -p '#{window_name}'`,
{ encoding: "utf-8", timeout: 1000 }
).trim()
} catch {
// Ignore errors
}
}
}
// Add alert prefix to tmux window name
function setTmuxAlert(): void {
if (!process.env.TMUX || !process.env.TMUX_PANE || hasAlert) return
try {
const currentName = execSync(
`tmux display-message -t "${process.env.TMUX_PANE}" -p '#{window_name}'`,
{ encoding: "utf-8", timeout: 1000 }
).trim()
// Don't add if already has alert prefix
if (currentName.startsWith(ALERT_PREFIX)) return
execSync(
`tmux rename-window -t "${process.env.TMUX_PANE}" "${ALERT_PREFIX}${currentName}"`,
{ encoding: "utf-8", timeout: 1000 }
)
hasAlert = true
} catch {
// Ignore errors
}
}
// Remove alert prefix from tmux window name
function clearTmuxAlert(): void {
if (!process.env.TMUX || !process.env.TMUX_PANE || !hasAlert) return
try {
const currentName = execSync(
`tmux display-message -t "${process.env.TMUX_PANE}" -p '#{window_name}'`,
{ encoding: "utf-8", timeout: 1000 }
).trim()
// Only remove if it has our alert prefix
if (currentName.startsWith(ALERT_PREFIX)) {
const originalName = currentName.slice(ALERT_PREFIX.length)
execSync(
`tmux rename-window -t "${process.env.TMUX_PANE}" "${originalName}"`,
{ encoding: "utf-8", timeout: 1000 }
)
}
hasAlert = false
} catch {
// Ignore errors
}
}
// Check if this specific pane/window is active
// Returns true if user is looking at this instance, false if they should be notified
function isPaneActive(): boolean {
// If we have a WezTerm pane ID, use focused_pane_id from wezterm cli
if (cachedWeztermPaneId !== null) {
// Stage 1: Is WezTerm even the frontmost app?
if (!isWezTermFrontmost()) {
return false
}
// Stage 2: Is our WezTerm pane the focused one?
if (!isOurWezTermPaneFocused()) {
return false
}
// Stage 3: If inside tmux, check if our tmux pane is active
if (process.env.TMUX) {
return isTmuxPaneActive()
}
// Our WezTerm pane is focused and no tmux — user is looking at us
return true
}
// Fallback: just check tmux if available
if (process.env.TMUX) {
return isTmuxPaneActive()
}
// Last resort: check if any terminal is focused
return isTerminalAppFocused()
}
// Check if WezTerm is the frontmost application
function isWezTermFrontmost(): boolean {
try {
const frontApp = execSync(
`osascript -e 'tell application "System Events" to get name of first application process whose frontmost is true'`,
{ encoding: "utf-8", timeout: 1000 }
).trim()
return frontApp.toLowerCase().includes("wezterm")
} catch {
return true // Assume frontmost on error
}
}
// Check if our WezTerm pane is the focused pane via wezterm cli list-clients
function isOurWezTermPaneFocused(): boolean {
try {
const clientInfo = execSync(`wezterm cli list-clients --format json`, {
encoding: "utf-8",
timeout: 1000,
})
const clients = JSON.parse(clientInfo)
if (clients.length === 0) return true // No client info, assume focused
// Check if any client has our pane focused
return clients.some(
(c: any) => c.focused_pane_id === cachedWeztermPaneId
)
} catch {
return true // Assume focused on error
}
}
// Check if this specific tmux pane is active
// Must check: session is attached AND window is active AND pane is active
function isTmuxPaneActive(): boolean {
try {
const tmuxPane = process.env.TMUX_PANE
if (!tmuxPane) return true // No pane ID, assume active
// Query the specific pane using its ID
const result = execSync(
`tmux display-message -t "${tmuxPane}" -p '#{session_attached} #{window_active} #{pane_active}'`,
{ encoding: "utf-8", timeout: 1000 }
).trim()
const [sessionAttached, windowActive, paneActive] = result.split(" ")
// All three must be true for this pane to be "active" (user looking at it)
return sessionAttached === "1" && windowActive === "1" && paneActive === "1"
} catch {
return true // Assume active on error
}
}
// Terminal app names to detect (fallback when not in wezterm)
const TERMINAL_APPS = [
"wezterm-gui",
"WezTerm",
"Terminal",
"iTerm2",
"iTerm",
"Alacritty",
"kitty",
"Ghostty",
"Hyper",
]
// Check if a terminal app is currently focused (fallback)
function isTerminalAppFocused(): boolean {
try {
const result = execSync(
`osascript -e 'tell application "System Events" to get name of first application process whose frontmost is true'`,
{ encoding: "utf-8", timeout: 1000 }
).trim()
return TERMINAL_APPS.some((app) =>
result.toLowerCase().includes(app.toLowerCase())
)
} catch {
return true
}
}
// Current theme info for logging (set during plugin init)
let currentThemeForLogging: string = ""
// Fire-and-forget sound playback (non-blocking)
// Only plays if this pane is NOT active, also sets tmux alert
function playSound(soundPath: string, event?: string, reason?: string): void {
if (isPaneActive()) {
return // Don't play sound if this pane is active
}
// Set tmux alert when playing sound
setTmuxAlert()
playSoundLib(soundPath, {
theme: currentThemeForLogging,
event,
reason,
})
}
// Always play sound regardless of focus
function playSoundAlways(soundPath: string, event?: string, reason?: string): void {
playSoundLib(soundPath, {
theme: currentThemeForLogging,
event,
reason,
force: true,
})
}
// =============================================================================
// TTY IDENTIFICATION
// =============================================================================
// Get a unique identifier for the current terminal session
// Combines multiple identifiers to be unique per terminal instance
function getTtyIdentifier(): string | null {
const parts: string[] = []
// TERM_SESSION_ID - UUID set by macOS Terminal.app and iTerm2
// This is unique per terminal tab/session and doesn't get recycled
if (process.env.TERM_SESSION_ID) {
parts.push(`term:${process.env.TERM_SESSION_ID}`)
}
// iTerm2 session ID (also a UUID)
if (process.env.ITERM_SESSION_ID) {
parts.push(`iterm:${process.env.ITERM_SESSION_ID}`)
}
// TMUX - format is "socket_path,server_pid,window_index"
// Combined with TMUX_PANE and server start time, this uniquely identifies a tmux pane
// The server_pid + start_time ensures uniqueness across tmux server restarts
if (process.env.TMUX && process.env.TMUX_PANE) {
// Extract server PID from TMUX
const tmuxParts = process.env.TMUX.split(",")
const serverPid = tmuxParts.length >= 2 ? tmuxParts[1] : "unknown"
// Get tmux server start time for extra uniqueness
let startTime = ""
try {
startTime = execSync("tmux display-message -p '#{start_time}'", {
encoding: "utf-8",
timeout: 1000,
}).trim()
} catch {
// Ignore errors, PID alone is usually sufficient
}
if (startTime) {
parts.push(`tmux:${serverPid}:${startTime}:${process.env.TMUX_PANE}`)
} else {
parts.push(`tmux:${serverPid}:${process.env.TMUX_PANE}`)
}
}
// WEZTERM_PANE - unique within WezTerm process
// Combine with WEZTERM_UNIX_SOCKET if available for uniqueness across restarts
if (process.env.WEZTERM_PANE) {
const socket = process.env.WEZTERM_UNIX_SOCKET || ""
// Extract a unique part from socket path (contains pid or timestamp)
const socketId = socket.split("/").pop() || ""
parts.push(`wezterm:${socketId}:${process.env.WEZTERM_PANE}`)
}
// If we have any identifiers, join them
if (parts.length > 0) {
return parts.join("+")
}
// Fallback: try tty device path (less reliable, gets recycled)
try {
if (process.stdin.isTTY) {
const ttyPath = execSync("tty", {
encoding: "utf-8",
timeout: 1000,
}).trim()
if (ttyPath && ttyPath !== "not a tty") {
return `tty:${ttyPath}`
}
}
} catch {
// Ignore errors
}
// Last resort fallbacks
if (process.env.WINDOWID) {
return `x11:${process.env.WINDOWID}`
}
return null
}
// =============================================================================
// TTY PROFILE MANAGEMENT
// =============================================================================
interface TtyProfiles {
profiles: Record<string, string> // tty identifier -> profile name
}
function ensureStateDir(): void {
if (!existsSync(STATE_DIR)) {
mkdirSync(STATE_DIR, { recursive: true })
}
}
function loadTtyProfiles(): TtyProfiles {
ensureStateDir()
if (existsSync(TTY_PROFILES_FILE)) {
try {
return JSON.parse(readFileSync(TTY_PROFILES_FILE, "utf-8"))
} catch {
return { profiles: {} }
}
}
return { profiles: {} }
}
function saveTtyProfiles(data: TtyProfiles): void {
ensureStateDir()
writeFileSync(TTY_PROFILES_FILE, JSON.stringify(data, null, 2))
}
function getTtyProfile(tty: string): string | null {
const data = loadTtyProfiles()
return data.profiles[tty] || null
}
function setTtyProfile(tty: string, profile: string): void {
const data = loadTtyProfiles()
data.profiles[tty] = profile
saveTtyProfiles(data)
}
// Read optional per-directory .ocsfx (just a profile name, no JSON needed)
function readDirectoryProfile(): string | null {
const profilePath = join(process.cwd(), PROFILE_FILE)
if (existsSync(profilePath)) {
try {
return readFileSync(profilePath, "utf-8").trim()
} catch {
return null
}
}
return null
}
// =============================================================================
// INSTANCE STATE MANAGEMENT
// =============================================================================
interface InstanceState {
instances: Record<string, { theme: string; startedAt: string }>
}
const INSTANCES_FILE = join(STATE_DIR, "instances.json")
function loadState(): InstanceState {
ensureStateDir()
if (existsSync(INSTANCES_FILE)) {
try {
return JSON.parse(readFileSync(INSTANCES_FILE, "utf-8"))
} catch {
return { instances: {} }
}
}
return { instances: {} }
}
function saveState(state: InstanceState): void {
ensureStateDir()
writeFileSync(INSTANCES_FILE, JSON.stringify(state, null, 2))
}
function cleanupStaleInstances(state: InstanceState): void {
// Remove instances older than 24 hours (likely stale)
const now = Date.now()
const maxAge = 24 * 60 * 60 * 1000
for (const [pid, info] of Object.entries(state.instances)) {
const startedAt = new Date(info.startedAt).getTime()
if (now - startedAt > maxAge) {
delete state.instances[pid]
}
}
}
function hasUserThemes(): boolean {
try {
return existsSync(USER_THEMES_DIR) && readdirSync(USER_THEMES_DIR).length > 0
} catch {
return false
}
}
function getAvailableThemes(state: InstanceState): string[] {
const usedThemes = new Set(Object.values(state.instances).map((i) => i.theme))
const allThemes = getThemeNames()
// Exclude "test" and "default" from random rotation when user has custom themes
// (default is the fallback for users without custom themes; test is for development)
const userHasThemes = hasUserThemes()
const candidateThemes = userHasThemes
? allThemes.filter((t) => t !== "test" && t !== "default")
: allThemes.filter((t) => t !== "test")
const available = candidateThemes.filter((t) => !usedThemes.has(t))
// If all candidate themes are used, return all candidates (will pick randomly)
return available.length > 0 ? available : candidateThemes.length > 0 ? candidateThemes : allThemes
}
// Determine the profile using priority:
// 1. OCSFX_THEME env var (explicit selection, highest priority)
// 2. .ocsfx file in cwd (explicit per-project config)
// 3. TTY-to-profile mapping in home dir (persists across directories in same terminal)
// 4. Random selection (saves to TTY mapping for persistence)
function determineProfile(): { profile: string; source: string } {
const allThemes = getThemeNames()
// 1. Check environment variable first
const envProfile = process.env[ENV_PROFILE]
if (envProfile && allThemes.includes(envProfile)) {
return { profile: envProfile, source: "env" }
}
// 2. Check .ocsfx in current directory
const dirProfile = readDirectoryProfile()
if (dirProfile && allThemes.includes(dirProfile)) {
return { profile: dirProfile, source: "file" }
}
// 3. Check TTY-to-profile mapping
const currentTty = getTtyIdentifier()
if (currentTty) {
const ttyProfile = getTtyProfile(currentTty)
if (ttyProfile && allThemes.includes(ttyProfile)) {
return { profile: ttyProfile, source: "tty" }
}
}
// 4. Random selection - try to avoid duplicates with other instances
const state = loadState()
cleanupStaleInstances(state)
const availableThemes = getAvailableThemes(state)
// If the user has no custom themes, prefer the "default" theme
// (its bundled sounds ship with the plugin and work out of the box)
let randomProfile: string
if (!hasUserThemes() && availableThemes.includes("default")) {
randomProfile = "default"
} else {
randomProfile =
availableThemes[Math.floor(Math.random() * availableThemes.length)]
}
// Save to TTY mapping for persistence (if we have a TTY identifier)
if (currentTty) {
setTtyProfile(currentTty, randomProfile)
}
return { profile: randomProfile, source: "random" }
}
function assignThemeToInstance(): { theme: string; source: string } {
const state = loadState()
cleanupStaleInstances(state)
// Check if this instance already has a theme (same PID reusing)
if (state.instances[INSTANCE_ID]) {
return { theme: state.instances[INSTANCE_ID].theme, source: "instance" }
}
// Determine profile using priority: env > file > tty > random
const { profile, source } = determineProfile()
// Register this instance with the selected theme
state.instances[INSTANCE_ID] = {
theme: profile,
startedAt: new Date().toISOString(),
}
saveState(state)
return { theme: profile, source }
}
function removeInstance(): void {
const state = loadState()
delete state.instances[INSTANCE_ID]
saveState(state)
}
// =============================================================================
// SOUND PLAYBACK HELPERS
// =============================================================================
function randomSound(sounds: string[]): string | null {
if (!sounds || sounds.length === 0) {
return null
}
return sounds[Math.floor(Math.random() * sounds.length)]
}
/**
* Check if a session is a sub-agent (has a parentID).
* Returns true if it's a sub-agent, false if it's a top-level session.
* On failure (e.g. session not found), returns false (fail-open: play the sound).
*/
let _isSubagentClient: PluginInput["client"] | null = null
async function isSubagentSession(sessionID: string): Promise<boolean> {
if (!_isSubagentClient) return false
try {
const session = await _isSubagentClient.session.get({
path: { id: sessionID },
query: { directory: process.cwd() },
})
return !!session.data?.parentID
} catch {
// If we can't fetch session info, assume it's not a sub-agent (fail-open)
return false
}
}
// =============================================================================
// PLUGIN EXPORT
// =============================================================================
export const OpenCodeSFX: Plugin = async ({ $, client }) => {
// Skip sound effects in non-interactive/headless mode (e.g., opencode run spawned by a bash tool).
// When there's no TTY on stdin, there's no user at a terminal to hear the sounds.
if (!process.stdin.isTTY) {
await client.app.log({
body: {
service: "opencode-sfx",
level: "info",
message: "OpenCode SFX: disabled (non-interactive mode, no TTY)",
},
})
return {}
}
// Store client reference for sub-agent session lookups
_isSubagentClient = client
// Capture window info at startup for focus detection
captureWindowInfo()
// Load themes from YAML (with caching)
let themes = loadThemes()
let themeNames = Object.keys(themes)
if (themeNames.length === 0) {
await client.app.log({
body: {
service: "opencode-sfx",
level: "error",
message: "No themes found! Check that themes/*.yaml files exist.",
},
})
return {}
}
const { theme: initialTheme, source } = assignThemeToInstance()
let currentThemeKey = initialTheme
let currentTheme = themes[currentThemeKey]
currentThemeForLogging = currentThemeKey
if (!currentTheme) {
await client.app.log({
body: {
service: "opencode-sfx",
level: "error",
message: `Theme "${currentThemeKey}" not found in loaded themes`,
extra: { availableThemes: themeNames },
},
})
return {}
}
// Log the assigned theme with source info
const sourceLabel =
source === "env"
? "from OCSFX_THEME"
: source === "file"
? "from .ocsfx"
: source === "tty"
? "from terminal session"
: source === "instance"
? "existing instance"
: "randomly selected"
await client.app.log({
body: {
service: "opencode-sfx",
level: "info",
message: `OpenCode SFX: ${currentTheme.name} (${currentTheme.description}) [${sourceLabel}]`,
extra: { theme: currentThemeKey, source, pid: INSTANCE_ID, tty: getTtyIdentifier() },
},
})
// Helper to switch themes
const switchTheme = (newThemeKey: string): { success: boolean; message: string } => {
const newTheme = themes[newThemeKey]
if (!newTheme) {
return { success: false, message: `Theme "${newThemeKey}" not found` }
}
currentThemeKey = newThemeKey
currentTheme = newTheme
currentThemeForLogging = newThemeKey
// Update TTY profile for persistence
const tty = getTtyIdentifier()
if (tty) {
setTtyProfile(tty, newThemeKey)
}
// Play announcement sound
const announceFile = randomSound(currentTheme.sounds.announce)
if (announceFile) {
const announcePath = resolveSoundPath(currentTheme, announceFile)
if (announcePath) {
playSoundAlways(announcePath, "theme.switch", "theme changed")
}
}
return { success: true, message: `Switched to ${currentTheme.name} (${currentTheme.description})` }
}
// Play the announcement sound on startup (always, regardless of focus)
const announceFile = randomSound(currentTheme.sounds.announce)
if (announceFile) {
const announcePath = resolveSoundPath(currentTheme, announceFile)
if (announcePath) {
playSoundAlways(announcePath, "startup", "plugin initialized")
}
}
// Cleanup on exit
const cleanup = () => {
clearTmuxAlert()
removeInstance()
}
process.on("exit", cleanup)
process.on("SIGINT", () => {
cleanup()
process.exit(0)
})
process.on("SIGTERM", () => {
cleanup()
process.exit(0)
})
return {
// Tools for managing themes (used by /sfx command via AI)
tool: {
sfx_list_themes: {
description: "List all available SFX sound themes",
parameters: {
type: "object",
properties: {},
},
execute: async () => {
themes = loadThemes()
themeNames = Object.keys(themes).sort()
const lines = [`Available themes (current: ${currentThemeKey}):`, ""]
for (const key of themeNames) {
const theme = themes[key]
const marker = key === currentThemeKey ? "* " : " "
lines.push(`${marker}${key} - ${theme.name} (${theme.description})`)
}
lines.push("", `Total: ${themeNames.length} themes`)
return lines.join("\n")
},
},
sfx_view_theme: {
description: "View details of a specific theme",
parameters: {
type: "object",
properties: {
theme: {
type: "string",
description: "Theme key to view. Defaults to current theme.",
},
},
},
execute: async ({ theme: themeKey }: { theme?: string }) => {
const key = themeKey || currentThemeKey
const theme = themes[key]
if (!theme) {
return `Error: Theme "${key}" not found`
}
const isCurrent = key === currentThemeKey ? " (current)" : ""
const lines = [
`Theme: ${theme.name}${isCurrent}`,
`Key: ${key}`,
`Description: ${theme.description}`,
"",
"Sounds:",
` Announce (${theme.sounds.announce.length}): ${theme.sounds.announce.join(", ")}`,
` Question (${theme.sounds.question.length}): ${theme.sounds.question.join(", ")}`,
` Idle (${theme.sounds.idle.length}): ${theme.sounds.idle.join(", ")}`,
` Error (${theme.sounds.error.length}): ${theme.sounds.error.join(", ")}`,
]
return lines.join("\n")
},
},
sfx_change_theme: {
description: "Switch to a different sound theme. Call with theme parameter set to the theme key (e.g., 'marine', 'ghost'). If no theme is specified, randomly picks a different theme than the current one.",
parameters: {
type: "object",
properties: {
theme: {
type: "string",
description: "Theme key to switch to. If omitted, a random different theme is selected.",
},
},
},
execute: async ({ theme: themeKey }: { theme?: string }) => {
if (!themeKey) {
// Random switch: pick a different theme than the current one
themes = loadThemes()
themeNames = Object.keys(themes).sort()
const candidates = themeNames.filter(t => t !== currentThemeKey && t !== "test")
if (candidates.length === 0) {
return "No other themes available to switch to."
}
const randomKey = candidates[Math.floor(Math.random() * candidates.length)]
const result = switchTheme(randomKey)
return result.message
}
const result = switchTheme(themeKey)
return result.message
},
},
sfx_reload_themes: {
description: "Reload all themes from YAML files",
parameters: {
type: "object",
properties: {},
},
execute: async () => {
themes = reloadThemes()
themeNames = Object.keys(themes).sort()
const updatedTheme = themes[currentThemeKey]
if (updatedTheme) {
currentTheme = updatedTheme
}
return `Reloaded ${themeNames.length} themes: ${themeNames.join(", ")}`
},
},
sfx_test_sound: {
description: "Play the current theme's announce sound",
parameters: {
type: "object",
properties: {},
},
execute: async () => {
const soundFile = randomSound(currentTheme.sounds.announce)
if (!soundFile) {
return `Error: No announce sounds configured for theme ${currentThemeKey}`
}
const soundPath = resolveSoundPath(currentTheme, soundFile)
if (soundPath) {
playSoundAlways(soundPath, "test", "user requested test")
return `Playing: ${soundFile} (theme: ${currentThemeKey})`
}
return `Error: Sound file not found: ${soundFile}`
},
},
sfx_create_theme: {
description: "Create a new SFX sound theme. For an interactive wizard with sound previews, tell the user to run `opencode-sfx create` in their terminal. To create a theme programmatically, provide all the sound selections as parameters. Use sfx_list_sounds first to see available files.",
parameters: {
type: "object",
properties: {
name: {
type: "string",
description: "Display name for the theme (e.g., 'My Custom Theme')",
},
description: {
type: "string",
description: "Short description of the theme",
},
announce: {
type: "string",
description: "Sound file for announce (played on startup)",
},
question: {
type: "string",
description: "Sound file for question (played when waiting for input)",
},
idle: {
type: "array",
items: { type: "string" },
description: "Array of sound files for idle (played when task completes)",
},
error: {
type: "array",
items: { type: "string" },
description: "Array of sound files for error (played on errors)",
},
},
required: ["name", "announce", "question", "idle", "error"],
},
execute: async ({ name: themeName, description = "Custom sound theme", announce: announceSound, question: questionSound, idle: idleSounds, error: errorSounds }: { name: string; description?: string; announce: string; question: string; idle: string[]; error: string[] }) => {
// Validate required parameters
if (!themeName) {
return "Error: 'name' parameter is required"
}
if (!announceSound) {
return "Error: 'announce' parameter is required"
}
if (!questionSound) {
return "Error: 'question' parameter is required"
}
if (!idleSounds || !Array.isArray(idleSounds) || idleSounds.length === 0) {
return "Error: 'idle' parameter must be a non-empty array of sound filenames"
}
if (!errorSounds || !Array.isArray(errorSounds) || errorSounds.length === 0) {
return "Error: 'error' parameter must be a non-empty array of sound filenames"
}
const themeKey = themeName.toLowerCase().replace(/[^a-z0-9]+/g, "-")
// Check if theme already exists
if (themes[themeKey]) {
return `Error: Theme "${themeKey}" already exists. Choose a different name.`
}
// Validate sound files exist
const validateSound = (file: string) => resolveSoundPath(currentTheme, file) !== null
if (!validateSound(announceSound)) {
return `Error: Announce sound not found: ${announceSound}`
}
if (!validateSound(questionSound)) {
return `Error: Question sound not found: ${questionSound}`
}
for (const s of idleSounds) {
if (!validateSound(s)) {
return `Error: Idle sound not found: ${s}`
}
}
for (const s of errorSounds) {
if (!validateSound(s)) {
return `Error: Error sound not found: ${s}`
}
}
// Generate YAML content
const yamlContent = [
`name: ${themeName}`,
`description: ${description}`,
"",
"sounds:",
` announce: ${announceSound}`,
` question: ${questionSound}`,
" idle:",
...idleSounds.map((s: string) => ` - ${s}`),
" error:",
...errorSounds.map((s: string) => ` - ${s}`),
"",
].join("\n")
// Write to user themes directory (~/.ocsfx/themes/<key>/<key>.yaml)
const themeDir = join(USER_THEMES_DIR, themeKey)
mkdirSync(themeDir, { recursive: true })
const themeFile = join(themeDir, `${themeKey}.yaml`)
// Write the theme file
writeFileSync(themeFile, yamlContent)
// Reload themes
themes = reloadThemes()
themeNames = Object.keys(themes).sort()
const lines = [
`Theme "${themeName}" created successfully!`,
`File: ${themeFile}`,
"",
"YAML content:",
yamlContent,
]
return lines.join("\n")
},
},
sfx_list_sounds: {
description: "List available sound files. Each theme is a self-contained directory with its own sounds.",
parameters: {
type: "object",
properties: {
theme: {
type: "string",
description: "Theme key to list sounds for. Defaults to current theme. Use '*' to list all themes.",
},
filter: {
type: "string",
description: "Filter pattern to match filenames (case-insensitive substring match)",
},
},
},
execute: async ({ theme: themeKey, filter }: { theme?: string; filter?: string }) => {
const lines: string[] = []
let totalFiles = 0
const lowerFilter = filter ? filter.toLowerCase() : null
const listThemeSounds = (key: string, t: SoundTheme) => {
if (!existsSync(t.basePath)) return
try {
let files = readdirSync(t.basePath)
.filter(f => /\.(mp3|wav|ogg|m4a|aac)$/i.test(f))
.sort()
if (lowerFilter) files = files.filter(f => f.toLowerCase().includes(lowerFilter))
if (files.length === 0) return
const marker = key === currentThemeKey ? " *" : ""
if (lines.length > 0) lines.push("")
lines.push(`${key}${marker} (${t.basePath}):`, "")
files.forEach((f, i) => {
lines.push(` ${(totalFiles + i + 1).toString().padStart(3)}. ${f}`)
})
totalFiles += files.length
} catch { /* ignore */ }
}
if (themeKey && themeKey !== "*") {
const t = themes[themeKey]
if (!t) return `Error: Theme "${themeKey}" not found`
listThemeSounds(themeKey, t)
} else {
// List all themes (or just current)
const keys = themeKey === "*" ? Object.keys(themes).sort() : [currentThemeKey]
for (const k of keys) {
const t = themes[k]
if (t) listThemeSounds(k, t)
}
}
if (totalFiles === 0) {
return `No sound files found${filter ? ` (filter: ${filter})` : ""}`
}
lines.push("", `Total: ${totalFiles} files`)
return lines.join("\n")
},
},
sfx_preview_sound: {
description: "Play a sound file for preview",
parameters: {
type: "object",
properties: {
filename: {
type: "string",