Elffuss BraidHub

kikocis/continue public

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