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