diff --git a/REFACTOR_PLAN.md b/REFACTOR_PLAN.md new file mode 100644 index 000000000..e670f3187 --- /dev/null +++ b/REFACTOR_PLAN.md @@ -0,0 +1,203 @@ +# Reactive Service Architecture Refactoring Plan + +## Problem Statement + +The current codebase has tightly coupled dependencies (config, apiClient, MCP service, model, etc.) that require full reloads when any component changes. This causes: + +1. **Slow startup**: TUI can't start until all components are loaded +2. **Poor UX**: Slash commands like `/org`, `/config` trigger complete restarts +3. **Tight coupling**: Can't change individual components without reloading everything +4. **Blocking initialization**: All dependencies must load before anything works + +## Solution Overview + +Implement a **Reactive Service Architecture** using: +- Custom ServiceContainer with Node.js EventEmitter +- React hooks for service consumption +- Progressive loading and error handling +- Independent service lifecycle management + +## Current Architecture Analysis + +### Key Components to Refactor +- **Config Management** (`src/config.ts`, `src/onboarding.ts`) +- **Authentication** (`src/auth/workos.ts`) +- **LLM/Model handling** (`src/config.ts` - `initializeLlmApi()`) +- **MCP Service** (`src/mcp.ts`) +- **API Client** (`src/CLIPlatformClient.ts`) + +### Current Initialization Flow +``` +chat() -> initializeChat() -> initializeWithOnboarding() -> initialize() + -> Returns: { config, llmApi, model, mcpService, apiClient } + -> startTUIChat() with all dependencies +``` + +### Current Problem Areas +- `src/commands/chat.ts` - `initializeChat()` loads everything synchronously +- `src/ui/index.ts` - `startTUIChat()` requires all deps upfront +- `src/slashCommands.ts` - `/config`, `/login` trigger full reloads via `onReload()` +- `src/ui/TUIChat.tsx` - Assumes all services are available at startup + +## Implementation Strategy + +### Phase 1: Extract Current Initialization into Services ✅ TODO +Create the service infrastructure and extract existing initialization logic. + +#### 1.1 Create Service Infrastructure +- [ ] Create `src/services/ServiceContainer.ts` - Core service management +- [ ] Create `src/hooks/useService.ts` - React hook for service consumption +- [ ] Create `src/services/types.ts` - Service-related TypeScript types + +#### 1.2 Create Individual Services +- [ ] Create `src/services/AuthService.ts` - Extract auth logic from `src/auth/workos.ts` +- [ ] Create `src/services/ConfigService.ts` - Extract config logic from `src/config.ts` +- [ ] Create `src/services/ModelService.ts` - Extract model initialization +- [ ] Create `src/services/MCPService.ts` - Extract MCP logic from `src/mcp.ts` +- [ ] Create `src/services/ApiClientService.ts` - Extract API client management + +#### 1.3 Create Service Registry +- [ ] Create `src/services/index.ts` - Central service registry and initialization +- [ ] Add service dependency management (e.g., ModelService depends on ConfigService) + +### Phase 2: Make TUI Reactive to Service Changes ✅ TODO +Update the TUI to consume services reactively instead of requiring all deps upfront. + +#### 2.1 Update TUI Components +- [ ] Update `src/ui/TUIChat.tsx` - Use `useService` hooks instead of props +- [ ] Add loading states for individual services +- [ ] Add error boundaries for service failures +- [ ] Remove service props from component interface + +#### 2.2 Update TUI Entry Point +- [ ] Update `src/ui/index.ts` - Remove dependency injection, just start TUI +- [ ] Update `src/commands/chat.ts` - Start TUI immediately, services load async + +#### 2.3 Handle Service Dependencies in UI +- [ ] Show progressive loading (e.g., "Config loaded, loading model...") +- [ ] Handle missing services gracefully +- [ ] Allow partial functionality when some services unavailable + +### Phase 3: Update Slash Commands to Use Services ✅ TODO +Make slash commands reactive by updating services instead of triggering reloads. + +#### 3.1 Update Slash Command Handlers +- [ ] Update `src/slashCommands.ts` - Remove `onReload` callback pattern +- [ ] Update `/config` command to use ConfigService.switchConfig() +- [ ] Update `/login` command to use AuthService.login() +- [ ] Update `/logout` command to use AuthService.logout() +- [ ] Add `/org` command to use AuthService.switchOrg() + +#### 3.2 Remove Reload Mechanisms +- [ ] Remove `onReload` callbacks from TUIChat +- [ ] Remove full restart logic from slash commands +- [ ] Services now auto-propagate changes to UI + +### Phase 4: Add Progressive Loading and Better Error Handling ✅ TODO +Enhance the user experience with better loading states and error recovery. + +#### 4.1 Enhanced Loading States +- [ ] Add service loading indicators in TUI +- [ ] Show which services are loading/ready +- [ ] Allow using available functionality while other services load + +#### 4.2 Error Handling and Recovery +- [ ] Add retry mechanisms for failed service initialization +- [ ] Add service health monitoring +- [ ] Graceful degradation when services fail +- [ ] Better error messages for specific service failures + +#### 4.3 Performance Optimizations +- [ ] Lazy load services only when needed +- [ ] Cache service results appropriately +- [ ] Debounce rapid service changes + +## File Changes Required + +### New Files +- `src/services/ServiceContainer.ts` +- `src/services/types.ts` +- `src/services/AuthService.ts` +- `src/services/ConfigService.ts` +- `src/services/ModelService.ts` +- `src/services/MCPService.ts` +- `src/services/ApiClientService.ts` +- `src/services/index.ts` +- `src/hooks/useService.ts` + +### Modified Files +- `src/commands/chat.ts` - Remove synchronous initialization +- `src/ui/index.ts` - Remove dependency injection +- `src/ui/TUIChat.tsx` - Use service hooks instead of props +- `src/slashCommands.ts` - Use services instead of reload callbacks +- `src/onboarding.ts` - Integrate with service architecture + +### Files to Analyze for Extraction +- `src/config.ts` - Extract initialization logic +- `src/auth/workos.ts` - Extract auth management +- `src/mcp.ts` - Extract MCP service logic + +## Success Criteria + +### Phase 1 Success +- [ ] Services can be initialized independently +- [ ] Existing functionality works through service layer +- [ ] No breaking changes to current behavior + +### Phase 2 Success +- [ ] TUI starts immediately without waiting for all services +- [ ] UI updates reactively when services load/change +- [ ] Loading states provide clear user feedback + +### Phase 3 Success +- [ ] Slash commands work without full reloads +- [ ] `/config` and `/login` commands update UI instantly +- [ ] No more blocking reinitialization + +### Phase 4 Success +- [ ] Better error handling for service failures +- [ ] Progressive enhancement - partial functionality available +- [ ] Improved startup performance + +## Testing Strategy + +### Unit Tests +- [ ] Test each service in isolation +- [ ] Test service dependencies and lifecycle +- [ ] Test React hooks with service changes + +### Integration Tests +- [ ] Test service interactions +- [ ] Test UI updates with service changes +- [ ] Test slash command service updates + +### E2E Tests +- [ ] Test full user flows with new architecture +- [ ] Test error recovery scenarios +- [ ] Test performance improvements + +## Migration Strategy + +1. **Backward Compatibility**: Ensure existing functionality works during transition +2. **Incremental Migration**: Each phase should be deployable independently +3. **Rollback Plan**: Keep old initialization as fallback during Phase 1-2 +4. **Monitoring**: Add logging to track service lifecycle and performance + +## Risk Mitigation + +### Technical Risks +- **Service dependency cycles**: Use dependency injection pattern +- **Memory leaks**: Proper EventEmitter cleanup in React hooks +- **Race conditions**: Use proper async/await patterns in services + +### User Experience Risks +- **Broken functionality during migration**: Extensive testing at each phase +- **Performance regressions**: Benchmark before/after each phase +- **Confusing loading states**: Clear UX design for progressive loading + +## Notes + +- Start with Phase 1 to establish the foundation +- Each phase should be fully tested before proceeding +- Consider feature flags for gradual rollout +- Document service APIs clearly for future development \ No newline at end of file diff --git a/src/hooks/useService.ts b/src/hooks/useService.ts new file mode 100644 index 000000000..a66be5153 --- /dev/null +++ b/src/hooks/useService.ts @@ -0,0 +1,167 @@ +import { useEffect, useState } from 'react'; +import { serviceContainer } from '../services/ServiceContainer.js'; +import { ServiceResult } from '../services/types.js'; + +/** + * React hook for consuming services reactively + * Automatically subscribes to service changes and provides loading/error states + */ +export function useService(serviceName: string): ServiceResult & { + reload: () => Promise; +} { + const [result, setResult] = useState>(() => + serviceContainer.getSync(serviceName) + ); + + useEffect(() => { + // Get initial state + const initialResult = serviceContainer.getSync(serviceName); + setResult(initialResult); + + // Auto-load if idle + if (initialResult.state === 'idle') { + serviceContainer.load(serviceName).catch(() => { + // Error is handled by the service container and will trigger the error event + }); + } + + // Set up event listeners + const onLoading = () => { + setResult(prev => ({ ...prev, state: 'loading', error: null })); + }; + + const onReady = (value: T) => { + setResult({ + value, + state: 'ready', + error: null, + lastUpdated: new Date() + }); + }; + + const onError = (error: Error) => { + setResult(prev => ({ + ...prev, + state: 'error', + error, + lastUpdated: new Date() + })); + }; + + const onChanged = (value: T) => { + setResult(prev => ({ + ...prev, + value, + error: null, + lastUpdated: new Date() + })); + }; + + // Subscribe to events + serviceContainer.on(`${serviceName}:loading`, onLoading); + serviceContainer.on(`${serviceName}:ready`, onReady); + serviceContainer.on(`${serviceName}:error`, onError); + serviceContainer.on(`${serviceName}:changed`, onChanged); + + // Cleanup + return () => { + serviceContainer.off(`${serviceName}:loading`, onLoading); + serviceContainer.off(`${serviceName}:ready`, onReady); + serviceContainer.off(`${serviceName}:error`, onError); + serviceContainer.off(`${serviceName}:changed`, onChanged); + }; + }, [serviceName]); + + const reload = async (): Promise => { + await serviceContainer.reload(serviceName); + }; + + return { + ...result, + reload + }; +} + +/** + * Hook for consuming multiple services + */ +export function useServices>( + serviceNames: (keyof T)[] +): { + services: Partial; + loading: boolean; + error: Error | null; + allReady: boolean; +} { + const [services, setServices] = useState>({}); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + + useEffect(() => { + const updateState = () => { + const newServices: Partial = {}; + let hasLoading = false; + let hasError: Error | null = null; + let allReady = true; + + for (const serviceName of serviceNames) { + const result = serviceContainer.getSync(serviceName as string); + + if (result.state === 'loading') { + hasLoading = true; + allReady = false; + } else if (result.state === 'error') { + hasError = result.error; + allReady = false; + } else if (result.state === 'idle') { + allReady = false; + // Auto-load idle services + serviceContainer.load(serviceName as string).catch(() => {}); + } else if (result.state === 'ready' && result.value !== null) { + newServices[serviceName] = result.value as T[keyof T]; + } else { + allReady = false; + } + } + + setServices(newServices); + setLoading(hasLoading); + setError(hasError); + }; + + // Initial state + updateState(); + + // Set up listeners for all services + const listeners: Array<() => void> = []; + + for (const serviceName of serviceNames) { + const name = serviceName as string; + + const onAnyChange = () => updateState(); + + serviceContainer.on(`${name}:loading`, onAnyChange); + serviceContainer.on(`${name}:ready`, onAnyChange); + serviceContainer.on(`${name}:error`, onAnyChange); + serviceContainer.on(`${name}:changed`, onAnyChange); + + listeners.push(() => { + serviceContainer.off(`${name}:loading`, onAnyChange); + serviceContainer.off(`${name}:ready`, onAnyChange); + serviceContainer.off(`${name}:error`, onAnyChange); + serviceContainer.off(`${name}:changed`, onAnyChange); + }); + } + + // Cleanup + return () => { + listeners.forEach(cleanup => cleanup()); + }; + }, [serviceNames.join(',')]); + + const allReady = serviceNames.every(name => + serviceContainer.isReady(name as string) + ); + + return { services, loading, error, allReady }; +} \ No newline at end of file diff --git a/src/services/ApiClientService.ts b/src/services/ApiClientService.ts new file mode 100644 index 000000000..957a8d022 --- /dev/null +++ b/src/services/ApiClientService.ts @@ -0,0 +1,70 @@ +import { AuthConfig } from "../auth/workos.js"; +import { getApiClient } from "../config.js"; +import logger from "../util/logger.js"; +import { ApiClientServiceState } from "./types.js"; + +/** + * Service for managing API client state + * Provides access to the Continue SDK API client + */ +export class ApiClientService { + private currentState: ApiClientServiceState = { + apiClient: null, + }; + + /** + * Initialize the API client service + */ + async initialize(authConfig: AuthConfig): Promise { + logger.debug("Initializing ApiClientService"); + + try { + const apiClient = getApiClient(authConfig?.accessToken); + + this.currentState = { + apiClient, + }; + + logger.debug("ApiClientService initialized successfully"); + return this.currentState; + } catch (error: any) { + logger.error("Failed to initialize ApiClientService:", error); + throw error; + } + } + + /** + * Get current API client state + */ + getState(): ApiClientServiceState { + return { ...this.currentState }; + } + + /** + * Update the API client with new auth config + */ + async update(authConfig: AuthConfig): Promise { + logger.debug("Updating ApiClientService"); + + try { + const apiClient = getApiClient(authConfig?.accessToken); + + this.currentState = { + apiClient, + }; + + logger.debug("ApiClientService updated successfully"); + return this.currentState; + } catch (error: any) { + logger.error("Failed to update ApiClientService:", error); + throw error; + } + } + + /** + * Check if the API client is ready + */ + isReady(): boolean { + return this.currentState.apiClient !== null; + } +} diff --git a/src/services/AuthService.ts b/src/services/AuthService.ts new file mode 100644 index 000000000..d2a9fc320 --- /dev/null +++ b/src/services/AuthService.ts @@ -0,0 +1,208 @@ +import { + AuthenticatedConfig, + login as doLogin, + logout as doLogout, + ensureOrganization, + isAuthenticated, + listUserOrganizations, + loadAuthConfig, + saveAuthConfig, +} from "../auth/workos.js"; +import logger from "../util/logger.js"; +import { AuthServiceState } from "./types.js"; + +/** + * Service for managing authentication state and operations + * Encapsulates all auth logic and provides reactive updates + */ +export class AuthService { + private currentState: AuthServiceState = { + authConfig: null, + isAuthenticated: false, + }; + + /** + * Initialize the auth service by loading current config + */ + async initialize(): Promise { + logger.debug("Initializing AuthService"); + + const authConfig = loadAuthConfig(); + const authenticated = isAuthenticated(); + + this.currentState = { + authConfig, + isAuthenticated: authenticated, + organizationId: authConfig?.organizationId || undefined, + }; + + logger.debug("AuthService initialized", { + authenticated, + hasConfig: !!authConfig, + orgId: this.currentState.organizationId, + }); + + return this.currentState; + } + + /** + * Get current auth state + */ + getState(): AuthServiceState { + return { ...this.currentState }; + } + + /** + * Perform login flow + */ + async login(): Promise { + logger.debug("Starting login flow"); + + try { + const newAuthConfig = await doLogin(); + + this.currentState = { + authConfig: newAuthConfig, + isAuthenticated: true, + organizationId: newAuthConfig?.organizationId || undefined, + }; + + logger.debug("Login successful", { + orgId: this.currentState.organizationId, + }); + + return this.currentState; + } catch (error: any) { + logger.error("Login failed:", error); + throw error; + } + } + + /** + * Perform logout + */ + async logout(): Promise { + logger.debug("Logging out"); + + doLogout(); + + this.currentState = { + authConfig: null, + isAuthenticated: false, + organizationId: undefined, + }; + + logger.debug("Logout complete"); + return this.currentState; + } + + /** + * Ensure organization is selected, prompting if necessary + */ + async ensureOrganization( + isHeadless: boolean = false + ): Promise { + if (!this.currentState.authConfig) { + throw new Error("Not authenticated - cannot ensure organization"); + } + + logger.debug("Ensuring organization is selected", { + currentOrgId: this.currentState.organizationId, + isHeadless, + }); + + const updatedConfig = await ensureOrganization( + this.currentState.authConfig, + isHeadless + ); + + this.currentState = { + authConfig: updatedConfig, + isAuthenticated: true, + organizationId: updatedConfig?.organizationId || undefined, + }; + + logger.debug("Organization ensured", { + orgId: this.currentState.organizationId, + }); + + return this.currentState; + } + + /** + * Switch to a different organization + */ + async switchOrganization( + organizationId: string | null + ): Promise { + if ( + !this.currentState.authConfig || + !("userId" in this.currentState.authConfig) + ) { + throw new Error( + "Not authenticated with file-based auth - cannot switch organizations" + ); + } + + logger.debug("Switching organization", { + from: this.currentState.organizationId, + to: organizationId, + }); + + const authenticatedConfig = this.currentState + .authConfig as AuthenticatedConfig; + + const updatedConfig: AuthenticatedConfig = { + ...authenticatedConfig, + organizationId, + }; + + saveAuthConfig(updatedConfig); + + this.currentState = { + authConfig: updatedConfig, + isAuthenticated: true, + organizationId: organizationId || undefined, + }; + + logger.debug("Organization switched", { + newOrgId: this.currentState.organizationId, + }); + + return this.currentState; + } + + /** + * Get available organizations for the current user + */ + async getAvailableOrganizations(): Promise< + { id: string; name: string }[] | null + > { + if (!this.currentState.isAuthenticated) { + return null; + } + + try { + return await listUserOrganizations(); + } catch (error: any) { + logger.error("Failed to list organizations:", error); + return null; + } + } + + /** + * Check if the current user has multiple organizations available + */ + async hasMultipleOrganizations(): Promise { + const orgs = await this.getAvailableOrganizations(); + return orgs !== null && orgs.length > 0; + } + + /** + * Refresh auth state from disk (useful after external changes) + */ + async refresh(): Promise { + logger.debug("Refreshing auth state from disk"); + return this.initialize(); + } +} diff --git a/src/services/ConfigService.ts b/src/services/ConfigService.ts new file mode 100644 index 000000000..3848ef503 --- /dev/null +++ b/src/services/ConfigService.ts @@ -0,0 +1,184 @@ +import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; +import { loadConfig } from '../config.js'; +import { AuthConfig, updateAssistantSlug } from '../auth/workos.js'; +import logger from '../util/logger.js'; +import { ConfigServiceState } from './types.js'; + +/** + * Service for managing configuration state and operations + * Handles loading configs from files or assistant slugs + */ +export class ConfigService { + private currentState: ConfigServiceState = { + config: null, + configPath: undefined + }; + + /** + * Initialize the config service + */ + async initialize( + authConfig: AuthConfig, + configPath: string | undefined, + organizationId: string | null, + apiClient: DefaultApiInterface, + rules?: string[] + ): Promise { + logger.debug('Initializing ConfigService', { configPath, organizationId }); + + try { + let config = await loadConfig(authConfig, configPath, organizationId, apiClient); + + // Inject rules if provided + if (rules && rules.length > 0) { + config = await this.injectRulesIntoConfig(config, rules); + } + + this.currentState = { + config, + configPath + }; + + // Save assistant slug to auth config if loading by slug + if (configPath && !this.isFilePath(configPath)) { + updateAssistantSlug(configPath); + } + + logger.debug('ConfigService initialized successfully'); + return this.currentState; + } catch (error: any) { + logger.error('Failed to initialize ConfigService:', error); + throw error; + } + } + + /** + * Get current config state + */ + getState(): ConfigServiceState { + return { ...this.currentState }; + } + + /** + * Switch to a new configuration + */ + async switchConfig( + newConfigPath: string, + authConfig: AuthConfig, + organizationId: string | null, + apiClient: DefaultApiInterface, + rules?: string[] + ): Promise { + logger.debug('Switching configuration', { + from: this.currentState.configPath, + to: newConfigPath + }); + + try { + let config = await loadConfig(authConfig, newConfigPath, organizationId, apiClient); + + // Inject rules if provided + if (rules && rules.length > 0) { + config = await this.injectRulesIntoConfig(config, rules); + } + + this.currentState = { + config, + configPath: newConfigPath + }; + + // Save assistant slug to auth config if loading by slug + if (!this.isFilePath(newConfigPath)) { + updateAssistantSlug(newConfigPath); + } + + logger.debug('Configuration switched successfully', { + newConfigPath + }); + + return this.currentState; + } catch (error: any) { + logger.error('Failed to switch configuration:', error); + throw error; + } + } + + /** + * Reload the current configuration + */ + async reload( + authConfig: AuthConfig, + organizationId: string | null, + apiClient: DefaultApiInterface, + rules?: string[] + ): Promise { + if (!this.currentState.configPath) { + throw new Error('No configuration path available for reload'); + } + + logger.debug('Reloading current configuration'); + + return this.switchConfig( + this.currentState.configPath, + authConfig, + organizationId, + apiClient, + rules + ); + } + + /** + * Process rules and inject them into the assistant config + */ + private async injectRulesIntoConfig( + config: AssistantUnrolled, + rules: string[] + ): Promise { + if (!rules || rules.length === 0) { + return config; + } + + const { processRule } = await import('../args.js'); + let processedRules: string[] = []; + + for (const ruleSpec of rules) { + try { + const processedRule = await processRule(ruleSpec); + processedRules.push(processedRule); + } catch (error: any) { + logger.warn(`Failed to process rule "${ruleSpec}": ${error.message}`); + } + } + + if (processedRules.length === 0) { + return config; + } + + // Clone the config to avoid mutating the original + const modifiedConfig = { ...config }; + + // Combine processed rules with existing system message if the config has one + const existingSystemMessage = (modifiedConfig as any).systemMessage || ""; + const rulesSection = processedRules.join("\n\n"); + + if (existingSystemMessage) { + (modifiedConfig as any).systemMessage = `${existingSystemMessage}\n\n${rulesSection}`; + } else { + (modifiedConfig as any).systemMessage = rulesSection; + } + + return modifiedConfig; + } + + /** + * Check if a config path is a file path vs assistant slug + */ + private isFilePath(configPath: string): boolean { + return ( + configPath.startsWith(".") || + configPath.startsWith("/") || + configPath.startsWith("~") + ); + } +} \ No newline at end of file diff --git a/src/services/MCPServiceWrapper.ts b/src/services/MCPServiceWrapper.ts new file mode 100644 index 000000000..8c1e3ac52 --- /dev/null +++ b/src/services/MCPServiceWrapper.ts @@ -0,0 +1,96 @@ +import { AssistantUnrolled } from "@continuedev/config-yaml"; +import { MCPService } from '../mcp.js'; +import logger from '../util/logger.js'; +import { MCPServiceState } from './types.js'; + +/** + * Service wrapper for managing MCP service state + * The actual MCPService is a singleton, this wrapper provides reactive updates + */ +export class MCPServiceWrapper { + private currentState: MCPServiceState = { + mcpService: null + }; + + /** + * Initialize the MCP service wrapper + */ + async initialize(assistant: AssistantUnrolled): Promise { + logger.debug('Initializing MCPServiceWrapper'); + + try { + const mcpService = await MCPService.create(assistant); + + this.currentState = { + mcpService + }; + + logger.debug('MCPServiceWrapper initialized successfully', { + toolCount: mcpService.getTools().length, + promptCount: mcpService.getPrompts().length + }); + + return this.currentState; + } catch (error: any) { + logger.error('Failed to initialize MCPServiceWrapper:', error); + throw error; + } + } + + /** + * Get current MCP service state + */ + getState(): MCPServiceState { + return { ...this.currentState }; + } + + /** + * Update the MCP service with a new assistant config + * Note: This creates a new MCP service since the original is a singleton + */ + async update(assistant: AssistantUnrolled): Promise { + logger.debug('Updating MCPServiceWrapper'); + + try { + // Clear the existing singleton instance to force recreation + (MCPService as any).instance = null; + + const mcpService = await MCPService.create(assistant); + + this.currentState = { + mcpService + }; + + logger.debug('MCPServiceWrapper updated successfully', { + toolCount: mcpService.getTools().length, + promptCount: mcpService.getPrompts().length + }); + + return this.currentState; + } catch (error: any) { + logger.error('Failed to update MCPServiceWrapper:', error); + throw error; + } + } + + /** + * Check if the MCP service is ready + */ + isReady(): boolean { + return this.currentState.mcpService !== null; + } + + /** + * Get MCP service information for display + */ + getMCPInfo(): { toolCount: number; promptCount: number } | null { + if (!this.currentState.mcpService) { + return null; + } + + return { + toolCount: this.currentState.mcpService.getTools().length, + promptCount: this.currentState.mcpService.getPrompts().length + }; + } +} \ No newline at end of file diff --git a/src/services/ModelService.ts b/src/services/ModelService.ts new file mode 100644 index 000000000..a2a84c1a6 --- /dev/null +++ b/src/services/ModelService.ts @@ -0,0 +1,103 @@ +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; +import { BaseLlmApi } from "@continuedev/openai-adapters"; +import { getLlmApi } from '../config.js'; +import { AuthConfig } from '../auth/workos.js'; +import logger from '../util/logger.js'; +import { ModelServiceState } from './types.js'; + +/** + * Service for managing LLM and model state + * Depends on auth config and assistant config + */ +export class ModelService { + private currentState: ModelServiceState = { + llmApi: null, + model: null + }; + + /** + * Initialize the model service + */ + async initialize( + assistant: AssistantUnrolled, + authConfig: AuthConfig + ): Promise { + logger.debug('Initializing ModelService'); + + try { + const [llmApi, model] = getLlmApi(assistant, authConfig); + + this.currentState = { + llmApi, + model + }; + + logger.debug('ModelService initialized successfully', { + modelProvider: model.provider, + modelName: (model as any).name || 'unnamed' + }); + + return this.currentState; + } catch (error: any) { + logger.error('Failed to initialize ModelService:', error); + throw error; + } + } + + /** + * Get current model state + */ + getState(): ModelServiceState { + return { ...this.currentState }; + } + + /** + * Update the model based on new config or auth changes + */ + async update( + assistant: AssistantUnrolled, + authConfig: AuthConfig + ): Promise { + logger.debug('Updating ModelService'); + + try { + const [llmApi, model] = getLlmApi(assistant, authConfig); + + this.currentState = { + llmApi, + model + }; + + logger.debug('ModelService updated successfully', { + modelProvider: model.provider, + modelName: (model as any).name || 'unnamed' + }); + + return this.currentState; + } catch (error: any) { + logger.error('Failed to update ModelService:', error); + throw error; + } + } + + /** + * Check if the current model is ready for use + */ + isReady(): boolean { + return this.currentState.llmApi !== null && this.currentState.model !== null; + } + + /** + * Get model information for display + */ + getModelInfo(): { provider: string; name: string } | null { + if (!this.currentState.model) { + return null; + } + + return { + provider: this.currentState.model.provider, + name: (this.currentState.model as any).name || 'unnamed' + }; + } +} \ No newline at end of file diff --git a/src/services/ServiceContainer.ts b/src/services/ServiceContainer.ts new file mode 100644 index 000000000..24b2135fa --- /dev/null +++ b/src/services/ServiceContainer.ts @@ -0,0 +1,230 @@ +import { EventEmitter } from 'events'; +import logger from '../util/logger.js'; +import { ServiceResult, ServiceState, ServiceEvents } from './types.js'; + +/** + * Central service container that manages service lifecycle and dependencies + * Uses EventEmitter for reactive updates across the application + */ +export class ServiceContainer extends EventEmitter { + private services = new Map>(); + private factories = new Map Promise>(); + private dependencies = new Map(); + + constructor() { + super(); + // Increase max listeners to handle multiple UI components + this.setMaxListeners(50); + } + + /** + * Register a service factory with optional dependencies + */ + register( + serviceName: string, + factory: () => Promise, + deps: string[] = [] + ): void { + this.factories.set(serviceName, factory); + this.dependencies.set(serviceName, deps); + + // Initialize with idle state + this.services.set(serviceName, { + value: null, + state: 'idle', + error: null + }); + + logger.debug(`Registered service: ${serviceName}`, { dependencies: deps }); + } + + /** + * Get current service result (synchronous) + */ + getSync(serviceName: string): ServiceResult { + const result = this.services.get(serviceName); + if (!result) { + logger.warn(`Service not found: ${serviceName}`); + return { + value: null, + state: 'error', + error: new Error(`Service '${serviceName}' not registered`) + }; + } + return result; + } + + /** + * Get service value, loading if necessary (async) + */ + async get(serviceName: string): Promise { + const current = this.getSync(serviceName); + + if (current.state === 'ready' && current.value !== null) { + return current.value; + } + + if (current.state === 'loading') { + // Wait for loading to complete + return new Promise((resolve, reject) => { + const onReady = (value: T) => { + this.off(`${serviceName}:ready`, onReady); + this.off(`${serviceName}:error`, onError); + resolve(value); + }; + + const onError = (error: Error) => { + this.off(`${serviceName}:ready`, onReady); + this.off(`${serviceName}:error`, onError); + reject(error); + }; + + this.once(`${serviceName}:ready`, onReady); + this.once(`${serviceName}:error`, onError); + }); + } + + // Need to load + return this.load(serviceName); + } + + /** + * Load a service, handling dependencies + */ + async load(serviceName: string): Promise { + const factory = this.factories.get(serviceName); + if (!factory) { + const error = new Error(`No factory registered for service '${serviceName}'`); + this.setServiceError(serviceName, error); + throw error; + } + + // Check if already loading + const current = this.services.get(serviceName); + if (current?.state === 'loading') { + return this.get(serviceName); + } + + logger.debug(`Loading service: ${serviceName}`); + this.setServiceState(serviceName, 'loading'); + + try { + // Load dependencies first + const deps = this.dependencies.get(serviceName) || []; + await Promise.all(deps.map(dep => this.load(dep))); + + // Load the service + const value = await factory(); + + this.setServiceValue(serviceName, value); + logger.debug(`Service loaded successfully: ${serviceName}`); + + return value; + } catch (error: any) { + logger.error(`Failed to load service '${serviceName}':`, error); + this.setServiceError(serviceName, error); + throw error; + } + } + + /** + * Reload a service (and dependents) + */ + async reload(serviceName: string): Promise { + logger.debug(`Reloading service: ${serviceName}`); + + // Find all services that depend on this one + const dependents = Array.from(this.dependencies.entries()) + .filter(([_, deps]) => deps.includes(serviceName)) + .map(([name, _]) => name); + + // Reset this service and all dependents + this.resetService(serviceName); + dependents.forEach(dep => this.resetService(dep)); + + // Reload + return this.load(serviceName); + } + + /** + * Manually set a service value (for testing or external updates) + */ + set(serviceName: string, value: T): void { + this.setServiceValue(serviceName, value); + } + + /** + * Check if service is ready + */ + isReady(serviceName: string): boolean { + const result = this.services.get(serviceName); + return result?.state === 'ready' && result.value !== null; + } + + /** + * Check if service is loading + */ + isLoading(serviceName: string): boolean { + const result = this.services.get(serviceName); + return result?.state === 'loading'; + } + + /** + * Get all service states (for debugging) + */ + getServiceStates(): Record { + const states: Record = {}; + for (const [name, result] of this.services) { + states[name] = result.state; + } + return states; + } + + /** + * Private helper methods + */ + private setServiceState(serviceName: string, state: ServiceState): void { + const current = this.services.get(serviceName) || { value: null, state: 'idle', error: null }; + const updated = { ...current, state, lastUpdated: new Date() }; + this.services.set(serviceName, updated); + this.emit(`${serviceName}:${state}`); + } + + private setServiceValue(serviceName: string, value: T): void { + const result: ServiceResult = { + value, + state: 'ready', + error: null, + lastUpdated: new Date() + }; + + this.services.set(serviceName, result); + this.emit(`${serviceName}:ready`, value); + this.emit(`${serviceName}:changed`, value); + } + + private setServiceError(serviceName: string, error: Error): void { + const result: ServiceResult = { + value: null, + state: 'error', + error, + lastUpdated: new Date() + }; + + this.services.set(serviceName, result); + this.emit(`${serviceName}:error`, error); + } + + private resetService(serviceName: string): void { + const result: ServiceResult = { + value: null, + state: 'idle', + error: null + }; + + this.services.set(serviceName, result); + } +} + +// Global singleton instance +export const serviceContainer = new ServiceContainer(); \ No newline at end of file diff --git a/src/services/index.ts b/src/services/index.ts new file mode 100644 index 000000000..285913bdc --- /dev/null +++ b/src/services/index.ts @@ -0,0 +1,161 @@ +import { serviceContainer } from './ServiceContainer.js'; +import { AuthService } from './AuthService.js'; +import { ConfigService } from './ConfigService.js'; +import { ModelService } from './ModelService.js'; +import { ApiClientService } from './ApiClientService.js'; +import { MCPServiceWrapper } from './MCPServiceWrapper.js'; +import { SERVICE_NAMES, ServiceInitOptions, AuthServiceState, ApiClientServiceState, ConfigServiceState } from './types.js'; +import logger from '../util/logger.js'; + +// Service instances +const authService = new AuthService(); +const configService = new ConfigService(); +const modelService = new ModelService(); +const apiClientService = new ApiClientService(); +const mcpServiceWrapper = new MCPServiceWrapper(); + +/** + * Initialize all services and register them with the service container + */ +export async function initializeServices(options: ServiceInitOptions = {}) { + logger.debug('Initializing service registry'); + + // Register service factories with dependencies + serviceContainer.register( + SERVICE_NAMES.AUTH, + () => authService.initialize(), + [] // No dependencies + ); + + serviceContainer.register( + SERVICE_NAMES.API_CLIENT, + async () => { + const authState = await serviceContainer.get(SERVICE_NAMES.AUTH); + return apiClientService.initialize(authState.authConfig); + }, + [SERVICE_NAMES.AUTH] // Depends on auth + ); + + serviceContainer.register( + SERVICE_NAMES.CONFIG, + async () => { + const [authState, apiClientState] = await Promise.all([ + serviceContainer.get(SERVICE_NAMES.AUTH), + serviceContainer.get(SERVICE_NAMES.API_CLIENT) + ]); + + // Ensure organization is selected if authenticated and not headless + let finalAuthState = authState; + if (authState.authConfig && !options.headless) { + finalAuthState = await authService.ensureOrganization(options.headless ?? false); + // Update the auth service state in container + serviceContainer.set(SERVICE_NAMES.AUTH, finalAuthState); + } + + if (!apiClientState.apiClient) { + throw new Error('API client not available'); + } + + return configService.initialize( + finalAuthState.authConfig, + options.configPath, + finalAuthState.organizationId || null, + apiClientState.apiClient, + options.rules + ); + }, + [SERVICE_NAMES.AUTH, SERVICE_NAMES.API_CLIENT] // Depends on auth and API client + ); + + serviceContainer.register( + SERVICE_NAMES.MODEL, + async () => { + const [configState, authState] = await Promise.all([ + serviceContainer.get(SERVICE_NAMES.CONFIG), + serviceContainer.get(SERVICE_NAMES.AUTH) + ]); + + if (!configState.config) { + throw new Error('Config not available'); + } + + return modelService.initialize(configState.config, authState.authConfig); + }, + [SERVICE_NAMES.CONFIG, SERVICE_NAMES.AUTH] // Depends on config and auth + ); + + serviceContainer.register( + SERVICE_NAMES.MCP, + async () => { + const configState = await serviceContainer.get(SERVICE_NAMES.CONFIG); + + if (!configState.config) { + throw new Error('Config not available for MCP service'); + } + + return mcpServiceWrapper.initialize(configState.config); + }, + [SERVICE_NAMES.CONFIG] // Depends on config + ); + + logger.debug('Service registry initialized'); +} + +/** + * Get a service from the container (async) + */ +export function getService(serviceName: string): Promise { + return serviceContainer.get(serviceName); +} + +/** + * Get service state synchronously + */ +export function getServiceSync(serviceName: string) { + return serviceContainer.getSync(serviceName); +} + +/** + * Reload a specific service + */ +export function reloadService(serviceName: string) { + return serviceContainer.reload(serviceName); +} + +/** + * Check if all core services are ready + */ +export function areServicesReady(): boolean { + return [ + SERVICE_NAMES.AUTH, + SERVICE_NAMES.API_CLIENT, + SERVICE_NAMES.CONFIG, + SERVICE_NAMES.MODEL, + SERVICE_NAMES.MCP + ].every(name => serviceContainer.isReady(name)); +} + +/** + * Get service states for debugging + */ +export function getServiceStates() { + return serviceContainer.getServiceStates(); +} + +/** + * Direct access to service instances for complex operations + */ +export const services = { + auth: authService, + config: configService, + model: modelService, + apiClient: apiClientService, + mcp: mcpServiceWrapper +} as const; + +// Export the service container for advanced usage +export { serviceContainer }; + +// Export service names and types +export { SERVICE_NAMES } from './types.js'; +export type * from './types.js'; \ No newline at end of file diff --git a/src/services/types.ts b/src/services/types.ts new file mode 100644 index 000000000..c99a6061d --- /dev/null +++ b/src/services/types.ts @@ -0,0 +1,77 @@ +import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml"; +import { BaseLlmApi } from "@continuedev/openai-adapters"; +import { DefaultApiInterface } from "@continuedev/sdk/dist/api/dist/index.js"; +import { AuthConfig } from "../auth/workos.js"; +import { MCPService } from "../mcp.js"; + +/** + * Service lifecycle states + */ +export type ServiceState = 'idle' | 'loading' | 'ready' | 'error'; + +/** + * Generic service result with state tracking + */ +export interface ServiceResult { + value: T | null; + state: ServiceState; + error: Error | null; + lastUpdated?: Date; +} + +/** + * Service event types for the EventEmitter + */ +export interface ServiceEvents { + [key: `${string}:loading`]: []; + [key: `${string}:ready`]: [any]; + [key: `${string}:error`]: [Error]; + [key: `${string}:changed`]: [any]; +} + +/** + * Core service types + */ +export interface AuthServiceState { + authConfig: AuthConfig | null; + isAuthenticated: boolean; + organizationId?: string; +} + +export interface ConfigServiceState { + config: AssistantUnrolled | null; + configPath?: string; +} + +export interface ModelServiceState { + llmApi: BaseLlmApi | null; + model: ModelConfig | null; +} + +export interface MCPServiceState { + mcpService: MCPService | null; +} + +export interface ApiClientServiceState { + apiClient: DefaultApiInterface | null; +} + +/** + * Service names as constants to prevent typos + */ +export const SERVICE_NAMES = { + AUTH: 'auth', + CONFIG: 'config', + MODEL: 'model', + MCP: 'mcp', + API_CLIENT: 'apiClient' +} as const; + +/** + * Service initialization options + */ +export interface ServiceInitOptions { + configPath?: string; + rules?: string[]; + headless?: boolean; +} \ No newline at end of file