root.go 6.5 KB

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