opencode-smart-voice-notify 1.0.6 → 1.0.7

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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/util/config.js +294 -264
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-smart-voice-notify",
3
- "version": "1.0.6",
3
+ "version": "1.0.7",
4
4
  "description": "Smart voice notification plugin for OpenCode with multiple TTS engines (ElevenLabs, Edge TTS, Windows SAPI) and intelligent reminder system",
5
5
  "main": "index.js",
6
6
  "type": "module",
package/util/config.js CHANGED
@@ -3,239 +3,254 @@ import path from 'path';
3
3
  import os from 'os';
4
4
  import { fileURLToPath } from 'url';
5
5
 
6
- /**
7
- * Basic JSONC parser that strips single-line and multi-line comments.
8
- * @param {string} jsonc
9
- * @returns {any}
10
- */
11
- const parseJSONC = (jsonc) => {
12
- const stripped = jsonc.replace(/\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g, (m, g) => g ? "" : m);
13
- return JSON.parse(stripped);
14
- };
15
-
16
- /**
17
- * Get the directory where this plugin is installed.
18
- * Used to find bundled assets like example.config.jsonc
19
- */
20
- const getPluginDir = () => {
21
- const __filename = fileURLToPath(import.meta.url);
22
- const __dirname = path.dirname(__filename);
23
- return path.dirname(__dirname); // Go up from util/ to plugin root
24
- };
25
-
26
- /**
27
- * Generate a comprehensive default configuration file content.
28
- * This provides users with ALL available options fully documented.
29
- */
30
- const generateDefaultConfig = () => {
31
- return `{
32
- // ============================================================
33
- // OpenCode Smart Voice Notify - Configuration
34
- // ============================================================
35
- //
36
- // This file was auto-generated with all available options.
37
- // Customize the settings below to your preference.
38
- //
39
- // Sound files have been automatically copied to:
40
- // ~/.config/opencode/assets/
41
- //
42
- // Documentation: https://github.com/MasuRii/opencode-smart-voice-notify
43
- //
44
- // ============================================================
45
-
46
- // ============================================================
47
- // NOTIFICATION MODE SETTINGS (Smart Notification System)
48
- // ============================================================
49
- // Controls how notifications are delivered:
50
- // 'sound-first' - Play sound immediately, TTS reminder after delay (RECOMMENDED)
51
- // 'tts-first' - Speak TTS immediately, no sound
52
- // 'both' - Play sound AND speak TTS immediately
53
- // 'sound-only' - Only play sound, no TTS at all
54
- "notificationMode": "sound-first",
55
-
56
- // ============================================================
57
- // TTS REMINDER SETTINGS (When user doesn't respond to sound)
58
- // ============================================================
59
-
60
- // Enable TTS reminder if user doesn't respond after sound notification
61
- "enableTTSReminder": true,
62
-
63
- // Delay (in seconds) before TTS reminder fires
64
- // Set globally or per-notification type
65
- "ttsReminderDelaySeconds": 30, // Global default
66
- "idleReminderDelaySeconds": 30, // For task completion notifications
67
- "permissionReminderDelaySeconds": 20, // For permission requests (more urgent)
68
-
69
- // Follow-up reminders if user STILL doesn't respond after first TTS
70
- "enableFollowUpReminders": true,
71
- "maxFollowUpReminders": 3, // Max number of follow-up TTS reminders
72
- "reminderBackoffMultiplier": 1.5, // Each follow-up waits longer (30s, 45s, 67s...)
73
-
74
- // ============================================================
75
- // TTS ENGINE SELECTION
76
- // ============================================================
6
+ /**
7
+ * Basic JSONC parser that strips single-line and multi-line comments.
8
+ * @param {string} jsonc
9
+ * @returns {any}
10
+ */
11
+ const parseJSONC = (jsonc) => {
12
+ const stripped = jsonc.replace(/\\"|"(?:\\"|[^"])*"|(\/\/.*|\/\*[\s\S]*?\*\/)/g, (m, g) => g ? "" : m);
13
+ return JSON.parse(stripped);
14
+ };
15
+
16
+ /**
17
+ * Helper to format JSON values for the template.
18
+ * @param {any} val
19
+ * @param {number} indent
20
+ * @returns {string}
21
+ */
22
+ const formatJSON = (val, indent = 0) => {
23
+ const json = JSON.stringify(val, null, 4);
24
+ return indent > 0 ? json.replace(/\n/g, '\n' + ' '.repeat(indent)) : json;
25
+ };
26
+
27
+ /**
28
+ * Get the directory where this plugin is installed.
29
+ * Used to find bundled assets like example.config.jsonc
30
+ */
31
+ const getPluginDir = () => {
32
+ const __filename = fileURLToPath(import.meta.url);
33
+ const __dirname = path.dirname(__filename);
34
+ return path.dirname(__dirname); // Go up from util/ to plugin root
35
+ };
36
+
37
+ /**
38
+ * Generate a comprehensive default configuration file content.
39
+ * This provides users with ALL available options fully documented.
40
+ * @param {object} overrides - Existing configuration to preserve
41
+ * @param {string} version - Current version to set in config
42
+ */
43
+ const generateDefaultConfig = (overrides = {}, version = '1.0.0') => {
44
+ return `{
45
+ // ============================================================
46
+ // OpenCode Smart Voice Notify - Configuration
47
+ // ============================================================
48
+ //
49
+ // This file was auto-generated with all available options.
50
+ // Customize the settings below to your preference.
51
+ //
52
+ // Sound files have been automatically copied to:
53
+ // ~/.config/opencode/assets/
54
+ //
55
+ // Documentation: https://github.com/MasuRii/opencode-smart-voice-notify
56
+ //
57
+ // ============================================================
58
+
59
+ // Internal version tracking - DO NOT REMOVE
60
+ "_configVersion": "${version}",
61
+
62
+ // ============================================================
63
+ // NOTIFICATION MODE SETTINGS (Smart Notification System)
64
+ // ============================================================
65
+ // Controls how notifications are delivered:
66
+ // 'sound-first' - Play sound immediately, TTS reminder after delay (RECOMMENDED)
67
+ // 'tts-first' - Speak TTS immediately, no sound
68
+ // 'both' - Play sound AND speak TTS immediately
69
+ // 'sound-only' - Only play sound, no TTS at all
70
+ "notificationMode": "${overrides.notificationMode || 'sound-first'}",
71
+
72
+ // ============================================================
73
+ // TTS REMINDER SETTINGS (When user doesn't respond to sound)
74
+ // ============================================================
75
+
76
+ // Enable TTS reminder if user doesn't respond after sound notification
77
+ "enableTTSReminder": ${overrides.enableTTSReminder !== undefined ? overrides.enableTTSReminder : true},
78
+
79
+ // Delay (in seconds) before TTS reminder fires
80
+ // Set globally or per-notification type
81
+ "ttsReminderDelaySeconds": ${overrides.ttsReminderDelaySeconds !== undefined ? overrides.ttsReminderDelaySeconds : 30}, // Global default
82
+ "idleReminderDelaySeconds": ${overrides.idleReminderDelaySeconds !== undefined ? overrides.idleReminderDelaySeconds : 30}, // For task completion notifications
83
+ "permissionReminderDelaySeconds": ${overrides.permissionReminderDelaySeconds !== undefined ? overrides.permissionReminderDelaySeconds : 20}, // For permission requests (more urgent)
84
+
85
+ // Follow-up reminders if user STILL doesn't respond after first TTS
86
+ "enableFollowUpReminders": ${overrides.enableFollowUpReminders !== undefined ? overrides.enableFollowUpReminders : true},
87
+ "maxFollowUpReminders": ${overrides.maxFollowUpReminders !== undefined ? overrides.maxFollowUpReminders : 3}, // Max number of follow-up TTS reminders
88
+ "reminderBackoffMultiplier": ${overrides.reminderBackoffMultiplier !== undefined ? overrides.reminderBackoffMultiplier : 1.5}, // Each follow-up waits longer (30s, 45s, 67s...)
89
+
90
+ // ============================================================
91
+ // TTS ENGINE SELECTION
92
+ // ============================================================
77
93
  // 'elevenlabs' - Best quality, anime-like voices (requires API key, free tier: 10k chars/month)
78
94
  // 'edge' - Good quality neural voices (free, requires: pip install edge-tts)
79
95
  // 'sapi' - Windows built-in voices (free, offline, robotic)
80
- "ttsEngine": "elevenlabs",
96
+ "ttsEngine": "${overrides.ttsEngine || 'elevenlabs'}",
81
97
 
82
98
  // Enable TTS for notifications (falls back to sound files if TTS fails)
83
- "enableTTS": true,
84
-
85
- // ============================================================
86
- // ELEVENLABS SETTINGS (Best Quality - Anime-like Voices)
87
- // ============================================================
88
- // Get your API key from: https://elevenlabs.io/app/settings/api-keys
89
- // Free tier: 10,000 characters/month
90
- //
91
- // To use ElevenLabs:
92
- // 1. Uncomment elevenLabsApiKey and add your key
93
- // 2. Change ttsEngine above to "elevenlabs"
94
- //
95
- // "elevenLabsApiKey": "YOUR_API_KEY_HERE",
96
-
97
- // Voice ID - Recommended cute/anime-like voices:
98
- // 'cgSgspJ2msm6clMCkdW9' - Jessica (Playful, Bright, Warm) - RECOMMENDED
99
- // 'FGY2WhTYpPnrIDTdsKH5' - Laura (Enthusiast, Quirky)
100
- // 'jsCqWAovK2LkecY7zXl4' - Freya (Expressive, Confident)
101
- // 'EXAVITQu4vr4xnSDxMaL' - Sarah (Soft, Warm)
102
- // Browse more at: https://elevenlabs.io/voice-library
103
- "elevenLabsVoiceId": "cgSgspJ2msm6clMCkdW9",
104
-
105
- // Model: 'eleven_turbo_v2_5' (fast, good), 'eleven_multilingual_v2' (highest quality)
106
- "elevenLabsModel": "eleven_turbo_v2_5",
107
-
108
- // Voice tuning (0.0 to 1.0)
109
- "elevenLabsStability": 0.5, // Lower = more expressive, Higher = more consistent
110
- "elevenLabsSimilarity": 0.75, // How closely to match the original voice
111
- "elevenLabsStyle": 0.5, // Style exaggeration (higher = more expressive)
112
-
113
- // ============================================================
114
- // EDGE TTS SETTINGS (Free Neural Voices - Default Engine)
115
- // ============================================================
116
- // Requires: pip install edge-tts
117
-
99
+ "enableTTS": ${overrides.enableTTS !== undefined ? overrides.enableTTS : true},
100
+
101
+ // ============================================================
102
+ // ELEVENLABS SETTINGS (Best Quality - Anime-like Voices)
103
+ // ============================================================
104
+ // Get your API key from: https://elevenlabs.io/app/settings/api-keys
105
+ // Free tier: 10,000 characters/month
106
+ //
107
+ // To use ElevenLabs:
108
+ // 1. Uncomment elevenLabsApiKey and add your key
109
+ // 2. Change ttsEngine above to "elevenlabs"
110
+ //
111
+ ${overrides.elevenLabsApiKey ? `"elevenLabsApiKey": "${overrides.elevenLabsApiKey}",` : `// "elevenLabsApiKey": "YOUR_API_KEY_HERE",`}
112
+
113
+ // Voice ID - Recommended cute/anime-like voices:
114
+ // 'cgSgspJ2msm6clMCkdW9' - Jessica (Playful, Bright, Warm) - RECOMMENDED
115
+ // 'FGY2WhTYpPnrIDTdsKH5' - Laura (Enthusiast, Quirky)
116
+ // 'jsCqWAovK2LkecY7zXl4' - Freya (Expressive, Confident)
117
+ // 'EXAVITQu4vr4xnSDxMaL' - Sarah (Soft, Warm)
118
+ // Browse more at: https://elevenlabs.io/voice-library
119
+ "elevenLabsVoiceId": "${overrides.elevenLabsVoiceId || 'cgSgspJ2msm6clMCkdW9'}",
120
+
121
+ // Model: 'eleven_turbo_v2_5' (fast, good), 'eleven_multilingual_v2' (highest quality)
122
+ "elevenLabsModel": "${overrides.elevenLabsModel || 'eleven_turbo_v2_5'}",
123
+
124
+ // Voice tuning (0.0 to 1.0)
125
+ "elevenLabsStability": ${overrides.elevenLabsStability !== undefined ? overrides.elevenLabsStability : 0.5}, // Lower = more expressive, Higher = more consistent
126
+ "elevenLabsSimilarity": ${overrides.elevenLabsSimilarity !== undefined ? overrides.elevenLabsSimilarity : 0.75}, // How closely to match the original voice
127
+ "elevenLabsStyle": ${overrides.elevenLabsStyle !== undefined ? overrides.elevenLabsStyle : 0.5}, // Style exaggeration (higher = more expressive)
128
+
129
+ // ============================================================
130
+ // EDGE TTS SETTINGS (Free Neural Voices - Default Engine)
131
+ // ============================================================
132
+ // Requires: pip install edge-tts
133
+
118
134
  // Voice options (run 'edge-tts --list-voices' to see all):
119
135
  // 'en-US-AnaNeural' - Young, cute, cartoon-like (RECOMMENDED)
120
136
  // 'en-US-JennyNeural' - Friendly, warm
121
137
  // 'en-US-AriaNeural' - Confident, clear
122
138
  // 'en-GB-SoniaNeural' - British, friendly
123
139
  // 'en-AU-NatashaNeural' - Australian, warm
124
- "edgeVoice": "en-US-JennyNeural",
140
+ "edgeVoice": "${overrides.edgeVoice || 'en-US-JennyNeural'}",
125
141
 
126
142
  // Pitch adjustment: +0Hz to +100Hz (higher = more anime-like)
127
- "edgePitch": "+0Hz",
128
-
129
- // Speech rate: -50% to +100%
130
- "edgeRate": "+10%",
131
-
132
- // ============================================================
133
- // SAPI SETTINGS (Windows Built-in - Last Resort Fallback)
134
- // ============================================================
135
-
136
- // Voice (run PowerShell to list all installed voices):
137
- // Add-Type -AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).GetInstalledVoices() | % { $_.VoiceInfo.Name }
138
- //
139
- // Common Windows voices:
140
- // 'Microsoft Zira Desktop' - Female, US English
141
- // 'Microsoft David Desktop' - Male, US English
142
- // 'Microsoft Hazel Desktop' - Female, UK English
143
- "sapiVoice": "Microsoft Zira Desktop",
144
-
145
- // Speech rate: -10 (slowest) to +10 (fastest), 0 is normal
146
- "sapiRate": -1,
147
-
148
- // Pitch: 'x-low', 'low', 'medium', 'high', 'x-high'
149
- "sapiPitch": "medium",
150
-
151
- // Volume: 'silent', 'x-soft', 'soft', 'medium', 'loud', 'x-loud'
152
- "sapiVolume": "loud",
153
-
154
- // ============================================================
155
- // INITIAL TTS MESSAGES (Used immediately or after sound)
156
- // These are randomly selected each time for variety
157
- // ============================================================
158
-
159
- // Messages when agent finishes work (task completion)
160
- "idleTTSMessages": [
161
- "All done! Your task has been completed successfully.",
162
- "Hey there! I finished working on your request.",
163
- "Task complete! Ready for your review whenever you are.",
164
- "Good news! Everything is done and ready for you.",
165
- "Finished! Let me know if you need anything else."
166
- ],
167
-
168
- // Messages for permission requests
169
- "permissionTTSMessages": [
170
- "Attention please! I need your permission to continue.",
171
- "Hey! Quick approval needed to proceed with the task.",
172
- "Heads up! There is a permission request waiting for you.",
173
- "Excuse me! I need your authorization before I can continue.",
174
- "Permission required! Please review and approve when ready."
175
- ],
176
-
177
- // ============================================================
178
- // TTS REMINDER MESSAGES (More urgent - used after delay if no response)
179
- // These are more personalized and urgent to get user attention
180
- // ============================================================
181
-
182
- // Reminder messages when agent finished but user hasn't responded
183
- "idleReminderTTSMessages": [
184
- "Hey, are you still there? Your task has been waiting for review.",
185
- "Just a gentle reminder - I finished your request a while ago!",
186
- "Hello? I completed your task. Please take a look when you can.",
187
- "Still waiting for you! The work is done and ready for review.",
188
- "Knock knock! Your completed task is patiently waiting for you."
189
- ],
190
-
191
- // Reminder messages when permission still needed
192
- "permissionReminderTTSMessages": [
193
- "Hey! I still need your permission to continue. Please respond!",
194
- "Reminder: There is a pending permission request. I cannot proceed without you.",
195
- "Hello? I am waiting for your approval. This is getting urgent!",
196
- "Please check your screen! I really need your permission to move forward.",
197
- "Still waiting for authorization! The task is on hold until you respond."
198
- ],
199
-
200
- // ============================================================
201
- // SOUND FILES (For immediate notifications)
202
- // These are played first before TTS reminder kicks in
203
- // ============================================================
204
- // Paths are relative to ~/.config/opencode/ directory
205
- // Sound files are automatically copied here on first run
206
- // You can replace with your own custom MP3/WAV files
207
-
208
- "idleSound": "assets/Soft-high-tech-notification-sound-effect.mp3",
209
- "permissionSound": "assets/Machine-alert-beep-sound-effect.mp3",
210
-
211
- // ============================================================
212
- // GENERAL SETTINGS
213
- // ============================================================
214
-
215
- // Wake monitor from sleep when notifying (Windows/macOS)
216
- "wakeMonitor": true,
217
-
218
- // Force system volume up if below threshold
219
- "forceVolume": true,
220
-
221
- // Volume threshold (0-100): force volume if current level is below this
222
- "volumeThreshold": 50,
223
-
224
- // Show TUI toast notifications in OpenCode terminal
225
- "enableToast": true,
226
-
227
- // Enable audio notifications (sound files and TTS)
228
- "enableSound": true,
229
-
230
- // Consider monitor asleep after this many seconds of inactivity (Windows only)
231
- "idleThresholdSeconds": 60,
232
-
233
- // Enable debug logging to ~/.config/opencode/smart-voice-notify-debug.log
234
- // Useful for troubleshooting notification issues
235
- "debugLog": false
236
- }
237
- `;
238
- };
143
+ "edgePitch": "${overrides.edgePitch || '+0Hz'}",
144
+
145
+ // Speech rate: -50% to +100%
146
+ "edgeRate": "${overrides.edgeRate || '+10%'}",
147
+
148
+ // ============================================================
149
+ // SAPI SETTINGS (Windows Built-in - Last Resort Fallback)
150
+ // ============================================================
151
+
152
+ // Voice (run PowerShell to list all installed voices):
153
+ // Add-Type -AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).GetInstalledVoices() | % { $_.VoiceInfo.Name }
154
+ //
155
+ // Common Windows voices:
156
+ // 'Microsoft Zira Desktop' - Female, US English
157
+ // 'Microsoft David Desktop' - Male, US English
158
+ // 'Microsoft Hazel Desktop' - Female, UK English
159
+ "sapiVoice": "${overrides.sapiVoice || 'Microsoft Zira Desktop'}",
160
+
161
+ // Speech rate: -10 (slowest) to +10 (fastest), 0 is normal
162
+ "sapiRate": ${overrides.sapiRate !== undefined ? overrides.sapiRate : -1},
163
+
164
+ // Pitch: 'x-low', 'low', 'medium', 'high', 'x-high'
165
+ "sapiPitch": "${overrides.sapiPitch || 'medium'}",
166
+
167
+ // Volume: 'silent', 'x-soft', 'soft', 'medium', 'loud', 'x-loud'
168
+ "sapiVolume": "${overrides.sapiVolume || 'loud'}",
169
+
170
+ // ============================================================
171
+ // INITIAL TTS MESSAGES (Used immediately or after sound)
172
+ // These are randomly selected each time for variety
173
+ // ============================================================
174
+
175
+ // Messages when agent finishes work (task completion)
176
+ "idleTTSMessages": ${formatJSON(overrides.idleTTSMessages || [
177
+ "All done! Your task has been completed successfully.",
178
+ "Hey there! I finished working on your request.",
179
+ "Task complete! Ready for your review whenever you are.",
180
+ "Good news! Everything is done and ready for you.",
181
+ "Finished! Let me know if you need anything else."
182
+ ], 4)},
183
+
184
+ // Messages for permission requests
185
+ "permissionTTSMessages": ${formatJSON(overrides.permissionTTSMessages || [
186
+ "Attention please! I need your permission to continue.",
187
+ "Hey! Quick approval needed to proceed with the task.",
188
+ "Heads up! There is a permission request waiting for you.",
189
+ "Excuse me! I need your authorization before I can continue.",
190
+ "Permission required! Please review and approve when ready."
191
+ ], 4)},
192
+
193
+ // ============================================================
194
+ // TTS REMINDER MESSAGES (More urgent - used after delay if no response)
195
+ // These are more personalized and urgent to get user attention
196
+ // ============================================================
197
+
198
+ // Reminder messages when agent finished but user hasn't responded
199
+ "idleReminderTTSMessages": ${formatJSON(overrides.idleReminderTTSMessages || [
200
+ "Hey, are you still there? Your task has been waiting for review.",
201
+ "Just a gentle reminder - I finished your request a while ago!",
202
+ "Hello? I completed your task. Please take a look when you can.",
203
+ "Still waiting for you! The work is done and ready for review.",
204
+ "Knock knock! Your completed task is patiently waiting for you."
205
+ ], 4)},
206
+
207
+ // Reminder messages when permission still needed
208
+ "permissionReminderTTSMessages": ${formatJSON(overrides.permissionReminderTTSMessages || [
209
+ "Hey! I still need your permission to continue. Please respond!",
210
+ "Reminder: There is a pending permission request. I cannot proceed without you.",
211
+ "Hello? I am waiting for your approval. This is getting urgent!",
212
+ "Please check your screen! I really need your permission to move forward.",
213
+ "Still waiting for authorization! The task is on hold until you respond."
214
+ ], 4)},
215
+
216
+ // ============================================================
217
+ // SOUND FILES (For immediate notifications)
218
+ // These are played first before TTS reminder kicks in
219
+ // ============================================================
220
+ // Paths are relative to ~/.config/opencode/ directory
221
+ // Sound files are automatically copied here on first run
222
+ // You can replace with your own custom MP3/WAV files
223
+
224
+ "idleSound": "${overrides.idleSound || 'assets/Soft-high-tech-notification-sound-effect.mp3'}",
225
+ "permissionSound": "${overrides.permissionSound || 'assets/Machine-alert-beep-sound-effect.mp3'}",
226
+
227
+ // ============================================================
228
+ // GENERAL SETTINGS
229
+ // ============================================================
230
+
231
+ // Wake monitor from sleep when notifying (Windows/macOS)
232
+ "wakeMonitor": ${overrides.wakeMonitor !== undefined ? overrides.wakeMonitor : true},
233
+
234
+ // Force system volume up if below threshold
235
+ "forceVolume": ${overrides.forceVolume !== undefined ? overrides.forceVolume : true},
236
+
237
+ // Volume threshold (0-100): force volume if current level is below this
238
+ "volumeThreshold": ${overrides.volumeThreshold !== undefined ? overrides.volumeThreshold : 50},
239
+
240
+ // Show TUI toast notifications in OpenCode terminal
241
+ "enableToast": ${overrides.enableToast !== undefined ? overrides.enableToast : true},
242
+
243
+ // Enable audio notifications (sound files and TTS)
244
+ "enableSound": ${overrides.enableSound !== undefined ? overrides.enableSound : true},
245
+
246
+ // Consider monitor asleep after this many seconds of inactivity (Windows only)
247
+ "idleThresholdSeconds": ${overrides.idleThresholdSeconds !== undefined ? overrides.idleThresholdSeconds : 60},
248
+
249
+ // Enable debug logging to ~/.config/opencode/smart-voice-notify-debug.log
250
+ // Useful for troubleshooting notification issues
251
+ "debugLog": ${overrides.debugLog !== undefined ? overrides.debugLog : false}
252
+ }`;
253
+ };
239
254
 
240
255
  /**
241
256
  * Copy bundled assets (sound files) to the OpenCode config directory.
@@ -273,47 +288,62 @@ const copyBundledAssets = (configDir) => {
273
288
  }
274
289
  };
275
290
 
276
- /**
277
- * Loads a configuration file from the OpenCode config directory.
278
- * If the file doesn't exist, creates a default config file.
279
- * @param {string} name - Name of the config file (without .jsonc extension)
280
- * @param {object} defaults - Default values if file doesn't exist or is invalid
281
- * @returns {object}
282
- */
283
- export const loadConfig = (name, defaults = {}) => {
284
- const configDir = process.env.OPENCODE_CONFIG_DIR || path.join(os.homedir(), '.config', 'opencode');
285
- const filePath = path.join(configDir, `${name}.jsonc`);
286
-
287
- if (!fs.existsSync(filePath)) {
288
- // Auto-create the default config file
289
- try {
290
- // Ensure config directory exists
291
- if (!fs.existsSync(configDir)) {
292
- fs.mkdirSync(configDir, { recursive: true });
293
- }
294
-
295
- // Write the default config
296
- const defaultConfig = generateDefaultConfig();
297
- fs.writeFileSync(filePath, defaultConfig, 'utf-8');
298
-
299
- // Also copy bundled assets (sound files) to the config directory
300
- copyBundledAssets(configDir);
301
-
302
- // Parse and return the newly created config merged with defaults
303
- const config = parseJSONC(defaultConfig);
304
- return { ...defaults, ...config };
305
- } catch (error) {
306
- // If we can't create the file, just return defaults
307
- return defaults;
308
- }
309
- }
310
-
311
- try {
312
- const content = fs.readFileSync(filePath, 'utf-8');
313
- const config = parseJSONC(content);
314
- return { ...defaults, ...config };
315
- } catch (error) {
316
- // Silently return defaults - don't use console.error as it breaks TUI
317
- return defaults;
318
- }
319
- };
291
+ /**
292
+ * Loads a configuration file from the OpenCode config directory.
293
+ * If the file doesn't exist, creates a default config file.
294
+ * Performs version checks and migrates config if necessary.
295
+ * @param {string} name - Name of the config file (without .jsonc extension)
296
+ * @param {object} defaults - Default values if file doesn't exist or is invalid
297
+ * @returns {object}
298
+ */
299
+ export const loadConfig = (name, defaults = {}) => {
300
+ const configDir = process.env.OPENCODE_CONFIG_DIR || path.join(os.homedir(), '.config', 'opencode');
301
+ const filePath = path.join(configDir, `${name}.jsonc`);
302
+
303
+ // Get current version from package.json
304
+ const pluginDir = getPluginDir();
305
+ const pkg = JSON.parse(fs.readFileSync(path.join(pluginDir, 'package.json'), 'utf-8'));
306
+ const currentVersion = pkg.version;
307
+
308
+ let existingConfig = null;
309
+ if (fs.existsSync(filePath)) {
310
+ try {
311
+ const content = fs.readFileSync(filePath, 'utf-8');
312
+ existingConfig = parseJSONC(content);
313
+ } catch (error) {
314
+ // If file is invalid JSONC, we'll treat it as missing and overwrite
315
+ }
316
+ }
317
+
318
+ // Version check and migration logic
319
+ if (!existingConfig || existingConfig._configVersion !== currentVersion) {
320
+ try {
321
+ // Ensure config directory exists
322
+ if (!fs.existsSync(configDir)) {
323
+ fs.mkdirSync(configDir, { recursive: true });
324
+ }
325
+
326
+ // Generate new config content using existing values as overrides
327
+ // This preserves user settings while updating comments and adding new fields
328
+ const newConfigContent = generateDefaultConfig(existingConfig || {}, currentVersion);
329
+ fs.writeFileSync(filePath, newConfigContent, 'utf-8');
330
+
331
+ // Also ensure all bundled assets (sound files) are present in the config directory
332
+ copyBundledAssets(configDir);
333
+
334
+ if (existingConfig) {
335
+ console.log(`[Smart Voice Notify] Config migrated to version ${currentVersion}`);
336
+ } else {
337
+ console.log(`[Smart Voice Notify] Initialized default config at ${filePath}`);
338
+ }
339
+
340
+ // Re-parse the newly written config
341
+ existingConfig = parseJSONC(newConfigContent);
342
+ } catch (error) {
343
+ // If migration fails, try to return whatever we have or defaults
344
+ return existingConfig || defaults;
345
+ }
346
+ }
347
+
348
+ return { ...defaults, ...existingConfig };
349
+ };