root.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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/config"
  13. "github.com/sst/opencode/internal/pubsub"
  14. "github.com/sst/opencode/internal/tui"
  15. "github.com/sst/opencode/internal/tui/app"
  16. )
  17. var rootCmd = &cobra.Command{
  18. Use: "OpenCode",
  19. Short: "A terminal AI assistant for software development",
  20. Long: `OpenCode is a powerful terminal-based AI assistant that helps with software development tasks.
  21. It provides an interactive chat interface with AI capabilities, code analysis, and LSP integration
  22. to assist developers in writing, debugging, and understanding code directly from the terminal.`,
  23. RunE: func(cmd *cobra.Command, args []string) error {
  24. // Setup logging
  25. // file, err := os.OpenFile("debug.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
  26. // if err != nil {
  27. // panic(err)
  28. // }
  29. // defer file.Close()
  30. // logger := slog.New(slog.NewTextHandler(file, &slog.HandlerOptions{Level: slog.LevelDebug}))
  31. // slog.SetDefault(logger)
  32. // Load the config
  33. debug, _ := cmd.Flags().GetBool("debug")
  34. cwd, _ := cmd.Flags().GetString("cwd")
  35. if cwd != "" {
  36. err := os.Chdir(cwd)
  37. if err != nil {
  38. return fmt.Errorf("failed to change directory: %v", err)
  39. }
  40. }
  41. if cwd == "" {
  42. c, err := os.Getwd()
  43. if err != nil {
  44. return fmt.Errorf("failed to get current working directory: %v", err)
  45. }
  46. cwd = c
  47. }
  48. _, err := config.Load(cwd, debug)
  49. if err != nil {
  50. return err
  51. }
  52. // Create main context for the application
  53. ctx, cancel := context.WithCancel(context.Background())
  54. defer cancel()
  55. app, err := app.New(ctx)
  56. if err != nil {
  57. slog.Error("Failed to create app", "error", err)
  58. return err
  59. }
  60. // Set up the TUI
  61. zone.NewGlobal()
  62. program := tea.NewProgram(
  63. tui.New(app),
  64. tea.WithAltScreen(),
  65. )
  66. evts, err := app.Events.Event(ctx)
  67. if err != nil {
  68. slog.Error("Failed to subscribe to events", "error", err)
  69. return err
  70. }
  71. go func() {
  72. for item := range evts {
  73. program.Send(item)
  74. }
  75. }()
  76. // Setup the subscriptions, this will send services events to the TUI
  77. ch, cancelSubs := setupSubscriptions(app, ctx)
  78. // Create a context for the TUI message handler
  79. tuiCtx, tuiCancel := context.WithCancel(ctx)
  80. var tuiWg sync.WaitGroup
  81. tuiWg.Add(1)
  82. // Set up message handling for the TUI
  83. go func() {
  84. defer tuiWg.Done()
  85. // defer logging.RecoverPanic("TUI-message-handler", func() {
  86. // attemptTUIRecovery(program)
  87. // })
  88. for {
  89. select {
  90. case <-tuiCtx.Done():
  91. slog.Info("TUI message handler shutting down")
  92. return
  93. case msg, ok := <-ch:
  94. if !ok {
  95. slog.Info("TUI message channel closed")
  96. return
  97. }
  98. program.Send(msg)
  99. }
  100. }
  101. }()
  102. // Cleanup function for when the program exits
  103. cleanup := func() {
  104. // Cancel subscriptions first
  105. cancelSubs()
  106. // Then shutdown the app
  107. app.Shutdown()
  108. // Then cancel TUI message handler
  109. tuiCancel()
  110. // Wait for TUI message handler to finish
  111. tuiWg.Wait()
  112. slog.Info("All goroutines cleaned up")
  113. }
  114. // Run the TUI
  115. result, err := program.Run()
  116. cleanup()
  117. if err != nil {
  118. slog.Error("TUI error", "error", err)
  119. return fmt.Errorf("TUI error: %v", err)
  120. }
  121. slog.Info("TUI exited", "result", result)
  122. return nil
  123. },
  124. }
  125. func setupSubscriber[T any](
  126. ctx context.Context,
  127. wg *sync.WaitGroup,
  128. name string,
  129. subscriber func(context.Context) <-chan pubsub.Event[T],
  130. outputCh chan<- tea.Msg,
  131. ) {
  132. wg.Add(1)
  133. go func() {
  134. defer wg.Done()
  135. // defer logging.RecoverPanic(fmt.Sprintf("subscription-%s", name), nil)
  136. subCh := subscriber(ctx)
  137. if subCh == nil {
  138. slog.Warn("subscription channel is nil", "name", name)
  139. return
  140. }
  141. for {
  142. select {
  143. case event, ok := <-subCh:
  144. if !ok {
  145. slog.Info("subscription channel closed", "name", name)
  146. return
  147. }
  148. var msg tea.Msg = event
  149. select {
  150. case outputCh <- msg:
  151. case <-time.After(2 * time.Second):
  152. slog.Warn("message dropped due to slow consumer", "name", name)
  153. case <-ctx.Done():
  154. slog.Info("subscription cancelled", "name", name)
  155. return
  156. }
  157. case <-ctx.Done():
  158. slog.Info("subscription cancelled", "name", name)
  159. return
  160. }
  161. }
  162. }()
  163. }
  164. func setupSubscriptions(app *app.App, parentCtx context.Context) (chan tea.Msg, func()) {
  165. ch := make(chan tea.Msg, 100)
  166. wg := sync.WaitGroup{}
  167. ctx, cancel := context.WithCancel(parentCtx) // Inherit from parent context
  168. setupSubscriber(ctx, &wg, "status", app.Status.Subscribe, ch)
  169. cleanupFunc := func() {
  170. slog.Info("Cancelling all subscriptions")
  171. cancel() // Signal all goroutines to stop
  172. waitCh := make(chan struct{})
  173. go func() {
  174. // defer logging.RecoverPanic("subscription-cleanup", nil)
  175. wg.Wait()
  176. close(waitCh)
  177. }()
  178. select {
  179. case <-waitCh:
  180. slog.Info("All subscription goroutines completed successfully")
  181. close(ch) // Only close after all writers are confirmed done
  182. case <-time.After(5 * time.Second):
  183. slog.Warn("Timed out waiting for some subscription goroutines to complete")
  184. close(ch)
  185. }
  186. }
  187. return ch, cleanupFunc
  188. }
  189. func Execute() {
  190. err := rootCmd.Execute()
  191. if err != nil {
  192. os.Exit(1)
  193. }
  194. }
  195. func init() {
  196. rootCmd.Flags().BoolP("help", "h", false, "Help")
  197. rootCmd.Flags().BoolP("version", "v", false, "Version")
  198. rootCmd.Flags().BoolP("debug", "d", false, "Debug")
  199. rootCmd.Flags().StringP("cwd", "c", "", "Current working directory")
  200. rootCmd.Flags().StringP("prompt", "p", "", "Run a single prompt in non-interactive mode")
  201. rootCmd.Flags().StringP("output-format", "f", "text", "Output format for non-interactive mode (text, json)")
  202. rootCmd.Flags().BoolP("quiet", "q", false, "Hide spinner in non-interactive mode")
  203. rootCmd.Flags().BoolP("verbose", "", false, "Display logs to stderr in non-interactive mode")
  204. rootCmd.Flags().StringSlice("allowedTools", nil, "Restrict the agent to only use the specified tools in non-interactive mode (comma-separated list)")
  205. rootCmd.Flags().StringSlice("excludedTools", nil, "Prevent the agent from using the specified tools in non-interactive mode (comma-separated list)")
  206. // Make allowedTools and excludedTools mutually exclusive
  207. rootCmd.MarkFlagsMutuallyExclusive("allowedTools", "excludedTools")
  208. // Make quiet and verbose mutually exclusive
  209. rootCmd.MarkFlagsMutuallyExclusive("quiet", "verbose")
  210. }