Elffuss BraidHub

kikocis/continue public

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