6119
My
mysis / files
mysis / internal / features / app.go
4.5 KB
1package features 2 3import ( 4 "fmt" 5 "io" 6 "os" 7 "path/filepath" 8 "strings" 9 "time" 10 11 "github.com/rs/zerolog" 12 "github.com/rs/zerolog/log" 13 "github.com/xonecas/mysis/internal/config" 14 "github.com/xonecas/mysis/internal/provider" 15) 16 17// InitializeProviders initializes the provider registry from config. 18// This is shared by both CLI and TUI modes. 19func InitializeProviders(cfg *config.Config, creds *config.Credentials) *provider.Registry { 20 registry := provider.NewRegistry() 21 22 for name, provCfg := range cfg.Providers { 23 // Detect provider type based on endpoint 24 switch { 25 case strings.Contains(provCfg.Endpoint, "localhost:11434"), strings.Contains(provCfg.Endpoint, "/ollama"): 26 // Ollama provider 27 factory := provider.NewOllamaFactory(name, provCfg.Endpoint) 28 registry.RegisterFactory(name, factory) 29 log.Debug().Str("name", name).Str("endpoint", provCfg.Endpoint).Msg("Registered Ollama provider") 30 case strings.Contains(provCfg.Endpoint, "opencode.ai"): 31 // OpenCode Zen provider 32 keyName := provCfg.APIKeyName 33 if keyName == "" { 34 keyName = name 35 } 36 apiKey := creds.GetAPIKey(keyName) 37 if apiKey == "" { 38 log.Warn().Str("name", name).Str("key_name", keyName).Msg("No API key found for provider") 39 continue 40 } 41 factory := provider.NewOpenCodeFactory(name, provCfg.Endpoint, apiKey) 42 registry.RegisterFactory(name, factory) 43 log.Debug().Str("name", name).Str("endpoint", provCfg.Endpoint).Msg("Registered OpenCode provider") 44 default: 45 log.Warn().Str("name", name).Str("endpoint", provCfg.Endpoint).Msg("Unknown provider type") 46 } 47 } 48 49 return registry 50} 51 52// LoadSystemPromptFromFile loads a system prompt from a markdown file. 53func LoadSystemPromptFromFile(path string) (string, error) { 54 ext := strings.ToLower(filepath.Ext(path)) 55 if ext != ".md" && ext != ".markdown" { 56 return "", fmt.Errorf("system prompt file must be markdown (.md or .markdown): %s", path) 57 } 58 59 //nolint:gosec // G304: Path from validated config file 60 data, err := os.ReadFile(path) 61 if err != nil { 62 return "", fmt.Errorf("read system prompt file: %w", err) 63 } 64 65 content := strings.TrimSpace(string(data)) 66 if content == "" { 67 return "", fmt.Errorf("system prompt file is empty: %s", path) 68 } 69 70 return content, nil 71} 72 73// HistoryHasSystemPrompt checks if the history already has a system prompt with the given content. 74func HistoryHasSystemPrompt(history []provider.Message, content string) bool { 75 for _, msg := range history { 76 if msg.Role == "system" && msg.Content == content { 77 return true 78 } 79 } 80 return false 81} 82 83// PrependSystemPrompt prepends a system prompt to the history. 84func PrependSystemPrompt(history []provider.Message, content string) []provider.Message { 85 systemMsg := provider.Message{Role: "system", Content: content} 86 return append([]provider.Message{systemMsg}, history...) 87} 88 89// SetupFileLogging configures zerolog to write to a file. 90// This is used by TUI mode to avoid collision with the UI. 91func SetupFileLogging(debug bool) error { 92 // Get data directory 93 dataDir, err := config.DataDir() 94 if err != nil { 95 return fmt.Errorf("get data directory: %w", err) 96 } 97 98 // Create logs directory 99 logDir := filepath.Join(dataDir, "logs") 100 if err := os.MkdirAll(logDir, 0750); err != nil { 101 return fmt.Errorf("create logs directory: %w", err) 102 } 103 104 // Create log file 105 logFile := filepath.Join(logDir, "mysis.log") 106 //nolint:gosec // G304: Path from validated config file 107 file, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) 108 if err != nil { 109 return fmt.Errorf("open log file: %w", err) 110 } 111 112 // Set up multi-writer: file (JSON) + console writer for debugging 113 var writers []io.Writer 114 115 // Always write JSON to file 116 writers = append(writers, file) 117 118 // In debug mode, also write human-readable logs to a separate debug file 119 if debug { 120 debugFile := filepath.Join(logDir, "mysis-debug.log") 121 //nolint:gosec // G304: Debug log file path is constructed from validated data directory 122 debugFileWriter, err := os.OpenFile(debugFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) 123 if err != nil { 124 return fmt.Errorf("open debug log file: %w", err) 125 } 126 consoleWriter := zerolog.ConsoleWriter{Out: debugFileWriter, TimeFormat: time.RFC3339} 127 writers = append(writers, consoleWriter) 128 } 129 130 // Configure logger 131 multi := io.MultiWriter(writers...) 132 log.Logger = zerolog.New(multi).With().Timestamp().Logger() 133 134 // Set log level 135 if debug { 136 zerolog.SetGlobalLevel(zerolog.DebugLevel) 137 } else { 138 zerolog.SetGlobalLevel(zerolog.InfoLevel) 139 } 140 141 log.Info(). 142 Str("log_file", logFile). 143 Bool("debug", debug). 144 Msg("File logging initialized") 145 146 return nil 147}