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