Elffuss BraidHub

kikocis/continue public

4e263ad457a7 · 6.5 KiBRawPermalink
1import { AssistantUnrolled } from "@continuedev/config-yaml";
2import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js";
3
4import { processPromptOrRule } from "../args.js";
5import { AuthConfig, loadAuthConfig } from "../auth/workos.js";
6import { logger } from "../util/logger.js";
7
8import { BaseService, ServiceWithDependencies } from "./BaseService.js";
9import { serviceContainer } from "./ServiceContainer.js";
10import {
11 ApiClientServiceState,
12 ConfigServiceState,
13 SERVICE_NAMES,
14} from "./types.js";
15
16/**
17 * Service for managing configuration state and operations
18 * Handles loading configs from files or assistant slugs
19 */
20export class ConfigService
21 extends BaseService<ConfigServiceState>
22 implements ServiceWithDependencies
23{
24 constructor() {
25 super("ConfigService", {
26 config: null,
27 configPath: undefined,
28 });
29 }
30
31 /**
32 * Declare dependencies on other services
33 */
34 getDependencies(): string[] {
35 return [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT];
36 }
37
38 /**
39 * Initialize the config service
40 */
41 async doInitialize(
42 authConfig: AuthConfig,
43 configPath: string | undefined,
44 organizationId: string | null,
45 apiClient: DefaultApiInterface,
46 rules?: string[],
47 ): Promise<ConfigServiceState> {
48 // Use the new streamlined config loader
49 const { loadConfiguration } = await import("../configLoader.js");
50 const result = await loadConfiguration(authConfig, configPath, apiClient);
51
52 let config = result.config;
53
54 // Inject rules if provided
55 if (rules && rules.length > 0) {
56 config = await this.injectRulesIntoConfig(config, rules);
57 }
58
59 // Config URI persistence is now handled by the streamlined loader
60
61 logger.debug("ConfigService initialized successfully");
62
63 return {
64 config,
65 configPath,
66 };
67 }
68
69 /**
70 * Switch to a new configuration
71 */
72 async switchConfig(
73 newConfigPath: string,
74 authConfig: AuthConfig,
75 organizationId: string | null,
76 apiClient: DefaultApiInterface,
77 rules?: string[],
78 ): Promise<ConfigServiceState> {
79 logger.debug("Switching configuration", {
80 from: this.currentState.configPath,
81 to: newConfigPath,
82 });
83
84 try {
85 // Use the new streamlined config loader
86 const { loadConfiguration } = await import("../configLoader.js");
87 const result = await loadConfiguration(
88 authConfig,
89 newConfigPath,
90 apiClient,
91 );
92
93 let config = result.config;
94
95 // Inject rules if provided
96 if (rules && rules.length > 0) {
97 config = await this.injectRulesIntoConfig(config, rules);
98 }
99
100 this.setState({
101 config,
102 configPath: newConfigPath,
103 });
104
105 // Config URI persistence is now handled by the streamlined loader
106
107 logger.debug("Configuration switched successfully", {
108 newConfigPath,
109 });
110
111 return this.getState();
112 } catch (error: any) {
113 logger.error("Failed to switch configuration:", error);
114 this.emit("error", error);
115 throw error;
116 }
117 }
118
119 /**
120 * Reload the current configuration
121 */
122 async reload(
123 authConfig: AuthConfig,
124 organizationId: string | null,
125 apiClient: DefaultApiInterface,
126 rules?: string[],
127 ): Promise<ConfigServiceState> {
128 if (!this.currentState.configPath) {
129 throw new Error("No configuration path available for reload");
130 }
131
132 logger.debug("Reloading current configuration");
133
134 return this.switchConfig(
135 this.currentState.configPath,
136 authConfig,
137 organizationId,
138 apiClient,
139 rules,
140 );
141 }
142
143 /**
144 * Process rules and inject them into the assistant config
145 */
146 private async injectRulesIntoConfig(
147 config: AssistantUnrolled,
148 rules: string[],
149 ): Promise<AssistantUnrolled> {
150 if (!rules || rules.length === 0) {
151 return config;
152 }
153
154 const processedRules: string[] = [];
155
156 for (const ruleSpec of rules) {
157 try {
158 const processedRule = await processPromptOrRule(ruleSpec);
159 processedRules.push(processedRule);
160 } catch (error: any) {
161 logger.warn(`Failed to process rule "${ruleSpec}": ${error.message}`);
162 }
163 }
164
165 if (processedRules.length === 0) {
166 return config;
167 }
168
169 // Clone the config to avoid mutating the original
170 const modifiedConfig = { ...config };
171
172 // Combine processed rules with existing system message if the config has one
173 const existingSystemMessage = (modifiedConfig as any).systemMessage || "";
174 const rulesSection = processedRules.join("\n\n");
175
176 if (existingSystemMessage) {
177 (modifiedConfig as any).systemMessage =
178 `${existingSystemMessage}\n\n${rulesSection}`;
179 } else {
180 (modifiedConfig as any).systemMessage = rulesSection;
181 }
182
183 return modifiedConfig;
184 }
185
186 /**
187 * Update the configuration path and notify the service container
188 * This triggers automatic dependent service reloads via the reactive system
189 */
190 async updateConfigPath(newConfigPath: string | undefined): Promise<void> {
191 logger.debug("Updating config path", {
192 from: this.currentState.configPath,
193 to: newConfigPath,
194 });
195
196 try {
197 // Get current auth and API client state needed for config loading
198 const authConfig = loadAuthConfig();
199 const apiClientState = await serviceContainer.get<ApiClientServiceState>(
200 SERVICE_NAMES.API_CLIENT,
201 );
202
203 if (!apiClientState.apiClient) {
204 throw new Error("API client not available");
205 }
206
207 // Load the new configuration using streamlined loader
208 const { loadConfiguration } = await import("../configLoader.js");
209 const result = await loadConfiguration(
210 authConfig,
211 newConfigPath,
212 apiClientState.apiClient,
213 );
214
215 // Update internal state
216 this.setState({
217 config: result.config,
218 configPath: newConfigPath,
219 });
220
221 // Config URI persistence is now handled by the streamlined loader
222
223 // Update the CONFIG service in the container
224 serviceContainer.set(SERVICE_NAMES.CONFIG, this.getState());
225
226 // Manually reload dependent services (MODEL, MCP) to pick up the new config
227 await serviceContainer.reload(SERVICE_NAMES.MODEL);
228 await serviceContainer.reload(SERVICE_NAMES.MCP);
229
230 logger.debug("Configuration path updated successfully", {
231 newConfigPath,
232 configName: result.config.name,
233 });
234 } catch (error: any) {
235 logger.error("Failed to update configuration path:", error);
236 this.emit("error", error);
237 throw error;
238 }
239 }
240}