Elffuss BraidHub

kikocis/continue public

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