Elffuss BraidHub

kikocis/continue public

ea05c35331da · 10.2 KiBRawPermalink
1import { loadAuthConfig } from "../auth/workos.js";
2import { initializeWithOnboarding } from "../onboarding.js";
3import { logger } from "../util/logger.js";
4
5import { ApiClientService } from "./ApiClientService.js";
6import { AuthService } from "./AuthService.js";
7import { ChatHistoryService } from "./ChatHistoryService.js";
8import { ConfigService } from "./ConfigService.js";
9import { FileIndexService } from "./FileIndexService.js";
10import { MCPService } from "./MCPService.js";
11import { ModelService } from "./ModelService.js";
12import { modeService } from "./ModeService.js";
13import { ResourceMonitoringService } from "./ResourceMonitoringService.js";
14import { serviceContainer } from "./ServiceContainer.js";
15import { systemMessageService } from "./SystemMessageService.js";
16import {
17 ApiClientServiceState,
18 AuthServiceState,
19 ConfigServiceState,
20 SERVICE_NAMES,
21 ServiceInitOptions,
22 ServiceInitResult,
23} from "./types.js";
24
25// Service instances
26const authService = new AuthService();
27const configService = new ConfigService();
28const modelService = new ModelService();
29const apiClientService = new ApiClientService();
30const mcpService = new MCPService();
31const fileIndexService = new FileIndexService();
32const resourceMonitoringService = new ResourceMonitoringService();
33const chatHistoryService = new ChatHistoryService();
34
35/**
36 * Initialize all services and register them with the service container
37 * Handles onboarding internally for TUI mode unless skipOnboarding is true
38 */
39export async function initializeServices(
40 initOptions: ServiceInitOptions = {},
41): Promise<ServiceInitResult> {
42 logger.debug("Initializing service registry");
43
44 let wasOnboarded = false;
45 const commandOptions = initOptions.options || {};
46
47 // Handle onboarding for TUI mode (headless: false) unless explicitly skipped
48 if (!initOptions.headless && !initOptions.skipOnboarding) {
49 const authConfig = loadAuthConfig();
50 const onboardingResult = await initializeWithOnboarding(
51 authConfig,
52 commandOptions.config,
53 commandOptions.rule,
54 );
55 wasOnboarded = onboardingResult.wasOnboarded;
56 }
57
58 // Handle ANTHROPIC_API_KEY in headless mode when no config path is provided
59 if (
60 initOptions.headless &&
61 !commandOptions.config &&
62 process.env.ANTHROPIC_API_KEY
63 ) {
64 const { createOrUpdateConfig } = await import("../onboarding.js");
65 const { env } = await import("../env.js");
66 const path = await import("path");
67
68 const CONFIG_PATH = path.join(env.continueHome, "config.yaml");
69 await createOrUpdateConfig(process.env.ANTHROPIC_API_KEY);
70
71 // Update options to use the created config
72 commandOptions.config = CONFIG_PATH;
73 }
74
75 // Initialize mode service with tool permission overrides
76 if (initOptions.toolPermissionOverrides) {
77 const overrides = { ...initOptions.toolPermissionOverrides };
78
79 // Convert mode to boolean flags for ModeService
80 const initArgs: Parameters<typeof modeService.initialize>[0] = {
81 allow: overrides.allow,
82 ask: overrides.ask,
83 exclude: overrides.exclude,
84 isHeadless: initOptions.headless,
85 };
86
87 // Only set the boolean flag that corresponds to the mode
88 if (overrides.mode === "plan") {
89 initArgs.readonly = true;
90 } else if (overrides.mode === "auto") {
91 initArgs.auto = true;
92 }
93 // If mode is "normal" or undefined, no flags are set
94
95 await modeService.initialize(initArgs);
96 } else {
97 // Even if no overrides, we need to initialize with defaults
98 await modeService.initialize({
99 isHeadless: initOptions.headless,
100 });
101 }
102
103 // Register the TOOL_PERMISSIONS service with immediate value
104 // Since ToolPermissionService is already initialized synchronously in ModeService,
105 // we can register it as a ready value instead of a factory
106 const toolPermissionState = modeService.getToolPermissionService().getState();
107 logger.debug("Registering TOOL_PERMISSIONS with state:", {
108 currentMode: toolPermissionState.currentMode,
109 isHeadless: toolPermissionState.isHeadless,
110 policyCount: toolPermissionState.permissions.policies.length,
111 });
112 serviceContainer.registerValue(
113 SERVICE_NAMES.TOOL_PERMISSIONS,
114 toolPermissionState,
115 );
116
117 // Initialize SystemMessageService with command options
118 serviceContainer.register(
119 SERVICE_NAMES.SYSTEM_MESSAGE,
120 () =>
121 systemMessageService.initialize({
122 additionalRules: commandOptions.rule,
123 format: (commandOptions as any).format, // format option from CLI
124 headless: initOptions.headless,
125 }),
126 [], // No dependencies
127 );
128
129 serviceContainer.register(
130 SERVICE_NAMES.AUTH,
131 () => authService.initialize(),
132 [], // No dependencies
133 );
134
135 serviceContainer.register(
136 SERVICE_NAMES.API_CLIENT,
137 async () => {
138 const authState = await serviceContainer.get<AuthServiceState>(
139 SERVICE_NAMES.AUTH,
140 );
141 return apiClientService.initialize(authState.authConfig);
142 },
143 [SERVICE_NAMES.AUTH], // Depends on auth
144 );
145
146 serviceContainer.register(
147 SERVICE_NAMES.CONFIG,
148 async () => {
149 const [authState, apiClientState] = await Promise.all([
150 serviceContainer.get<AuthServiceState>(SERVICE_NAMES.AUTH),
151 serviceContainer.get<ApiClientServiceState>(SERVICE_NAMES.API_CLIENT),
152 ]);
153
154 // Ensure organization is selected if authenticated
155 let finalAuthState = authState;
156 if (authState.authConfig) {
157 finalAuthState = await authService.ensureOrganization(
158 initOptions.headless ?? false,
159 commandOptions.org,
160 );
161 // Update the auth service state in container
162 serviceContainer.set(SERVICE_NAMES.AUTH, finalAuthState);
163 }
164
165 if (!apiClientState.apiClient) {
166 throw new Error("API client not available");
167 }
168
169 // Use current config path from ConfigService state if available (for reloads),
170 // otherwise use initial options.config (for first initialization)
171 // IMPORTANT: Always prefer explicit --config flag over saved state
172 const currentState = configService.getState();
173 let configPath =
174 commandOptions.config ||
175 (currentState.configPath === undefined
176 ? undefined
177 : currentState.configPath);
178
179 // If no config path is available, check for saved config URI in auth config
180 if (!configPath) {
181 const { getConfigUri } = await import("../auth/workos.js");
182 const { uriToPath, uriToSlug } = await import("../auth/uriUtils.js");
183 const configUri = getConfigUri(finalAuthState.authConfig);
184 if (configUri) {
185 const filePath = uriToPath(configUri);
186 const slug = uriToSlug(configUri);
187 configPath = filePath || slug || undefined;
188 }
189 }
190
191 return configService.initialize(
192 finalAuthState.authConfig,
193 configPath,
194 finalAuthState.organizationId || null,
195 apiClientState.apiClient,
196 commandOptions,
197 );
198 },
199 [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT], // Depends on auth and API client
200 );
201
202 serviceContainer.register(
203 SERVICE_NAMES.MODEL,
204 async () => {
205 const [configState, authState] = await Promise.all([
206 serviceContainer.get<ConfigServiceState>(SERVICE_NAMES.CONFIG),
207 serviceContainer.get<AuthServiceState>(SERVICE_NAMES.AUTH),
208 ]);
209
210 if (!configState.config) {
211 throw new Error("Config not available");
212 }
213
214 return modelService.initialize(configState.config, authState.authConfig);
215 },
216 [SERVICE_NAMES.CONFIG, SERVICE_NAMES.AUTH], // Depends on config and auth
217 );
218
219 serviceContainer.register(
220 SERVICE_NAMES.MCP,
221 async () => {
222 const configState = await serviceContainer.get<ConfigServiceState>(
223 SERVICE_NAMES.CONFIG,
224 );
225
226 if (!configState.config) {
227 throw new Error("Config not available for MCP service");
228 }
229 return mcpService.initialize(configState.config, initOptions.headless);
230 },
231 [SERVICE_NAMES.CONFIG], // Depends on config
232 );
233
234 serviceContainer.register(
235 SERVICE_NAMES.FILE_INDEX,
236 () => fileIndexService.initialize(),
237 [],
238 );
239
240 serviceContainer.register(
241 SERVICE_NAMES.RESOURCE_MONITORING,
242 () => resourceMonitoringService.initialize(),
243 [],
244 );
245
246 serviceContainer.register(
247 SERVICE_NAMES.CHAT_HISTORY,
248 () => chatHistoryService.initialize(undefined, initOptions.headless),
249 [], // No dependencies for now, but could depend on SESSION in future
250 );
251
252 // Eagerly initialize all services to ensure they're ready when needed
253 // This avoids race conditions and "service not ready" errors
254 await serviceContainer.initializeAll();
255
256 logger.debug("Service registry initialized");
257
258 return { wasOnboarded };
259}
260
261/**
262 * Get a service from the container (async)
263 */
264export function getService<T>(serviceName: string): Promise<T> {
265 return serviceContainer.get<T>(serviceName);
266}
267
268/**
269 * Get service state synchronously
270 */
271export function getServiceSync<T>(serviceName: string) {
272 return serviceContainer.getSync<T>(serviceName);
273}
274
275/**
276 * Reload a specific service
277 */
278export function reloadService(serviceName: string) {
279 return serviceContainer.reload(serviceName);
280}
281
282/**
283 * Check if all core services are ready
284 */
285export function areServicesReady(): boolean {
286 return [
287 SERVICE_NAMES.TOOL_PERMISSIONS,
288 SERVICE_NAMES.AUTH,
289 SERVICE_NAMES.API_CLIENT,
290 SERVICE_NAMES.CONFIG,
291 SERVICE_NAMES.MODEL,
292 SERVICE_NAMES.MCP,
293 SERVICE_NAMES.FILE_INDEX,
294 SERVICE_NAMES.RESOURCE_MONITORING,
295 SERVICE_NAMES.CHAT_HISTORY,
296 ].every((name) => serviceContainer.isReady(name));
297}
298
299/**
300 * Get service states for debugging
301 */
302export function getServiceStates() {
303 return serviceContainer.getServiceStates();
304}
305
306/**
307 * Direct access to service instances for complex operations
308 */
309export const services = {
310 auth: authService,
311 config: configService,
312 model: modelService,
313 apiClient: apiClientService,
314 mcp: mcpService,
315 fileIndex: fileIndexService,
316 mode: modeService,
317 resourceMonitoring: resourceMonitoringService,
318 systemMessage: systemMessageService,
319 chatHistory: chatHistoryService,
320} as const;
321
322// Export the service container for advanced usage
323export { serviceContainer };
324
325// Export service names and types
326export type * from "./types.js";
327export { SERVICE_NAMES } from "./types.js";