root.go 10 KB

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