root.go 8.2 KB

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