wave-agent-sdk 0.0.7 → 0.0.10

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 (240) hide show
  1. package/dist/agent.d.ts +105 -24
  2. package/dist/agent.d.ts.map +1 -1
  3. package/dist/agent.js +438 -53
  4. package/dist/index.d.ts +4 -0
  5. package/dist/index.d.ts.map +1 -1
  6. package/dist/index.js +4 -0
  7. package/dist/managers/aiManager.d.ts +18 -7
  8. package/dist/managers/aiManager.d.ts.map +1 -1
  9. package/dist/managers/aiManager.js +254 -142
  10. package/dist/managers/backgroundBashManager.d.ts.map +1 -1
  11. package/dist/managers/backgroundBashManager.js +11 -9
  12. package/dist/managers/hookManager.d.ts +6 -6
  13. package/dist/managers/hookManager.d.ts.map +1 -1
  14. package/dist/managers/hookManager.js +81 -39
  15. package/dist/managers/liveConfigManager.d.ts +95 -0
  16. package/dist/managers/liveConfigManager.d.ts.map +1 -0
  17. package/dist/managers/liveConfigManager.js +442 -0
  18. package/dist/managers/lspManager.d.ts +43 -0
  19. package/dist/managers/lspManager.d.ts.map +1 -0
  20. package/dist/managers/lspManager.js +326 -0
  21. package/dist/managers/messageManager.d.ts +41 -24
  22. package/dist/managers/messageManager.d.ts.map +1 -1
  23. package/dist/managers/messageManager.js +184 -73
  24. package/dist/managers/permissionManager.d.ts +66 -0
  25. package/dist/managers/permissionManager.d.ts.map +1 -0
  26. package/dist/managers/permissionManager.js +208 -0
  27. package/dist/managers/skillManager.d.ts +1 -0
  28. package/dist/managers/skillManager.d.ts.map +1 -1
  29. package/dist/managers/skillManager.js +2 -1
  30. package/dist/managers/slashCommandManager.d.ts.map +1 -1
  31. package/dist/managers/slashCommandManager.js +4 -2
  32. package/dist/managers/subagentManager.d.ts +42 -6
  33. package/dist/managers/subagentManager.d.ts.map +1 -1
  34. package/dist/managers/subagentManager.js +213 -62
  35. package/dist/managers/toolManager.d.ts +38 -1
  36. package/dist/managers/toolManager.d.ts.map +1 -1
  37. package/dist/managers/toolManager.js +66 -2
  38. package/dist/services/aiService.d.ts +15 -5
  39. package/dist/services/aiService.d.ts.map +1 -1
  40. package/dist/services/aiService.js +446 -77
  41. package/dist/services/configurationService.d.ts +116 -0
  42. package/dist/services/configurationService.d.ts.map +1 -0
  43. package/dist/services/configurationService.js +585 -0
  44. package/dist/services/fileWatcher.d.ts +69 -0
  45. package/dist/services/fileWatcher.d.ts.map +1 -0
  46. package/dist/services/fileWatcher.js +212 -0
  47. package/dist/services/hook.d.ts +5 -40
  48. package/dist/services/hook.d.ts.map +1 -1
  49. package/dist/services/hook.js +47 -109
  50. package/dist/services/jsonlHandler.d.ts +71 -0
  51. package/dist/services/jsonlHandler.d.ts.map +1 -0
  52. package/dist/services/jsonlHandler.js +236 -0
  53. package/dist/services/memory.d.ts.map +1 -1
  54. package/dist/services/memory.js +33 -11
  55. package/dist/services/session.d.ts +116 -52
  56. package/dist/services/session.d.ts.map +1 -1
  57. package/dist/services/session.js +415 -143
  58. package/dist/tools/bashTool.d.ts.map +1 -1
  59. package/dist/tools/bashTool.js +77 -17
  60. package/dist/tools/deleteFileTool.d.ts.map +1 -1
  61. package/dist/tools/deleteFileTool.js +27 -1
  62. package/dist/tools/editTool.d.ts.map +1 -1
  63. package/dist/tools/editTool.js +33 -8
  64. package/dist/tools/lspTool.d.ts +6 -0
  65. package/dist/tools/lspTool.d.ts.map +1 -0
  66. package/dist/tools/lspTool.js +589 -0
  67. package/dist/tools/multiEditTool.d.ts.map +1 -1
  68. package/dist/tools/multiEditTool.js +30 -10
  69. package/dist/tools/readTool.d.ts.map +1 -1
  70. package/dist/tools/readTool.js +113 -3
  71. package/dist/tools/skillTool.js +2 -2
  72. package/dist/tools/todoWriteTool.d.ts.map +1 -1
  73. package/dist/tools/todoWriteTool.js +23 -0
  74. package/dist/tools/types.d.ts +11 -8
  75. package/dist/tools/types.d.ts.map +1 -1
  76. package/dist/tools/writeTool.d.ts.map +1 -1
  77. package/dist/tools/writeTool.js +30 -15
  78. package/dist/types/commands.d.ts +4 -1
  79. package/dist/types/commands.d.ts.map +1 -1
  80. package/dist/types/config.d.ts +4 -0
  81. package/dist/types/config.d.ts.map +1 -1
  82. package/dist/types/configuration.d.ts +69 -0
  83. package/dist/types/configuration.d.ts.map +1 -0
  84. package/dist/types/configuration.js +8 -0
  85. package/dist/types/core.d.ts +45 -0
  86. package/dist/types/core.d.ts.map +1 -1
  87. package/dist/types/environment.d.ts +83 -0
  88. package/dist/types/environment.d.ts.map +1 -0
  89. package/dist/types/environment.js +21 -0
  90. package/dist/types/fileSearch.d.ts +5 -0
  91. package/dist/types/fileSearch.d.ts.map +1 -0
  92. package/dist/types/fileSearch.js +1 -0
  93. package/dist/types/hooks.d.ts +18 -3
  94. package/dist/types/hooks.d.ts.map +1 -1
  95. package/dist/types/hooks.js +8 -8
  96. package/dist/types/index.d.ts +7 -0
  97. package/dist/types/index.d.ts.map +1 -1
  98. package/dist/types/index.js +7 -0
  99. package/dist/types/lsp.d.ts +90 -0
  100. package/dist/types/lsp.d.ts.map +1 -0
  101. package/dist/types/lsp.js +4 -0
  102. package/dist/types/messaging.d.ts +19 -12
  103. package/dist/types/messaging.d.ts.map +1 -1
  104. package/dist/types/permissions.d.ts +35 -0
  105. package/dist/types/permissions.d.ts.map +1 -0
  106. package/dist/types/permissions.js +12 -0
  107. package/dist/types/session.d.ts +15 -0
  108. package/dist/types/session.d.ts.map +1 -0
  109. package/dist/types/session.js +7 -0
  110. package/dist/types/skills.d.ts +1 -0
  111. package/dist/types/skills.d.ts.map +1 -1
  112. package/dist/types/tools.d.ts +35 -0
  113. package/dist/types/tools.d.ts.map +1 -0
  114. package/dist/types/tools.js +4 -0
  115. package/dist/utils/abortUtils.d.ts +34 -0
  116. package/dist/utils/abortUtils.d.ts.map +1 -0
  117. package/dist/utils/abortUtils.js +92 -0
  118. package/dist/utils/bashHistory.d.ts +4 -0
  119. package/dist/utils/bashHistory.d.ts.map +1 -1
  120. package/dist/utils/bashHistory.js +48 -30
  121. package/dist/utils/builtinSubagents.d.ts +7 -0
  122. package/dist/utils/builtinSubagents.d.ts.map +1 -0
  123. package/dist/utils/builtinSubagents.js +65 -0
  124. package/dist/utils/cacheControlUtils.d.ts +96 -0
  125. package/dist/utils/cacheControlUtils.d.ts.map +1 -0
  126. package/dist/utils/cacheControlUtils.js +324 -0
  127. package/dist/utils/commandPathResolver.d.ts +52 -0
  128. package/dist/utils/commandPathResolver.d.ts.map +1 -0
  129. package/dist/utils/commandPathResolver.js +145 -0
  130. package/dist/utils/configPaths.d.ts +85 -0
  131. package/dist/utils/configPaths.d.ts.map +1 -0
  132. package/dist/utils/configPaths.js +121 -0
  133. package/dist/utils/constants.d.ts +1 -13
  134. package/dist/utils/constants.d.ts.map +1 -1
  135. package/dist/utils/constants.js +2 -14
  136. package/dist/utils/convertMessagesForAPI.d.ts +2 -1
  137. package/dist/utils/convertMessagesForAPI.d.ts.map +1 -1
  138. package/dist/utils/convertMessagesForAPI.js +39 -18
  139. package/dist/utils/customCommands.d.ts.map +1 -1
  140. package/dist/utils/customCommands.js +66 -21
  141. package/dist/utils/fileSearch.d.ts +14 -0
  142. package/dist/utils/fileSearch.d.ts.map +1 -0
  143. package/dist/utils/fileSearch.js +88 -0
  144. package/dist/utils/fileUtils.d.ts +27 -0
  145. package/dist/utils/fileUtils.d.ts.map +1 -0
  146. package/dist/utils/fileUtils.js +145 -0
  147. package/dist/utils/globalLogger.d.ts +88 -0
  148. package/dist/utils/globalLogger.d.ts.map +1 -0
  149. package/dist/utils/globalLogger.js +120 -0
  150. package/dist/utils/largeOutputHandler.d.ts +15 -0
  151. package/dist/utils/largeOutputHandler.d.ts.map +1 -0
  152. package/dist/utils/largeOutputHandler.js +40 -0
  153. package/dist/utils/markdownParser.d.ts.map +1 -1
  154. package/dist/utils/markdownParser.js +1 -17
  155. package/dist/utils/mcpUtils.d.ts.map +1 -1
  156. package/dist/utils/mcpUtils.js +25 -3
  157. package/dist/utils/messageOperations.d.ts +20 -18
  158. package/dist/utils/messageOperations.d.ts.map +1 -1
  159. package/dist/utils/messageOperations.js +30 -38
  160. package/dist/utils/pathEncoder.d.ts +108 -0
  161. package/dist/utils/pathEncoder.d.ts.map +1 -0
  162. package/dist/utils/pathEncoder.js +279 -0
  163. package/dist/utils/subagentParser.d.ts +2 -2
  164. package/dist/utils/subagentParser.d.ts.map +1 -1
  165. package/dist/utils/subagentParser.js +12 -8
  166. package/dist/utils/tokenCalculation.d.ts +26 -0
  167. package/dist/utils/tokenCalculation.d.ts.map +1 -0
  168. package/dist/utils/tokenCalculation.js +36 -0
  169. package/dist/utils/tokenEstimator.d.ts +39 -0
  170. package/dist/utils/tokenEstimator.d.ts.map +1 -0
  171. package/dist/utils/tokenEstimator.js +55 -0
  172. package/package.json +6 -6
  173. package/src/agent.ts +586 -78
  174. package/src/index.ts +4 -0
  175. package/src/managers/aiManager.ts +341 -192
  176. package/src/managers/backgroundBashManager.ts +11 -9
  177. package/src/managers/hookManager.ts +102 -54
  178. package/src/managers/liveConfigManager.ts +634 -0
  179. package/src/managers/lspManager.ts +434 -0
  180. package/src/managers/messageManager.ts +258 -121
  181. package/src/managers/permissionManager.ts +276 -0
  182. package/src/managers/skillManager.ts +3 -1
  183. package/src/managers/slashCommandManager.ts +5 -3
  184. package/src/managers/subagentManager.ts +295 -76
  185. package/src/managers/toolManager.ts +95 -3
  186. package/src/services/aiService.ts +656 -84
  187. package/src/services/configurationService.ts +762 -0
  188. package/src/services/fileWatcher.ts +300 -0
  189. package/src/services/hook.ts +54 -144
  190. package/src/services/jsonlHandler.ts +303 -0
  191. package/src/services/memory.ts +34 -11
  192. package/src/services/session.ts +522 -173
  193. package/src/tools/bashTool.ts +94 -20
  194. package/src/tools/deleteFileTool.ts +38 -1
  195. package/src/tools/editTool.ts +44 -9
  196. package/src/tools/lspTool.ts +760 -0
  197. package/src/tools/multiEditTool.ts +41 -11
  198. package/src/tools/readTool.ts +127 -3
  199. package/src/tools/skillTool.ts +2 -2
  200. package/src/tools/todoWriteTool.ts +33 -1
  201. package/src/tools/types.ts +15 -9
  202. package/src/tools/writeTool.ts +43 -16
  203. package/src/types/commands.ts +6 -1
  204. package/src/types/config.ts +5 -0
  205. package/src/types/configuration.ts +73 -0
  206. package/src/types/core.ts +55 -0
  207. package/src/types/environment.ts +104 -0
  208. package/src/types/fileSearch.ts +4 -0
  209. package/src/types/hooks.ts +32 -16
  210. package/src/types/index.ts +7 -0
  211. package/src/types/lsp.ts +96 -0
  212. package/src/types/messaging.ts +21 -14
  213. package/src/types/permissions.ts +48 -0
  214. package/src/types/session.ts +20 -0
  215. package/src/types/skills.ts +1 -0
  216. package/src/types/tools.ts +38 -0
  217. package/src/utils/abortUtils.ts +118 -0
  218. package/src/utils/bashHistory.ts +55 -31
  219. package/src/utils/builtinSubagents.ts +71 -0
  220. package/src/utils/cacheControlUtils.ts +475 -0
  221. package/src/utils/commandPathResolver.ts +189 -0
  222. package/src/utils/configPaths.ts +163 -0
  223. package/src/utils/constants.ts +2 -17
  224. package/src/utils/convertMessagesForAPI.ts +44 -18
  225. package/src/utils/customCommands.ts +90 -22
  226. package/src/utils/fileSearch.ts +107 -0
  227. package/src/utils/fileUtils.ts +160 -0
  228. package/src/utils/globalLogger.ts +128 -0
  229. package/src/utils/largeOutputHandler.ts +55 -0
  230. package/src/utils/markdownParser.ts +1 -19
  231. package/src/utils/mcpUtils.ts +34 -3
  232. package/src/utils/messageOperations.ts +47 -53
  233. package/src/utils/pathEncoder.ts +394 -0
  234. package/src/utils/subagentParser.ts +13 -9
  235. package/src/utils/tokenCalculation.ts +43 -0
  236. package/src/utils/tokenEstimator.ts +68 -0
  237. package/dist/utils/configResolver.d.ts +0 -38
  238. package/dist/utils/configResolver.d.ts.map +0 -1
  239. package/dist/utils/configResolver.js +0 -106
  240. package/src/utils/configResolver.ts +0 -142
@@ -0,0 +1,634 @@
1
+ /**
2
+ * Live Configuration Manager
3
+ *
4
+ * Orchestrates live configuration reload functionality including:
5
+ * - Hook configuration watching and reloading
6
+ * - Configuration file watching for settings.json files
7
+ * - Coordination between file watchers and configuration updates
8
+ */
9
+
10
+ import { existsSync } from "fs";
11
+ import type { Logger } from "../types/index.js";
12
+ import {
13
+ FileWatcherService,
14
+ type FileWatchEvent,
15
+ } from "../services/fileWatcher.js";
16
+ import type { HookManager } from "./hookManager.js";
17
+ import type { PermissionManager } from "./permissionManager.js";
18
+ import {
19
+ getProjectConfigPaths,
20
+ getUserConfigPaths,
21
+ } from "@/utils/configPaths.js";
22
+ import type { WaveConfiguration, ValidationResult } from "../types/hooks.js";
23
+ import { isValidHookEvent, isValidHookEventConfig } from "../types/hooks.js";
24
+ import { ConfigurationService } from "../services/configurationService.js";
25
+ import { ensureGlobalGitIgnore } from "../utils/fileUtils.js";
26
+
27
+ import type { ConfigurationLoadResult } from "../types/configuration.js";
28
+
29
+ export interface LiveConfigManagerOptions {
30
+ workdir: string;
31
+ logger?: Logger;
32
+ hookManager?: HookManager;
33
+ permissionManager?: PermissionManager;
34
+ configurationService?: ConfigurationService;
35
+ }
36
+
37
+ export class LiveConfigManager {
38
+ private readonly workdir: string;
39
+ private readonly logger?: Logger;
40
+ private readonly hookManager?: HookManager;
41
+ private readonly permissionManager?: PermissionManager;
42
+ private isInitialized: boolean = false;
43
+ private readonly configurationService: ConfigurationService;
44
+
45
+ // Configuration state
46
+ private currentConfiguration: WaveConfiguration | null = null;
47
+ private lastValidConfiguration: WaveConfiguration | null = null;
48
+
49
+ // File watching state
50
+ private fileWatcher: FileWatcherService;
51
+ private userConfigPaths?: string[];
52
+ private projectConfigPaths?: string[];
53
+ private isWatching: boolean = false;
54
+ private reloadInProgress: boolean = false;
55
+
56
+ constructor(options: LiveConfigManagerOptions) {
57
+ this.workdir = options.workdir;
58
+ this.logger = options.logger;
59
+ this.hookManager = options.hookManager;
60
+ this.permissionManager = options.permissionManager;
61
+ this.configurationService =
62
+ options.configurationService || new ConfigurationService();
63
+ this.fileWatcher = new FileWatcherService(this.logger);
64
+ this.setupFileWatcherEvents();
65
+ }
66
+
67
+ /**
68
+ * Initialize configuration watching
69
+ * Maps to FR-004: System MUST watch settings.json files
70
+ * Supports watching multiple file paths (e.g., settings.local.json and settings.json)
71
+ */
72
+ private async initializeWatching(
73
+ userPaths: string[],
74
+ projectPaths?: string[],
75
+ ): Promise<void> {
76
+ try {
77
+ this.logger?.info("Live Config: Initializing configuration watching...");
78
+
79
+ this.userConfigPaths = userPaths;
80
+ this.projectConfigPaths = projectPaths;
81
+
82
+ // Load initial configuration
83
+ await this.reloadConfiguration();
84
+
85
+ // Start watching user configs that exist
86
+ for (const userPath of userPaths) {
87
+ if (existsSync(userPath)) {
88
+ this.logger?.debug(
89
+ `Live Config: Starting to watch user config: ${userPath}`,
90
+ );
91
+ await this.fileWatcher.watchFile(userPath, (event) =>
92
+ this.handleFileChange(event, "user"),
93
+ );
94
+ } else {
95
+ this.logger?.debug(
96
+ `Live Config: User config file does not exist: ${userPath}`,
97
+ );
98
+ }
99
+ }
100
+
101
+ // Start watching project configs that exist
102
+ if (projectPaths) {
103
+ for (const projectPath of projectPaths) {
104
+ if (existsSync(projectPath)) {
105
+ if (projectPath.endsWith("settings.local.json")) {
106
+ await ensureGlobalGitIgnore("**/.wave/settings.local.json");
107
+ }
108
+ this.logger?.debug(
109
+ `Live Config: Starting to watch project config: ${projectPath}`,
110
+ );
111
+ await this.fileWatcher.watchFile(projectPath, (event) =>
112
+ this.handleFileChange(event, "project"),
113
+ );
114
+ } else {
115
+ this.logger?.debug(
116
+ `Live Config: Project config file does not exist: ${projectPath}`,
117
+ );
118
+ }
119
+ }
120
+ }
121
+
122
+ this.isWatching = true;
123
+ this.logger?.info(
124
+ "Live Config: Configuration watching initialized successfully",
125
+ );
126
+ } catch (error) {
127
+ const errorMessage = `Failed to initialize configuration watching: ${(error as Error).message}`;
128
+ this.logger?.error(`Live Config: ${errorMessage}`);
129
+ throw new Error(errorMessage);
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Get current configuration
135
+ */
136
+ getCurrentConfiguration(): WaveConfiguration | null {
137
+ return this.currentConfiguration ? { ...this.currentConfiguration } : null;
138
+ }
139
+
140
+ /**
141
+ * Initialize configuration management with file watching
142
+ */
143
+ async initialize(): Promise<void> {
144
+ if (this.isInitialized) {
145
+ this.logger?.debug("Already initialized");
146
+ return;
147
+ }
148
+
149
+ try {
150
+ // Get configuration file paths
151
+ const { userPaths, projectPaths } = this.getConfigurationPaths();
152
+
153
+ // Initialize configuration watching
154
+ await this.initializeWatching(userPaths, projectPaths);
155
+
156
+ this.isInitialized = true;
157
+ this.logger?.info(
158
+ "Live configuration management initialized with file watching",
159
+ );
160
+ } catch (error) {
161
+ this.logger?.error(`Failed to initialize: ${(error as Error).message}`);
162
+ throw error;
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Shutdown configuration management and cleanup resources
168
+ */
169
+ async shutdown(): Promise<void> {
170
+ if (!this.isInitialized) {
171
+ return;
172
+ }
173
+
174
+ try {
175
+ this.logger?.info("Live Config: Shutting down configuration manager...");
176
+
177
+ this.isWatching = false;
178
+
179
+ // Cleanup file watcher
180
+ await this.fileWatcher.cleanup();
181
+
182
+ // Clean up state
183
+ this.currentConfiguration = null;
184
+ this.lastValidConfiguration = null;
185
+
186
+ this.isInitialized = false;
187
+ this.logger?.info("Live configuration management shutdown completed");
188
+ } catch (error) {
189
+ this.logger?.error(`Error during shutdown: ${(error as Error).message}`);
190
+ throw error;
191
+ }
192
+ }
193
+
194
+ /**
195
+ * Reload configuration from files
196
+ * Maps to FR-008: Continue with previous valid configuration on errors
197
+ */
198
+ private async reloadConfiguration(): Promise<WaveConfiguration> {
199
+ if (this.reloadInProgress) {
200
+ this.logger?.debug("Live Config: Reload already in progress, skipping");
201
+ return this.currentConfiguration || {};
202
+ }
203
+
204
+ this.reloadInProgress = true;
205
+
206
+ try {
207
+ this.logger?.debug("Live Config: Reloading configuration from files...");
208
+
209
+ // Load merged configuration using ConfigurationService
210
+ const loadResult: ConfigurationLoadResult =
211
+ await this.configurationService.loadMergedConfiguration(this.workdir);
212
+ const newConfig = loadResult.configuration;
213
+
214
+ // Check for errors during loading
215
+ if (!loadResult.success) {
216
+ const errorMessage =
217
+ loadResult.error || "Configuration loading failed with unknown error";
218
+ this.logger?.error(
219
+ `Live Config: Configuration loading failed: ${errorMessage}`,
220
+ );
221
+
222
+ // Log warnings if any
223
+ if (loadResult.warnings && loadResult.warnings.length > 0) {
224
+ this.logger?.warn(
225
+ `Live Config: Configuration warnings: ${loadResult.warnings.join("; ")}`,
226
+ );
227
+ }
228
+
229
+ // Use fallback configuration if available
230
+ if (this.lastValidConfiguration) {
231
+ this.logger?.info(
232
+ "Live Config: Using previous valid configuration due to loading errors",
233
+ );
234
+ this.currentConfiguration = this.lastValidConfiguration;
235
+
236
+ // Apply environment variables to configuration service if configured
237
+ if (this.lastValidConfiguration.env) {
238
+ this.configurationService.setEnvironmentVars(
239
+ this.lastValidConfiguration.env,
240
+ );
241
+ }
242
+
243
+ // Update hook manager if available
244
+ if (this.hookManager) {
245
+ this.hookManager.loadConfigurationFromWaveConfig(
246
+ this.lastValidConfiguration,
247
+ );
248
+ }
249
+
250
+ return this.currentConfiguration;
251
+ } else {
252
+ this.logger?.warn(
253
+ "Live Config: No previous valid configuration available, using empty config",
254
+ );
255
+ this.currentConfiguration = {};
256
+ return this.currentConfiguration;
257
+ }
258
+ }
259
+
260
+ // Log success with detailed information
261
+ if (newConfig) {
262
+ this.logger?.info(
263
+ `Live Config: Configuration loaded successfully from ${loadResult.sourcePath || "merged sources"}`,
264
+ );
265
+
266
+ // Log detailed configuration info
267
+ const hookCount = Object.keys(newConfig.hooks || {}).length;
268
+ const envCount = Object.keys(newConfig.env || {}).length;
269
+ this.logger?.debug(
270
+ `Live Config: Loaded ${hookCount} hook events and ${envCount} environment variables`,
271
+ );
272
+ } else {
273
+ this.logger?.info(
274
+ "Live Config: No configuration found (using empty configuration)",
275
+ );
276
+ }
277
+
278
+ // Log warnings from successful loading
279
+ if (loadResult.warnings && loadResult.warnings.length > 0) {
280
+ this.logger?.warn(
281
+ `Live Config: Configuration warnings: ${loadResult.warnings.join("; ")}`,
282
+ );
283
+ }
284
+
285
+ // Validate new configuration if it exists
286
+ if (newConfig) {
287
+ const validation = this.validateConfiguration(newConfig);
288
+ if (!validation.valid) {
289
+ const errorMessage = `Configuration validation failed: ${validation.errors.join(", ")}`;
290
+ this.logger?.error(`Live Config: ${errorMessage}`);
291
+
292
+ // Use previous valid configuration for error recovery
293
+ if (this.lastValidConfiguration) {
294
+ this.logger?.info(
295
+ "Live Config: Using previous valid configuration due to validation errors",
296
+ );
297
+ this.currentConfiguration = this.lastValidConfiguration;
298
+
299
+ // Apply environment variables to configuration service if configured
300
+ if (this.lastValidConfiguration.env) {
301
+ this.configurationService.setEnvironmentVars(
302
+ this.lastValidConfiguration.env,
303
+ );
304
+ }
305
+
306
+ // Update hook manager if available
307
+ if (this.hookManager) {
308
+ this.hookManager.loadConfigurationFromWaveConfig(
309
+ this.lastValidConfiguration,
310
+ );
311
+ }
312
+
313
+ return this.currentConfiguration;
314
+ } else {
315
+ this.logger?.warn(
316
+ "Live Config: No previous valid configuration available, using empty config",
317
+ );
318
+ this.currentConfiguration = {};
319
+ return this.currentConfiguration;
320
+ }
321
+ }
322
+ }
323
+
324
+ // Detect changes between old and new configuration
325
+ this.detectChanges(this.currentConfiguration, newConfig);
326
+
327
+ // Update current configuration
328
+ this.currentConfiguration = newConfig || {};
329
+
330
+ // Save as last valid configuration if it's valid and not empty
331
+ if (newConfig && (newConfig.hooks || newConfig.env)) {
332
+ this.lastValidConfiguration = { ...newConfig };
333
+ this.logger?.debug(
334
+ "Live Config: Saved current configuration as last valid backup",
335
+ );
336
+ }
337
+
338
+ // Note: Environment variables are already applied by loadMergedConfiguration()
339
+ // No need to set them again here as currentConfiguration === newConfig
340
+
341
+ // Update hook manager if available
342
+ if (this.hookManager) {
343
+ this.hookManager.loadConfigurationFromWaveConfig(
344
+ this.currentConfiguration,
345
+ );
346
+ }
347
+
348
+ // Update permission manager if available
349
+ if (this.permissionManager) {
350
+ if (this.currentConfiguration.defaultMode) {
351
+ this.permissionManager.updateConfiguredDefaultMode(
352
+ this.currentConfiguration.defaultMode,
353
+ );
354
+ }
355
+ if (this.currentConfiguration.permissions?.allow) {
356
+ this.permissionManager.updateAllowedRules(
357
+ this.currentConfiguration.permissions.allow,
358
+ );
359
+ }
360
+ }
361
+
362
+ this.logger?.info(
363
+ `Live Config: Configuration reload completed successfully with ${Object.keys(newConfig?.hooks || {}).length} event types and ${Object.keys(newConfig?.env || {}).length} environment variables`,
364
+ );
365
+
366
+ return this.currentConfiguration;
367
+ } catch (error) {
368
+ const errorMessage = `Configuration reload failed with exception: ${(error as Error).message}`;
369
+ this.logger?.error(`Live Config: ${errorMessage}`);
370
+
371
+ // Use previous valid configuration for error recovery
372
+ if (this.lastValidConfiguration) {
373
+ this.logger?.info(
374
+ "Live Config: Using previous valid configuration due to reload exception",
375
+ );
376
+ this.currentConfiguration = this.lastValidConfiguration;
377
+
378
+ // Apply environment variables to configuration service if configured
379
+ if (this.lastValidConfiguration.env) {
380
+ this.configurationService.setEnvironmentVars(
381
+ this.lastValidConfiguration.env,
382
+ );
383
+ }
384
+
385
+ // Update hook manager if available
386
+ if (this.hookManager) {
387
+ this.hookManager.loadConfigurationFromWaveConfig(
388
+ this.lastValidConfiguration,
389
+ );
390
+ }
391
+ } else {
392
+ this.logger?.warn(
393
+ "Live Config: No previous valid configuration available, using empty config",
394
+ );
395
+ this.currentConfiguration = {};
396
+ }
397
+
398
+ return this.currentConfiguration;
399
+ } finally {
400
+ this.reloadInProgress = false;
401
+ }
402
+ }
403
+
404
+ /**
405
+ * Reload configuration from files (public method)
406
+ */
407
+ async reload(): Promise<WaveConfiguration> {
408
+ this.logger?.info("Manually reloading configuration...");
409
+ return await this.reloadConfiguration();
410
+ }
411
+
412
+ /**
413
+ * Check if watching is active
414
+ */
415
+ isWatchingActive(): boolean {
416
+ return this.isWatching;
417
+ }
418
+
419
+ /**
420
+ * Get watcher status for monitoring
421
+ */
422
+ getWatcherStatus() {
423
+ const statuses = this.fileWatcher.getAllWatcherStatuses();
424
+ return {
425
+ isActive: this.isWatching,
426
+ configurationLoaded: this.currentConfiguration !== null,
427
+ hasValidConfiguration: this.lastValidConfiguration !== null,
428
+ reloadInProgress: this.reloadInProgress,
429
+ watchedFiles: statuses.map((s) => ({
430
+ path: s.path,
431
+ isActive: s.isActive,
432
+ method: s.method,
433
+ errorCount: s.errorCount,
434
+ })),
435
+ };
436
+ }
437
+
438
+ private setupFileWatcherEvents(): void {
439
+ this.fileWatcher.on("watcherError", (error: Error) => {
440
+ this.logger?.error(`Live Config: File watcher error: ${error.message}`);
441
+ });
442
+ }
443
+
444
+ private async handleFileChange(
445
+ event: FileWatchEvent,
446
+ source: "user" | "project",
447
+ ): Promise<void> {
448
+ this.logger?.debug(
449
+ `Live Config: File ${event.type} detected for ${source} config: ${event.path}`,
450
+ );
451
+
452
+ try {
453
+ // Handle file deletion
454
+ if (event.type === "delete") {
455
+ this.logger?.info(
456
+ `Live Config: ${source} config file deleted: ${event.path}`,
457
+ );
458
+ // Reload configuration without the deleted file
459
+ await this.reloadConfiguration();
460
+ return;
461
+ }
462
+
463
+ // Handle file creation or modification
464
+ if (event.type === "change" || event.type === "create") {
465
+ this.logger?.info(
466
+ `Live Config: ${source} config file ${event.type}: ${event.path}`,
467
+ );
468
+
469
+ if (
470
+ source === "project" &&
471
+ event.path.endsWith("settings.local.json") &&
472
+ event.type === "create"
473
+ ) {
474
+ await ensureGlobalGitIgnore("**/.wave/settings.local.json");
475
+ }
476
+
477
+ // Add small delay to ensure file write is complete
478
+ await new Promise((resolve) => setTimeout(resolve, 50));
479
+
480
+ // Reload configuration
481
+ await this.reloadConfiguration();
482
+ }
483
+ } catch (error) {
484
+ this.logger?.error(
485
+ `Live Config: Error handling file change for ${source} config: ${(error as Error).message}`,
486
+ );
487
+ }
488
+ }
489
+
490
+ /**
491
+ * Validate configuration structure and content
492
+ */
493
+ private validateConfiguration(config: WaveConfiguration): ValidationResult {
494
+ const errors: string[] = [];
495
+
496
+ if (!config || typeof config !== "object") {
497
+ return { valid: false, errors: ["Configuration must be an object"] };
498
+ }
499
+
500
+ // Validate defaultMode if present
501
+ if (config.defaultMode !== undefined) {
502
+ if (
503
+ config.defaultMode !== "default" &&
504
+ config.defaultMode !== "bypassPermissions" &&
505
+ config.defaultMode !== "acceptEdits"
506
+ ) {
507
+ errors.push(
508
+ `Invalid defaultMode: "${config.defaultMode}". Must be "default", "bypassPermissions" or "acceptEdits"`,
509
+ );
510
+ }
511
+ }
512
+
513
+ // Validate hooks if present
514
+ if (config.hooks) {
515
+ if (typeof config.hooks !== "object") {
516
+ errors.push("hooks property must be an object");
517
+ } else {
518
+ // Validate each hook event
519
+ for (const [eventName, eventConfigs] of Object.entries(config.hooks)) {
520
+ // Validate event name
521
+ if (!isValidHookEvent(eventName)) {
522
+ errors.push(`Invalid hook event: ${eventName}`);
523
+ continue;
524
+ }
525
+
526
+ // Validate event configurations
527
+ if (!Array.isArray(eventConfigs)) {
528
+ errors.push(
529
+ `Hook event ${eventName} must be an array of configurations`,
530
+ );
531
+ continue;
532
+ }
533
+
534
+ eventConfigs.forEach((eventConfig, index) => {
535
+ if (!isValidHookEventConfig(eventConfig)) {
536
+ errors.push(
537
+ `Invalid hook event configuration at ${eventName}[${index}]`,
538
+ );
539
+ }
540
+ });
541
+ }
542
+ }
543
+ }
544
+
545
+ // Validate environment variables if present
546
+ if (config.env) {
547
+ if (typeof config.env !== "object" || Array.isArray(config.env)) {
548
+ errors.push("env property must be an object");
549
+ } else {
550
+ for (const [key, value] of Object.entries(config.env)) {
551
+ if (typeof key !== "string" || key.trim() === "") {
552
+ errors.push(`Invalid environment variable key: ${key}`);
553
+ }
554
+ if (typeof value !== "string") {
555
+ errors.push(`Environment variable ${key} must have a string value`);
556
+ }
557
+ }
558
+ }
559
+ }
560
+
561
+ return {
562
+ valid: errors.length === 0,
563
+ errors,
564
+ };
565
+ }
566
+
567
+ private detectChanges(
568
+ oldConfig: WaveConfiguration | null,
569
+ newConfig: WaveConfiguration | null,
570
+ ): {
571
+ added: string[];
572
+ modified: string[];
573
+ removed: string[];
574
+ } {
575
+ const added: string[] = [];
576
+ const modified: string[] = [];
577
+ const removed: string[] = [];
578
+
579
+ // Handle environment variables changes
580
+ const oldEnv = oldConfig?.env || {};
581
+ const newEnv = newConfig?.env || {};
582
+
583
+ for (const key of Object.keys(newEnv)) {
584
+ if (!(key in oldEnv)) {
585
+ added.push(`env.${key}`);
586
+ } else if (oldEnv[key] !== newEnv[key]) {
587
+ modified.push(`env.${key}`);
588
+ }
589
+ }
590
+
591
+ for (const key of Object.keys(oldEnv)) {
592
+ if (!(key in newEnv)) {
593
+ removed.push(`env.${key}`);
594
+ }
595
+ }
596
+
597
+ // Handle hooks changes (simplified)
598
+ const oldHooks = oldConfig?.hooks || {};
599
+ const newHooks = newConfig?.hooks || {};
600
+
601
+ for (const event of Object.keys(newHooks)) {
602
+ if (isValidHookEvent(event)) {
603
+ if (!(event in oldHooks)) {
604
+ added.push(`hooks.${event}`);
605
+ } else if (
606
+ JSON.stringify(oldHooks[event]) !== JSON.stringify(newHooks[event])
607
+ ) {
608
+ modified.push(`hooks.${event}`);
609
+ }
610
+ }
611
+ }
612
+
613
+ for (const event of Object.keys(oldHooks)) {
614
+ if (isValidHookEvent(event) && !(event in newHooks)) {
615
+ removed.push(`hooks.${event}`);
616
+ }
617
+ }
618
+
619
+ return { added, modified, removed };
620
+ }
621
+
622
+ /**
623
+ * Get configuration file paths for user and project settings
624
+ * Returns paths in priority order (local.json first, then .json)
625
+ */
626
+ private getConfigurationPaths(): {
627
+ userPaths: string[];
628
+ projectPaths: string[];
629
+ } {
630
+ const userPaths = getUserConfigPaths();
631
+ const projectPaths = getProjectConfigPaths(this.workdir);
632
+ return { userPaths, projectPaths };
633
+ }
634
+ }