root.go 9.8 KB

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