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