root.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "sync"
  7. "time"
  8. "log/slog"
  9. tea "github.com/charmbracelet/bubbletea"
  10. zone "github.com/lrstanley/bubblezone"
  11. "github.com/spf13/cobra"
  12. "github.com/sst/opencode/internal/app"
  13. "github.com/sst/opencode/internal/config"
  14. "github.com/sst/opencode/internal/db"
  15. "github.com/sst/opencode/internal/format"
  16. "github.com/sst/opencode/internal/llm/agent"
  17. "github.com/sst/opencode/internal/logging"
  18. "github.com/sst/opencode/internal/lsp/discovery"
  19. "github.com/sst/opencode/internal/pubsub"
  20. "github.com/sst/opencode/internal/tui"
  21. "github.com/sst/opencode/internal/version"
  22. )
  23. type SessionIDHandler struct {
  24. slog.Handler
  25. app *app.App
  26. }
  27. func (h *SessionIDHandler) Handle(ctx context.Context, r slog.Record) error {
  28. if h.app != nil {
  29. sessionID := h.app.CurrentSession.ID
  30. if sessionID != "" {
  31. r.AddAttrs(slog.String("session_id", sessionID))
  32. }
  33. }
  34. return h.Handler.Handle(ctx, r)
  35. }
  36. func (h *SessionIDHandler) WithApp(app *app.App) *SessionIDHandler {
  37. h.app = app
  38. return h
  39. }
  40. var rootCmd = &cobra.Command{
  41. Use: "OpenCode",
  42. Short: "A terminal AI assistant for software development",
  43. Long: `OpenCode is a powerful terminal-based AI assistant that helps with software development tasks.
  44. It provides an interactive chat interface with AI capabilities, code analysis, and LSP integration
  45. to assist developers in writing, debugging, and understanding code directly from the terminal.`,
  46. RunE: func(cmd *cobra.Command, args []string) error {
  47. // If the help flag is set, show the help message
  48. if cmd.Flag("help").Changed {
  49. cmd.Help()
  50. return nil
  51. }
  52. if cmd.Flag("version").Changed {
  53. fmt.Println(version.Version)
  54. return nil
  55. }
  56. // Setup logging
  57. lvl := new(slog.LevelVar)
  58. textHandler := slog.NewTextHandler(logging.NewSlogWriter(), &slog.HandlerOptions{Level: lvl})
  59. sessionAwareHandler := &SessionIDHandler{Handler: textHandler}
  60. logger := slog.New(sessionAwareHandler)
  61. slog.SetDefault(logger)
  62. // Load the config
  63. debug, _ := cmd.Flags().GetBool("debug")
  64. cwd, _ := cmd.Flags().GetString("cwd")
  65. if cwd != "" {
  66. err := os.Chdir(cwd)
  67. if err != nil {
  68. return fmt.Errorf("failed to change directory: %v", err)
  69. }
  70. }
  71. if cwd == "" {
  72. c, err := os.Getwd()
  73. if err != nil {
  74. return fmt.Errorf("failed to get current working directory: %v", err)
  75. }
  76. cwd = c
  77. }
  78. _, err := config.Load(cwd, debug, lvl)
  79. if err != nil {
  80. return err
  81. }
  82. // Check if we're in non-interactive mode
  83. prompt, _ := cmd.Flags().GetString("prompt")
  84. if prompt != "" {
  85. outputFormatStr, _ := cmd.Flags().GetString("output-format")
  86. outputFormat := format.OutputFormat(outputFormatStr)
  87. if !outputFormat.IsValid() {
  88. return fmt.Errorf("invalid output format: %s", outputFormatStr)
  89. }
  90. quiet, _ := cmd.Flags().GetBool("quiet")
  91. verbose, _ := cmd.Flags().GetBool("verbose")
  92. // Get tool restriction flags
  93. allowedTools, _ := cmd.Flags().GetStringSlice("allowedTools")
  94. excludedTools, _ := cmd.Flags().GetStringSlice("excludedTools")
  95. return handleNonInteractiveMode(cmd.Context(), prompt, outputFormat, quiet, verbose, allowedTools, excludedTools)
  96. }
  97. // Run LSP auto-discovery
  98. if err := discovery.IntegrateLSPServers(cwd); err != nil {
  99. slog.Warn("Failed to auto-discover LSP servers", "error", err)
  100. // Continue anyway, this is not a fatal error
  101. }
  102. // Connect DB, this will also run migrations
  103. conn, err := db.Connect()
  104. if err != nil {
  105. return err
  106. }
  107. // Create main context for the application
  108. ctx, cancel := context.WithCancel(context.Background())
  109. defer cancel()
  110. app, err := app.New(ctx, conn)
  111. if err != nil {
  112. slog.Error("Failed to create app", "error", err)
  113. return err
  114. }
  115. sessionAwareHandler.WithApp(app)
  116. // Set up the TUI
  117. zone.NewGlobal()
  118. program := tea.NewProgram(
  119. tui.New(app),
  120. tea.WithAltScreen(),
  121. )
  122. // Initialize MCP tools in the background
  123. initMCPTools(ctx, app)
  124. // Setup the subscriptions, this will send services events to the TUI
  125. ch, cancelSubs := setupSubscriptions(app, ctx)
  126. // Create a context for the TUI message handler
  127. tuiCtx, tuiCancel := context.WithCancel(ctx)
  128. var tuiWg sync.WaitGroup
  129. tuiWg.Add(1)
  130. // Set up message handling for the TUI
  131. go func() {
  132. defer tuiWg.Done()
  133. defer logging.RecoverPanic("TUI-message-handler", func() {
  134. attemptTUIRecovery(program)
  135. })
  136. for {
  137. select {
  138. case <-tuiCtx.Done():
  139. slog.Info("TUI message handler shutting down")
  140. return
  141. case msg, ok := <-ch:
  142. if !ok {
  143. slog.Info("TUI message channel closed")
  144. return
  145. }
  146. program.Send(msg)
  147. }
  148. }
  149. }()
  150. // Cleanup function for when the program exits
  151. cleanup := func() {
  152. // Cancel subscriptions first
  153. cancelSubs()
  154. // Then shutdown the app
  155. app.Shutdown()
  156. // Then cancel TUI message handler
  157. tuiCancel()
  158. // Wait for TUI message handler to finish
  159. tuiWg.Wait()
  160. slog.Info("All goroutines cleaned up")
  161. }
  162. // Run the TUI
  163. result, err := program.Run()
  164. cleanup()
  165. if err != nil {
  166. slog.Error("TUI error", "error", err)
  167. return fmt.Errorf("TUI error: %v", err)
  168. }
  169. slog.Info("TUI exited", "result", result)
  170. return nil
  171. },
  172. }
  173. // attemptTUIRecovery tries to recover the TUI after a panic
  174. func attemptTUIRecovery(program *tea.Program) {
  175. slog.Info("Attempting to recover TUI after panic")
  176. // We could try to restart the TUI or gracefully exit
  177. // For now, we'll just quit the program to avoid further issues
  178. program.Quit()
  179. }
  180. func initMCPTools(ctx context.Context, app *app.App) {
  181. go func() {
  182. defer logging.RecoverPanic("MCP-goroutine", nil)
  183. // Create a context with timeout for the initial MCP tools fetch
  184. ctxWithTimeout, cancel := context.WithTimeout(ctx, 30*time.Second)
  185. defer cancel()
  186. // Set this up once with proper error handling
  187. agent.GetMcpTools(ctxWithTimeout, app.Permissions)
  188. slog.Info("MCP message handling goroutine exiting")
  189. }()
  190. }
  191. func setupSubscriber[T any](
  192. ctx context.Context,
  193. wg *sync.WaitGroup,
  194. name string,
  195. subscriber func(context.Context) <-chan pubsub.Event[T],
  196. outputCh chan<- tea.Msg,
  197. ) {
  198. wg.Add(1)
  199. go func() {
  200. defer wg.Done()
  201. defer logging.RecoverPanic(fmt.Sprintf("subscription-%s", name), nil)
  202. subCh := subscriber(ctx)
  203. if subCh == nil {
  204. slog.Warn("subscription channel is nil", "name", name)
  205. return
  206. }
  207. for {
  208. select {
  209. case event, ok := <-subCh:
  210. if !ok {
  211. slog.Info("subscription channel closed", "name", name)
  212. return
  213. }
  214. var msg tea.Msg = event
  215. select {
  216. case outputCh <- msg:
  217. case <-time.After(2 * time.Second):
  218. slog.Warn("message dropped due to slow consumer", "name", name)
  219. case <-ctx.Done():
  220. slog.Info("subscription cancelled", "name", name)
  221. return
  222. }
  223. case <-ctx.Done():
  224. slog.Info("subscription cancelled", "name", name)
  225. return
  226. }
  227. }
  228. }()
  229. }
  230. func setupSubscriptions(app *app.App, parentCtx context.Context) (chan tea.Msg, func()) {
  231. ch := make(chan tea.Msg, 100)
  232. wg := sync.WaitGroup{}
  233. ctx, cancel := context.WithCancel(parentCtx) // Inherit from parent context
  234. setupSubscriber(ctx, &wg, "logging", app.Logs.Subscribe, ch)
  235. setupSubscriber(ctx, &wg, "sessions", app.Sessions.Subscribe, ch)
  236. setupSubscriber(ctx, &wg, "messages", app.Messages.Subscribe, ch)
  237. setupSubscriber(ctx, &wg, "permissions", app.Permissions.Subscribe, ch)
  238. setupSubscriber(ctx, &wg, "status", app.Status.Subscribe, ch)
  239. cleanupFunc := func() {
  240. slog.Info("Cancelling all subscriptions")
  241. cancel() // Signal all goroutines to stop
  242. waitCh := make(chan struct{})
  243. go func() {
  244. defer logging.RecoverPanic("subscription-cleanup", nil)
  245. wg.Wait()
  246. close(waitCh)
  247. }()
  248. select {
  249. case <-waitCh:
  250. slog.Info("All subscription goroutines completed successfully")
  251. close(ch) // Only close after all writers are confirmed done
  252. case <-time.After(5 * time.Second):
  253. slog.Warn("Timed out waiting for some subscription goroutines to complete")
  254. close(ch)
  255. }
  256. }
  257. return ch, cleanupFunc
  258. }
  259. func Execute() {
  260. err := rootCmd.Execute()
  261. if err != nil {
  262. os.Exit(1)
  263. }
  264. }
  265. func init() {
  266. rootCmd.Flags().BoolP("help", "h", false, "Help")
  267. rootCmd.Flags().BoolP("version", "v", false, "Version")
  268. rootCmd.Flags().BoolP("debug", "d", false, "Debug")
  269. rootCmd.Flags().StringP("cwd", "c", "", "Current working directory")
  270. rootCmd.Flags().StringP("prompt", "p", "", "Run a single prompt in non-interactive mode")
  271. rootCmd.Flags().StringP("output-format", "f", "text", "Output format for non-interactive mode (text, json)")
  272. rootCmd.Flags().BoolP("quiet", "q", false, "Hide spinner in non-interactive mode")
  273. rootCmd.Flags().BoolP("verbose", "", false, "Display logs to stderr in non-interactive mode")
  274. rootCmd.Flags().StringSlice("allowedTools", nil, "Restrict the agent to only use the specified tools in non-interactive mode (comma-separated list)")
  275. rootCmd.Flags().StringSlice("excludedTools", nil, "Prevent the agent from using the specified tools in non-interactive mode (comma-separated list)")
  276. // Make allowedTools and excludedTools mutually exclusive
  277. rootCmd.MarkFlagsMutuallyExclusive("allowedTools", "excludedTools")
  278. // Make quiet and verbose mutually exclusive
  279. rootCmd.MarkFlagsMutuallyExclusive("quiet", "verbose")
  280. }