root.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. evts, err := app.Client.Event(ctx)
  160. if err != nil {
  161. slog.Error("Failed to subscribe to events", "error", err)
  162. return err
  163. }
  164. go func() {
  165. for item := range evts {
  166. program.Send(item)
  167. }
  168. }()
  169. // Cleanup function for when the program exits
  170. cleanup := func() {
  171. // Cancel subscriptions first
  172. cancelSubs()
  173. // Then shutdown the app
  174. app.Shutdown()
  175. // Then cancel TUI message handler
  176. tuiCancel()
  177. // Wait for TUI message handler to finish
  178. tuiWg.Wait()
  179. slog.Info("All goroutines cleaned up")
  180. }
  181. // Run the TUI
  182. result, err := program.Run()
  183. cleanup()
  184. if err != nil {
  185. slog.Error("TUI error", "error", err)
  186. return fmt.Errorf("TUI error: %v", err)
  187. }
  188. slog.Info("TUI exited", "result", result)
  189. return nil
  190. },
  191. }
  192. // attemptTUIRecovery tries to recover the TUI after a panic
  193. func attemptTUIRecovery(program *tea.Program) {
  194. slog.Info("Attempting to recover TUI after panic")
  195. // We could try to restart the TUI or gracefully exit
  196. // For now, we'll just quit the program to avoid further issues
  197. program.Quit()
  198. }
  199. func initMCPTools(ctx context.Context, app *app.App) {
  200. go func() {
  201. defer logging.RecoverPanic("MCP-goroutine", nil)
  202. // Create a context with timeout for the initial MCP tools fetch
  203. ctxWithTimeout, cancel := context.WithTimeout(ctx, 30*time.Second)
  204. defer cancel()
  205. // Set this up once with proper error handling
  206. agent.GetMcpTools(ctxWithTimeout, app.Permissions)
  207. slog.Info("MCP message handling goroutine exiting")
  208. }()
  209. }
  210. func setupSubscriber[T any](
  211. ctx context.Context,
  212. wg *sync.WaitGroup,
  213. name string,
  214. subscriber func(context.Context) <-chan pubsub.Event[T],
  215. outputCh chan<- tea.Msg,
  216. ) {
  217. wg.Add(1)
  218. go func() {
  219. defer wg.Done()
  220. defer logging.RecoverPanic(fmt.Sprintf("subscription-%s", name), nil)
  221. subCh := subscriber(ctx)
  222. if subCh == nil {
  223. slog.Warn("subscription channel is nil", "name", name)
  224. return
  225. }
  226. for {
  227. select {
  228. case event, ok := <-subCh:
  229. if !ok {
  230. slog.Info("subscription channel closed", "name", name)
  231. return
  232. }
  233. var msg tea.Msg = event
  234. select {
  235. case outputCh <- msg:
  236. case <-time.After(2 * time.Second):
  237. slog.Warn("message dropped due to slow consumer", "name", name)
  238. case <-ctx.Done():
  239. slog.Info("subscription cancelled", "name", name)
  240. return
  241. }
  242. case <-ctx.Done():
  243. slog.Info("subscription cancelled", "name", name)
  244. return
  245. }
  246. }
  247. }()
  248. }
  249. func setupSubscriptions(app *app.App, parentCtx context.Context) (chan tea.Msg, func()) {
  250. ch := make(chan tea.Msg, 100)
  251. wg := sync.WaitGroup{}
  252. ctx, cancel := context.WithCancel(parentCtx) // Inherit from parent context
  253. setupSubscriber(ctx, &wg, "logging", app.Logs.Subscribe, ch)
  254. setupSubscriber(ctx, &wg, "sessions", app.Sessions.Subscribe, ch)
  255. setupSubscriber(ctx, &wg, "messages", app.Messages.Subscribe, ch)
  256. setupSubscriber(ctx, &wg, "permissions", app.Permissions.Subscribe, ch)
  257. setupSubscriber(ctx, &wg, "status", app.Status.Subscribe, ch)
  258. cleanupFunc := func() {
  259. slog.Info("Cancelling all subscriptions")
  260. cancel() // Signal all goroutines to stop
  261. waitCh := make(chan struct{})
  262. go func() {
  263. defer logging.RecoverPanic("subscription-cleanup", nil)
  264. wg.Wait()
  265. close(waitCh)
  266. }()
  267. select {
  268. case <-waitCh:
  269. slog.Info("All subscription goroutines completed successfully")
  270. close(ch) // Only close after all writers are confirmed done
  271. case <-time.After(5 * time.Second):
  272. slog.Warn("Timed out waiting for some subscription goroutines to complete")
  273. close(ch)
  274. }
  275. }
  276. return ch, cleanupFunc
  277. }
  278. func Execute() {
  279. err := rootCmd.Execute()
  280. if err != nil {
  281. os.Exit(1)
  282. }
  283. }
  284. // checkStdinPipe checks if there's data being piped into stdin
  285. func checkStdinPipe() (string, bool) {
  286. // Check if stdin is not a terminal (i.e., it's being piped)
  287. stat, _ := os.Stdin.Stat()
  288. if (stat.Mode() & os.ModeCharDevice) == 0 {
  289. // Read all data from stdin
  290. data, err := io.ReadAll(os.Stdin)
  291. if err != nil {
  292. return "", false
  293. }
  294. // If we got data, return it
  295. if len(data) > 0 {
  296. return string(data), true
  297. }
  298. }
  299. return "", false
  300. }
  301. func init() {
  302. rootCmd.Flags().BoolP("help", "h", false, "Help")
  303. rootCmd.Flags().BoolP("version", "v", false, "Version")
  304. rootCmd.Flags().BoolP("debug", "d", false, "Debug")
  305. rootCmd.Flags().StringP("cwd", "c", "", "Current working directory")
  306. rootCmd.Flags().StringP("prompt", "p", "", "Run a single prompt in non-interactive mode")
  307. rootCmd.Flags().StringP("output-format", "f", "text", "Output format for non-interactive mode (text, json)")
  308. rootCmd.Flags().BoolP("quiet", "q", false, "Hide spinner in non-interactive mode")
  309. rootCmd.Flags().BoolP("verbose", "", false, "Display logs to stderr in non-interactive mode")
  310. rootCmd.Flags().StringSlice("allowedTools", nil, "Restrict the agent to only use the specified tools in non-interactive mode (comma-separated list)")
  311. rootCmd.Flags().StringSlice("excludedTools", nil, "Prevent the agent from using the specified tools in non-interactive mode (comma-separated list)")
  312. // Make allowedTools and excludedTools mutually exclusive
  313. rootCmd.MarkFlagsMutuallyExclusive("allowedTools", "excludedTools")
  314. // Make quiet and verbose mutually exclusive
  315. rootCmd.MarkFlagsMutuallyExclusive("quiet", "verbose")
  316. }