blob: 00f7bae166014f73c0f557d79ddb1777b23c01b4 [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
19 "github.com/fatih/color"
20 "golang.org/x/term"
21 "sketch.dev/loop"
22)
23
24var (
25 // toolUseTemplTxt defines how tool invocations appear in the terminal UI.
26 // Keep this template in sync with the tools defined in claudetool package
27 // and registered in loop/agent.go.
28 // Add formatting for new tools as they are created.
29 // TODO: should this be part of tool definition to make it harder to forget to set up?
30 toolUseTemplTxt = `{{if .msg.ToolError}}šŸ™ˆ {{end -}}
31{{if eq .msg.ToolName "think" -}}
32 🧠 {{.input.thoughts -}}
33{{else if eq .msg.ToolName "keyword_search" -}}
34 šŸ” {{ .input.query}}: {{.input.keywords -}}
35{{else if eq .msg.ToolName "bash" -}}
Philip Zeyligerb60f0f22025-04-23 18:19:32 +000036 šŸ–„ļø{{if .input.background}}šŸ”„{{end}} {{ .input.command -}}
Earl Lee2e463fb2025-04-17 11:22:22 -070037{{else if eq .msg.ToolName "patch" -}}
38 āŒØļø {{.input.path -}}
39{{else if eq .msg.ToolName "done" -}}
40{{/* nothing to show here, the agent will write more in its next message */}}
41{{else if eq .msg.ToolName "title" -}}
42 šŸ·ļø {{.input.title -}}
43{{else if eq .msg.ToolName "str_replace_editor" -}}
44 āœļø {{.input.file_path -}}
45{{else if eq .msg.ToolName "codereview" -}}
46 šŸ› Running automated code review, may be slow
47{{else -}}
48 šŸ› ļø {{ .msg.ToolName}}: {{.msg.ToolInput -}}
49{{end -}}
50`
51 toolUseTmpl = template.Must(template.New("tool_use").Parse(toolUseTemplTxt))
52)
53
54type termUI struct {
55 stdin *os.File
56 stdout *os.File
57 stderr *os.File
58
59 agent loop.CodingAgent
60 httpURL string
61
62 trm *term.Terminal
63
64 // the chatMsgCh channel is for "conversation" messages, like responses to user input
65 // from the LLM, or output from executing slash-commands issued by the user.
66 chatMsgCh chan chatMessage
67
68 // the log channel is for secondary messages, like logging, errors, and debug information
69 // from local and remove subproceses.
70 termLogCh chan string
71
72 // protects following
73 mu sync.Mutex
74 oldState *term.State
75 // Tracks branches that were pushed during the session
76 pushedBranches map[string]struct{}
77}
78
79type chatMessage struct {
80 idx int
81 sender string
82 content string
83 thinking bool
84}
85
86func New(agent loop.CodingAgent, httpURL string) *termUI {
87 return &termUI{
88 agent: agent,
89 stdin: os.Stdin,
90 stdout: os.Stdout,
91 stderr: os.Stderr,
92 httpURL: httpURL,
93 chatMsgCh: make(chan chatMessage, 1),
94 termLogCh: make(chan string, 1),
95 pushedBranches: make(map[string]struct{}),
96 }
97}
98
99func (ui *termUI) Run(ctx context.Context) error {
100 fmt.Println(`šŸŽØ Welcome to Sketch`)
101 fmt.Println(`🌐 ` + ui.httpURL + `/`)
102 fmt.Println(`šŸ“ Initial Commit: ` + ui.agent.InitialCommit())
103 fmt.Println(`šŸ’¬ type 'help' for help`)
104 fmt.Println()
105
106 // Start up the main terminal UI:
107 if err := ui.initializeTerminalUI(ctx); err != nil {
108 return err
109 }
110 go ui.receiveMessagesLoop(ctx)
111 if err := ui.inputLoop(ctx); err != nil {
112 return err
113 }
114 return nil
115}
116
117func (ui *termUI) LogToolUse(resp loop.AgentMessage) {
118 inputData := map[string]any{}
119 if err := json.Unmarshal([]byte(resp.ToolInput), &inputData); err != nil {
120 ui.AppendSystemMessage("error: %v", err)
121 return
122 }
123 buf := bytes.Buffer{}
124 if err := toolUseTmpl.Execute(&buf, map[string]any{"msg": resp, "input": inputData, "output": resp.ToolResult}); err != nil {
125 ui.AppendSystemMessage("error: %v", err)
126 return
127 }
128 ui.AppendSystemMessage("%s\n", buf.String())
129}
130
131func (ui *termUI) receiveMessagesLoop(ctx context.Context) {
132 bold := color.New(color.Bold).SprintFunc()
133 for {
134 select {
135 case <-ctx.Done():
136 return
137 default:
138 }
139 resp := ui.agent.WaitForMessage(ctx)
140 // Typically a user message will start the thinking and a (top-level
141 // conversation) end of turn will stop it.
142 thinking := !(resp.EndOfTurn && resp.ParentConversationID == nil)
143
144 switch resp.Type {
145 case loop.AgentMessageType:
146 ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "šŸ•“ļø", content: resp.Content})
147 case loop.ToolUseMessageType:
148 ui.LogToolUse(resp)
149 case loop.ErrorMessageType:
150 ui.AppendSystemMessage("āŒ %s", resp.Content)
151 case loop.BudgetMessageType:
152 ui.AppendSystemMessage("šŸ’° %s", resp.Content)
153 case loop.AutoMessageType:
154 ui.AppendSystemMessage("🧐 %s", resp.Content)
155 case loop.UserMessageType:
156 ui.AppendChatMessage(chatMessage{thinking: thinking, idx: resp.Idx, sender: "šŸ‘¤ļø", content: resp.Content})
157 case loop.CommitMessageType:
158 // Display each commit in the terminal
159 for _, commit := range resp.Commits {
160 if commit.PushedBranch != "" {
Sean McCullough43664f62025-04-20 16:13:03 -0700161 ui.AppendSystemMessage("šŸ”„ new commit: [%s] %s\npushed to: %s", commit.Hash[:8], commit.Subject, bold(commit.PushedBranch))
Earl Lee2e463fb2025-04-17 11:22:22 -0700162
163 // Track the pushed branch in our map
164 ui.mu.Lock()
165 ui.pushedBranches[commit.PushedBranch] = struct{}{}
166 ui.mu.Unlock()
167 } else {
168 ui.AppendSystemMessage("šŸ”„ new commit: [%s] %s", commit.Hash[:8], commit.Subject)
169 }
170 }
171 default:
172 ui.AppendSystemMessage("āŒ Unexpected Message Type %s %v", resp.Type, resp)
173 }
174 }
175}
176
177func (ui *termUI) inputLoop(ctx context.Context) error {
178 for {
179 line, err := ui.trm.ReadLine()
180 if errors.Is(err, io.EOF) {
181 ui.AppendSystemMessage("\n")
182 line = "exit"
183 } else if err != nil {
184 return err
185 }
186
187 line = strings.TrimSpace(line)
188
189 switch line {
190 case "?", "help":
191 ui.AppendSystemMessage(`Available commands:
192- help, ? : Show this help message
193- budget : Show original budget
194- usage, cost : Show current token usage and cost
195- stop, cancel, abort : Cancel the current operation
196- exit, quit, q : Exit the application
197- ! <command> : Execute shell command (e.g. !ls -la)`)
198 case "budget":
199 originalBudget := ui.agent.OriginalBudget()
200 ui.AppendSystemMessage("šŸ’° Budget summary:")
201 if originalBudget.MaxResponses > 0 {
202 ui.AppendSystemMessage("- Max responses: %d", originalBudget.MaxResponses)
203 }
204 if originalBudget.MaxWallTime > 0 {
205 ui.AppendSystemMessage("- Max wall time: %v", originalBudget.MaxWallTime)
206 }
207 ui.AppendSystemMessage("- Max total cost: %0.2f", originalBudget.MaxDollars)
208 case "usage", "cost":
209 totalUsage := ui.agent.TotalUsage()
210 ui.AppendSystemMessage("šŸ’° Current usage summary:")
211 ui.AppendSystemMessage("- Input tokens: %d [Cache: read=%d, creation=%d]", totalUsage.InputTokens, totalUsage.CacheReadInputTokens, totalUsage.CacheCreationInputTokens)
212 ui.AppendSystemMessage("- Output tokens: %d", totalUsage.OutputTokens)
213 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
214 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
215 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
216 case "bye", "exit", "q", "quit":
217 ui.trm.SetPrompt("")
218 // Display final usage stats
219 totalUsage := ui.agent.TotalUsage()
220 ui.AppendSystemMessage("šŸ’° Final usage summary:")
221 ui.AppendSystemMessage("- Input tokens: %d [Cache: read=%d, creation=%d]", totalUsage.InputTokens, totalUsage.CacheReadInputTokens, totalUsage.CacheCreationInputTokens)
222 ui.AppendSystemMessage("- Output tokens: %d", totalUsage.OutputTokens)
223 ui.AppendSystemMessage("- Responses: %d", totalUsage.Responses)
224 ui.AppendSystemMessage("- Wall time: %s", totalUsage.WallTime().Round(time.Second))
225 ui.AppendSystemMessage("- Total cost: $%0.2f", totalUsage.TotalCostUSD)
226
227 // Display pushed branches
228 ui.mu.Lock()
229 if len(ui.pushedBranches) > 0 {
230 // Convert map keys to a slice for display
231 branches := make([]string, 0, len(ui.pushedBranches))
232 for branch := range ui.pushedBranches {
233 branches = append(branches, branch)
234 }
235
236 if len(branches) == 1 {
237 ui.AppendSystemMessage("\nšŸ”„ Branch pushed during session: %s", branches[0])
238 ui.AppendSystemMessage("šŸ’ To add those changes to your branch: git cherry-pick %s..%s", ui.agent.InitialCommit(), branches[0])
239 } else {
240 ui.AppendSystemMessage("\nšŸ”„ Branches pushed during session:")
241 for _, branch := range branches {
242 ui.AppendSystemMessage("- %s", branch)
243 }
244 ui.AppendSystemMessage("\nšŸ’ To add all those changes to your branch:")
245 for _, branch := range branches {
246 ui.AppendSystemMessage("git cherry-pick %s..%s", ui.agent.InitialCommit(), branch)
247 }
248 }
249 }
250 ui.mu.Unlock()
251
252 ui.AppendSystemMessage("\nšŸ‘‹ Goodbye!")
253 return nil
254 case "stop", "cancel", "abort":
255 ui.agent.CancelInnerLoop(fmt.Errorf("user canceled the operation"))
256 case "panic":
257 panic("user forced a panic")
258 default:
259 if line == "" {
260 continue
261 }
262 if strings.HasPrefix(line, "!") {
263 // Execute as shell command
264 line = line[1:] // remove the '!' prefix
265 sendToLLM := strings.HasPrefix(line, "!")
266 if sendToLLM {
267 line = line[1:] // remove the second '!'
268 }
269
270 // Create a cmd and run it
271 // TODO: ui.trm contains a mutex inside its write call.
272 // It is potentially safe to attach ui.trm directly to this
273 // cmd object's Stdout/Stderr and stream the output.
274 // That would make a big difference for, e.g. wget.
275 cmd := exec.Command("bash", "-c", line)
276 out, err := cmd.CombinedOutput()
277 ui.AppendSystemMessage("%s", out)
278 if err != nil {
279 ui.AppendSystemMessage("āŒ Command error: %v", err)
280 }
281 if sendToLLM {
282 // Send the command and its output to the agent
283 message := fmt.Sprintf("I ran the command: `%s`\nOutput:\n```\n%s```", line, out)
284 if err != nil {
285 message += fmt.Sprintf("\n\nError: %v", err)
286 }
287 ui.agent.UserMessage(ctx, message)
288 }
289 continue
290 }
291
292 // Send it to the LLM
293 // chatMsg := chatMessage{sender: "you", content: line}
294 // ui.sendChatMessage(chatMsg)
295 ui.agent.UserMessage(ctx, line)
296 }
297 }
298}
299
300func (ui *termUI) updatePrompt(thinking bool) {
301 var t string
302
303 if thinking {
304 // Emoji don't seem to work here? Messes up my terminal.
305 t = "*"
306 }
307 p := fmt.Sprintf("%s/ %s($%0.2f/%0.2f)%s> ",
308 ui.httpURL, ui.agent.WorkingDir(), ui.agent.TotalUsage().TotalCostUSD, ui.agent.OriginalBudget().MaxDollars, t)
309 ui.trm.SetPrompt(p)
310}
311
312func (ui *termUI) initializeTerminalUI(ctx context.Context) error {
313 ui.mu.Lock()
314 defer ui.mu.Unlock()
315
316 if !term.IsTerminal(int(ui.stdin.Fd())) {
317 return fmt.Errorf("this command requires terminal I/O")
318 }
319
320 oldState, err := term.MakeRaw(int(ui.stdin.Fd()))
321 if err != nil {
322 return err
323 }
324 ui.oldState = oldState
325 ui.trm = term.NewTerminal(ui.stdin, "")
326 width, height, err := term.GetSize(int(ui.stdin.Fd()))
327 if err != nil {
328 return fmt.Errorf("Error getting terminal size: %v\n", err)
329 }
330 ui.trm.SetSize(width, height)
331 // Handle terminal resizes...
332 sig := make(chan os.Signal, 1)
333 signal.Notify(sig, syscall.SIGWINCH)
334 go func() {
335 for {
336 <-sig
337 newWidth, newHeight, err := term.GetSize(int(ui.stdin.Fd()))
338 if err != nil {
339 continue
340 }
341 if newWidth != width || newHeight != height {
342 width, height = newWidth, newHeight
343 ui.trm.SetSize(width, height)
344 }
345 }
346 }()
347
348 ui.updatePrompt(false)
349
350 // This is the only place where we should call fe.trm.Write:
351 go func() {
352 for {
353 select {
354 case <-ctx.Done():
355 return
356 case msg := <-ui.chatMsgCh:
357 // Sometimes claude doesn't say anything when it runs tools.
358 // No need to output anything in that case.
359 if strings.TrimSpace(msg.content) == "" {
360 break
361 }
362 s := fmt.Sprintf("%s %s\n", msg.sender, msg.content)
363 // Update prompt before writing, because otherwise it doesn't redraw the prompt.
364 ui.updatePrompt(msg.thinking)
365 ui.trm.Write([]byte(s))
366 case logLine := <-ui.termLogCh:
367 b := []byte(logLine + "\n")
368 ui.trm.Write(b)
369 }
370 }
371 }()
372
373 return nil
374}
375
376func (ui *termUI) RestoreOldState() error {
377 ui.mu.Lock()
378 defer ui.mu.Unlock()
379 return term.Restore(int(ui.stdin.Fd()), ui.oldState)
380}
381
382// AppendChatMessage is for showing responses the user's request, conversational dialog etc
383func (ui *termUI) AppendChatMessage(msg chatMessage) {
384 ui.chatMsgCh <- msg
385}
386
387// AppendSystemMessage is for debug information, errors and such that are not part of the "conversation" per se,
388// but still need to be shown to the user.
389func (ui *termUI) AppendSystemMessage(fmtString string, args ...any) {
390 ui.termLogCh <- fmt.Sprintf(fmtString, args...)
391}