blob: 1575473ce9aa82fa362aa869b101e6a6752db4e6 [file] [log] [blame]
Earl Lee2e463fb2025-04-17 11:22:22 -07001package termui
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io"
10 "os"
11 "os/exec"
12 "os/signal"
13 "strings"
14 "sync"
15 "syscall"
16 "text/template"
17 "time"
18
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +000019 "github.com/dustin/go-humanize"
Earl Lee2e463fb2025-04-17 11:22:22 -070020 "github.com/fatih/color"
21 "golang.org/x/term"
22 "sketch.dev/loop"
23)
24
25var (
26 // toolUseTemplTxt defines how tool invocations appear in the terminal UI.
27 // Keep this template in sync with the tools defined in claudetool package
28 // and registered in loop/agent.go.
29 // Add formatting for new tools as they are created.
30 // TODO: should this be part of tool definition to make it harder to forget to set up?
Josh Bleecher Snyderc3c20232025-05-07 05:46:04 -070031 toolUseTemplTxt = `{{if .msg.ToolError}}ć€°ļø {{end -}}
Earl Lee2e463fb2025-04-17 11:22:22 -070032{{if eq .msg.ToolName "think" -}}
33 🧠 {{.input.thoughts -}}
34{{else if eq .msg.ToolName "keyword_search" -}}
Josh Bleecher Snyder453a62f2025-05-01 10:14:33 -070035 šŸ” {{ .input.query}}: {{.input.search_terms -}}
Earl Lee2e463fb2025-04-17 11:22:22 -070036{{else if eq .msg.ToolName "bash" -}}
Philip Zeyligerb60f0f22025-04-23 18:19:32 +000037 šŸ–„ļø{{if .input.background}}šŸ”„{{end}} {{ .input.command -}}
Earl Lee2e463fb2025-04-17 11:22:22 -070038{{else if eq .msg.ToolName "patch" -}}
39 āŒØļø {{.input.path -}}
40{{else if eq .msg.ToolName "done" -}}
41{{/* nothing to show here, the agent will write more in its next message */}}
42{{else if eq .msg.ToolName "title" -}}
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +000043šŸ·ļø {{.input.title}}
Josh Bleecher Snydera2a31502025-05-07 12:37:18 +000044{{else if eq .msg.ToolName "precommit" -}}
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +000045🌱 git branch: sketch/{{.input.branch_name}}
Josh Bleecher Snyder31785ae2025-05-06 01:50:58 +000046{{else if eq .msg.ToolName "knowledge_base" -}}
47šŸ“š Knowledge: {{.input.topic}}
Earl Lee2e463fb2025-04-17 11:22:22 -070048{{else if eq .msg.ToolName "str_replace_editor" -}}
49 āœļø {{.input.file_path -}}
50{{else if eq .msg.ToolName "codereview" -}}
51 šŸ› Running automated code review, may be slow
Sean McCullough485afc62025-04-28 14:28:39 -070052{{else if eq .msg.ToolName "multiplechoice" -}}
53 šŸ“ {{.input.question}}
54{{ range .input.responseOptions -}}
55 - {{ .caption}}: {{.responseText}}
56{{end -}}
Earl Lee2e463fb2025-04-17 11:22:22 -070057{{else -}}
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +000058 šŸ› ļø {{ .msg.ToolName}}: {{.msg.ToolInput -}}
Earl Lee2e463fb2025-04-17 11:22:22 -070059{{end -}}
60`
61 toolUseTmpl = template.Must(template.New("tool_use").Parse(toolUseTemplTxt))
62)
63
David Crawshaw93fec602025-05-05 08:40:06 -070064type TermUI struct {
Earl Lee2e463fb2025-04-17 11:22:22 -070065 stdin *os.File
66 stdout *os.File
67 stderr *os.File
68
69 agent loop.CodingAgent
70 httpURL string
71
72 trm *term.Terminal
73
74 // the chatMsgCh channel is for "conversation" messages, like responses to user input
75 // from the LLM, or output from executing slash-commands issued by the user.
76 chatMsgCh chan chatMessage
77
78 // the log channel is for secondary messages, like logging, errors, and debug information
79 // from local and remove subproceses.
80 termLogCh chan string
81
82 // protects following
83 mu sync.Mutex
84 oldState *term.State
85 // Tracks branches that were pushed during the session
86 pushedBranches map[string]struct{}
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +000087
88 // Pending message count, for graceful shutdown
89 messageWaitGroup sync.WaitGroup
Earl Lee2e463fb2025-04-17 11:22:22 -070090}
91
92type chatMessage struct {
93 idx int
94 sender string
95 content string
96 thinking bool
97}
98
David Crawshaw93fec602025-05-05 08:40:06 -070099func New(agent loop.CodingAgent, httpURL string) *TermUI {
100 return &TermUI{
Earl Lee2e463fb2025-04-17 11:22:22 -0700101 agent: agent,
102 stdin: os.Stdin,
103 stdout: os.Stdout,
104 stderr: os.Stderr,
105 httpURL: httpURL,
106 chatMsgCh: make(chan chatMessage, 1),
107 termLogCh: make(chan string, 1),
108 pushedBranches: make(map[string]struct{}),
109 }
110}
111
David Crawshaw93fec602025-05-05 08:40:06 -0700112func (ui *TermUI) Run(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700113 fmt.Println(`🌐 ` + ui.httpURL + `/`)
Earl Lee2e463fb2025-04-17 11:22:22 -0700114 fmt.Println(`šŸ’¬ type 'help' for help`)
115 fmt.Println()
116
117 // Start up the main terminal UI:
118 if err := ui.initializeTerminalUI(ctx); err != nil {
119 return err
120 }
121 go ui.receiveMessagesLoop(ctx)
122 if err := ui.inputLoop(ctx); err != nil {
123 return err
124 }
125 return nil
126}
127
David Crawshaw93fec602025-05-05 08:40:06 -0700128func (ui *TermUI) LogToolUse(resp *loop.AgentMessage) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700129 inputData := map[string]any{}
130 if err := json.Unmarshal([]byte(resp.ToolInput), &inputData); err != nil {
131 ui.AppendSystemMessage("error: %v", err)
132 return
133 }
134 buf := bytes.Buffer{}
135 if err := toolUseTmpl.Execute(&buf, map[string]any{"msg": resp, "input": inputData, "output": resp.ToolResult}); err != nil {
136 ui.AppendSystemMessage("error: %v", err)
137 return
138 }
139 ui.AppendSystemMessage("%s\n", buf.String())
140}
141
David Crawshaw93fec602025-05-05 08:40:06 -0700142func (ui *TermUI) receiveMessagesLoop(ctx context.Context) {
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700143 it := ui.agent.NewIterator(ctx, 0)
Earl Lee2e463fb2025-04-17 11:22:22 -0700144 bold := color.New(color.Bold).SprintFunc()
145 for {
146 select {
147 case <-ctx.Done():
148 return
149 default:
150 }
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700151 resp := it.Next()
152 if resp == nil {
153 return
154 }
Josh Bleecher Snyder4d544932025-05-07 13:33:53 +0000155 if resp.HideOutput {
156 continue
157 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700158 // Typically a user message will start the thinking and a (top-level
159 // conversation) end of turn will stop it.
160 thinking := !(resp.EndOfTurn && resp.ParentConversationID == nil)
161
162 switch resp.Type {
163 case loop.AgentMessageType:
Josh Bleecher Snyder2978ab22025-04-30 10:29:32 -0700164 ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "šŸ•“ļø ", content: resp.Content})
Earl Lee2e463fb2025-04-17 11:22:22 -0700165 case loop.ToolUseMessageType:
166 ui.LogToolUse(resp)
167 case loop.ErrorMessageType:
168 ui.AppendSystemMessage("āŒ %s", resp.Content)
169 case loop.BudgetMessageType:
170 ui.AppendSystemMessage("šŸ’° %s", resp.Content)
171 case loop.AutoMessageType:
172 ui.AppendSystemMessage("🧐 %s", resp.Content)
173 case loop.UserMessageType:
Josh Bleecher Snyderc2d26102025-04-30 06:19:43 -0700174 ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "🦸", content: resp.Content})
Earl Lee2e463fb2025-04-17 11:22:22 -0700175 case loop.CommitMessageType:
176 // Display each commit in the terminal
177 for _, commit := range resp.Commits {
178 if commit.PushedBranch != "" {
Sean McCullough43664f62025-04-20 16:13:03 -0700179 ui.AppendSystemMessage("šŸ”„ new commit: [%s] %s\npushed to: %s", commit.Hash[:8], commit.Subject, bold(commit.PushedBranch))
Earl Lee2e463fb2025-04-17 11:22:22 -0700180
181 // Track the pushed branch in our map
182 ui.mu.Lock()
183 ui.pushedBranches[commit.PushedBranch] = struct{}{}
184 ui.mu.Unlock()
185 } else {
186 ui.AppendSystemMessage("šŸ”„ new commit: [%s] %s", commit.Hash[:8], commit.Subject)
187 }
188 }
189 default:
190 ui.AppendSystemMessage("āŒ Unexpected Message Type %s %v", resp.Type, resp)
191 }
192 }
193}
194
David Crawshaw93fec602025-05-05 08:40:06 -0700195func (ui *TermUI) inputLoop(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700196 for {
197 line, err := ui.trm.ReadLine()
198 if errors.Is(err, io.EOF) {
199 ui.AppendSystemMessage("\n")
200 line = "exit"
201 } else if err != nil {
202 return err
203 }
204
205 line = strings.TrimSpace(line)
206
207 switch line {
208 case "?", "help":
Josh Bleecher Snyder85068942025-04-30 10:51:27 -0700209 ui.AppendSystemMessage(`General use:
210Use chat to ask sketch to tackle a task or answer a question about this repo.
211
212Special commands:
213- help, ? : Show this help message
214- budget : Show original budget
215- usage, cost : Show current token usage and cost
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000216- browser, open, b : Open current conversation in browser
Earl Lee2e463fb2025-04-17 11:22:22 -0700217- stop, cancel, abort : Cancel the current operation
Josh Bleecher Snyder85068942025-04-30 10:51:27 -0700218- exit, quit, q : Exit sketch
219- ! <command> : Execute a shell command (e.g. !ls -la)`)
Earl Lee2e463fb2025-04-17 11:22:22 -0700220 case "budget":
221 originalBudget := ui.agent.OriginalBudget()
222 ui.AppendSystemMessage("šŸ’° Budget summary:")
223 if originalBudget.MaxResponses > 0 {
224 ui.AppendSystemMessage("- Max responses: %d", originalBudget.MaxResponses)
225 }
226 if originalBudget.MaxWallTime > 0 {
227 ui.AppendSystemMessage("- Max wall time: %v", originalBudget.MaxWallTime)
228 }
229 ui.AppendSystemMessage("- Max total cost: %0.2f", originalBudget.MaxDollars)
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000230 case "browser", "open", "b":
231 if ui.httpURL != "" {
232 ui.AppendSystemMessage("🌐 Opening %s in browser", ui.httpURL)
233 go ui.agent.OpenBrowser(ui.httpURL)
234 } else {
235 ui.AppendSystemMessage("āŒ No web URL available for this session")
236 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700237 case "usage", "cost":
238 totalUsage := ui.agent.TotalUsage()
239 ui.AppendSystemMessage("šŸ’° Current usage summary:")
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +0000240 ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens())))
241 ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700242 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
243 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
244 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
245 case "bye", "exit", "q", "quit":
246 ui.trm.SetPrompt("")
247 // Display final usage stats
248 totalUsage := ui.agent.TotalUsage()
249 ui.AppendSystemMessage("šŸ’° Final usage summary:")
Josh Bleecher Snydera0801ad2025-04-25 19:34:53 +0000250 ui.AppendSystemMessage("- Input tokens: %s", humanize.Comma(int64(totalUsage.TotalInputTokens())))
251 ui.AppendSystemMessage("- Output tokens: %s", humanize.Comma(int64(totalUsage.OutputTokens)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700252 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
253 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
254 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
255
256 // Display pushed branches
257 ui.mu.Lock()
258 if len(ui.pushedBranches) > 0 {
259 // Convert map keys to a slice for display
260 branches := make([]string, 0, len(ui.pushedBranches))
261 for branch := range ui.pushedBranches {
262 branches = append(branches, branch)
263 }
264
Josh Bleecher Snyder8fdf7532025-05-06 00:56:12 +0000265 initialCommitRef := getShortSHA(ui.agent.InitialCommit())
Earl Lee2e463fb2025-04-17 11:22:22 -0700266 if len(branches) == 1 {
267 ui.AppendSystemMessage("\nšŸ”„ Branch pushed during session: %s", branches[0])
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000268 ui.AppendSystemMessage("šŸ’ To add those changes to your branch: git cherry-pick %s..%s", initialCommitRef, branches[0])
Earl Lee2e463fb2025-04-17 11:22:22 -0700269 } else {
270 ui.AppendSystemMessage("\nšŸ”„ Branches pushed during session:")
271 for _, branch := range branches {
272 ui.AppendSystemMessage("- %s", branch)
273 }
274 ui.AppendSystemMessage("\nšŸ’ To add all those changes to your branch:")
275 for _, branch := range branches {
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000276 ui.AppendSystemMessage("git cherry-pick %s..%s", initialCommitRef, branch)
Earl Lee2e463fb2025-04-17 11:22:22 -0700277 }
278 }
279 }
280 ui.mu.Unlock()
281
282 ui.AppendSystemMessage("\nšŸ‘‹ Goodbye!")
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000283 // Wait for all pending messages to be processed before exiting
284 ui.messageWaitGroup.Wait()
Earl Lee2e463fb2025-04-17 11:22:22 -0700285 return nil
286 case "stop", "cancel", "abort":
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000287 ui.agent.CancelTurn(fmt.Errorf("user canceled the operation"))
Earl Lee2e463fb2025-04-17 11:22:22 -0700288 case "panic":
289 panic("user forced a panic")
290 default:
291 if line == "" {
292 continue
293 }
294 if strings.HasPrefix(line, "!") {
295 // Execute as shell command
296 line = line[1:] // remove the '!' prefix
297 sendToLLM := strings.HasPrefix(line, "!")
298 if sendToLLM {
299 line = line[1:] // remove the second '!'
300 }
301
302 // Create a cmd and run it
303 // TODO: ui.trm contains a mutex inside its write call.
304 // It is potentially safe to attach ui.trm directly to this
305 // cmd object's Stdout/Stderr and stream the output.
306 // That would make a big difference for, e.g. wget.
307 cmd := exec.Command("bash", "-c", line)
308 out, err := cmd.CombinedOutput()
309 ui.AppendSystemMessage("%s", out)
310 if err != nil {
311 ui.AppendSystemMessage("āŒ Command error: %v", err)
312 }
313 if sendToLLM {
314 // Send the command and its output to the agent
315 message := fmt.Sprintf("I ran the command: `%s`\nOutput:\n```\n%s```", line, out)
316 if err != nil {
317 message += fmt.Sprintf("\n\nError: %v", err)
318 }
319 ui.agent.UserMessage(ctx, message)
320 }
321 continue
322 }
323
324 // Send it to the LLM
325 // chatMsg := chatMessage{sender: "you", content: line}
326 // ui.sendChatMessage(chatMsg)
327 ui.agent.UserMessage(ctx, line)
328 }
329 }
330}
331
David Crawshaw93fec602025-05-05 08:40:06 -0700332func (ui *TermUI) updatePrompt(thinking bool) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700333 var t string
334
335 if thinking {
336 // Emoji don't seem to work here? Messes up my terminal.
337 t = "*"
338 }
Josh Bleecher Snyder23b6a2d2025-04-30 04:07:52 +0000339 p := fmt.Sprintf("%s ($%0.2f/%0.2f)%s> ",
340 ui.httpURL, ui.agent.TotalUsage().TotalCostUSD, ui.agent.OriginalBudget().MaxDollars, t)
Earl Lee2e463fb2025-04-17 11:22:22 -0700341 ui.trm.SetPrompt(p)
342}
343
David Crawshaw93fec602025-05-05 08:40:06 -0700344func (ui *TermUI) initializeTerminalUI(ctx context.Context) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700345 ui.mu.Lock()
346 defer ui.mu.Unlock()
347
348 if !term.IsTerminal(int(ui.stdin.Fd())) {
Philip Zeyligerc5b8ed42025-05-05 20:28:34 +0000349 return fmt.Errorf("this command requires terminal I/O when termui=true")
Earl Lee2e463fb2025-04-17 11:22:22 -0700350 }
351
352 oldState, err := term.MakeRaw(int(ui.stdin.Fd()))
353 if err != nil {
354 return err
355 }
356 ui.oldState = oldState
357 ui.trm = term.NewTerminal(ui.stdin, "")
358 width, height, err := term.GetSize(int(ui.stdin.Fd()))
359 if err != nil {
360 return fmt.Errorf("Error getting terminal size: %v\n", err)
361 }
362 ui.trm.SetSize(width, height)
363 // Handle terminal resizes...
364 sig := make(chan os.Signal, 1)
365 signal.Notify(sig, syscall.SIGWINCH)
366 go func() {
367 for {
368 <-sig
369 newWidth, newHeight, err := term.GetSize(int(ui.stdin.Fd()))
370 if err != nil {
371 continue
372 }
373 if newWidth != width || newHeight != height {
374 width, height = newWidth, newHeight
375 ui.trm.SetSize(width, height)
376 }
377 }
378 }()
379
380 ui.updatePrompt(false)
381
382 // This is the only place where we should call fe.trm.Write:
383 go func() {
Sean McCullougha4b19f82025-05-05 10:22:59 -0700384 var lastMsg *chatMessage
Earl Lee2e463fb2025-04-17 11:22:22 -0700385 for {
386 select {
387 case <-ctx.Done():
388 return
389 case msg := <-ui.chatMsgCh:
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000390 func() {
391 defer ui.messageWaitGroup.Done()
Sean McCullougha4b19f82025-05-05 10:22:59 -0700392 // Update prompt before writing, because otherwise it doesn't redraw the prompt.
393 ui.updatePrompt(msg.thinking)
394 lastMsg = &msg
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000395 // Sometimes claude doesn't say anything when it runs tools.
396 // No need to output anything in that case.
397 if strings.TrimSpace(msg.content) == "" {
398 return
399 }
400 s := fmt.Sprintf("%s %s\n", msg.sender, msg.content)
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000401 ui.trm.Write([]byte(s))
402 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700403 case logLine := <-ui.termLogCh:
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000404 func() {
405 defer ui.messageWaitGroup.Done()
Sean McCullougha4b19f82025-05-05 10:22:59 -0700406 if lastMsg != nil {
407 ui.updatePrompt(lastMsg.thinking)
408 } else {
409 ui.updatePrompt(false)
410 }
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000411 b := []byte(logLine + "\n")
412 ui.trm.Write(b)
413 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700414 }
415 }
416 }()
417
418 return nil
419}
420
David Crawshaw93fec602025-05-05 08:40:06 -0700421func (ui *TermUI) RestoreOldState() error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700422 ui.mu.Lock()
423 defer ui.mu.Unlock()
424 return term.Restore(int(ui.stdin.Fd()), ui.oldState)
425}
426
427// AppendChatMessage is for showing responses the user's request, conversational dialog etc
David Crawshaw93fec602025-05-05 08:40:06 -0700428func (ui *TermUI) AppendChatMessage(msg chatMessage) {
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000429 ui.messageWaitGroup.Add(1)
Earl Lee2e463fb2025-04-17 11:22:22 -0700430 ui.chatMsgCh <- msg
431}
432
433// AppendSystemMessage is for debug information, errors and such that are not part of the "conversation" per se,
434// but still need to be shown to the user.
David Crawshaw93fec602025-05-05 08:40:06 -0700435func (ui *TermUI) AppendSystemMessage(fmtString string, args ...any) {
Josh Bleecher Snyderb1e81572025-05-01 00:53:27 +0000436 ui.messageWaitGroup.Add(1)
Earl Lee2e463fb2025-04-17 11:22:22 -0700437 ui.termLogCh <- fmt.Sprintf(fmtString, args...)
438}
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000439
Josh Bleecher Snyder8fdf7532025-05-06 00:56:12 +0000440// getShortSHA returns the short SHA for the given git reference, falling back to the original SHA on error.
441func getShortSHA(sha string) string {
442 cmd := exec.Command("git", "rev-parse", "--short", sha)
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000443 shortSha, err := cmd.Output()
444 if err == nil {
445 shortStr := strings.TrimSpace(string(shortSha))
446 if shortStr != "" {
447 return shortStr
448 }
449 }
Josh Bleecher Snyder0137a7f2025-04-30 01:16:35 +0000450 return sha
451}