blob: 82846ac11df297ab75e49df682512bd69d390d79 [file] [log] [blame]
Earl Lee2e463fb2025-04-17 11:22:22 -07001// Package server provides HTTP server functionality for the sketch loop.
2package server
3
4import (
Sean McCulloughbaa2b592025-04-23 10:40:08 -07005 "context"
Earl Lee2e463fb2025-04-17 11:22:22 -07006 "encoding/base64"
7 "encoding/json"
8 "fmt"
9 "html"
10 "io"
11 "io/fs"
12 "log/slog"
13 "net/http"
14 "net/http/pprof"
15 "os"
16 "os/exec"
17 "strconv"
18 "strings"
19 "sync"
20 "syscall"
21 "time"
22
Philip Zeyliger176de792025-04-21 12:25:18 -070023 "sketch.dev/loop/server/gzhandler"
24
Earl Lee2e463fb2025-04-17 11:22:22 -070025 "github.com/creack/pty"
26 "sketch.dev/ant"
27 "sketch.dev/loop"
Philip Zeyliger2032b1c2025-04-23 19:40:42 -070028 "sketch.dev/webui"
Earl Lee2e463fb2025-04-17 11:22:22 -070029)
30
31// terminalSession represents a terminal session with its PTY and the event channel
32type terminalSession struct {
33 pty *os.File
34 eventsClients map[chan []byte]bool
35 lastEventClientID int
36 eventsClientsMutex sync.Mutex
37 cmd *exec.Cmd
38}
39
40// TerminalMessage represents a message sent from the client for terminal resize events
41type TerminalMessage struct {
42 Type string `json:"type"`
43 Cols uint16 `json:"cols"`
44 Rows uint16 `json:"rows"`
45}
46
47// TerminalResponse represents the response for a new terminal creation
48type TerminalResponse struct {
49 SessionID string `json:"sessionId"`
50}
51
Sean McCulloughd9f13372025-04-21 15:08:49 -070052type State struct {
Philip Zeyliger99a9a022025-04-27 15:15:25 +000053 MessageCount int `json:"message_count"`
54 TotalUsage *ant.CumulativeUsage `json:"total_usage,omitempty"`
55 InitialCommit string `json:"initial_commit"`
56 Title string `json:"title"`
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +000057 BranchName string `json:"branch_name,omitempty"`
Philip Zeyliger99a9a022025-04-27 15:15:25 +000058 Hostname string `json:"hostname"` // deprecated
59 WorkingDir string `json:"working_dir"` // deprecated
60 OS string `json:"os"` // deprecated
61 GitOrigin string `json:"git_origin,omitempty"`
62 OutstandingLLMCalls int `json:"outstanding_llm_calls"`
63 OutstandingToolCalls []string `json:"outstanding_tool_calls"`
Philip Zeyligerc72fff52025-04-29 20:17:54 +000064 SessionID string `json:"session_id"`
65 SSHAvailable bool `json:"ssh_available"`
66 SSHError string `json:"ssh_error,omitempty"`
Philip Zeyliger2c4db092025-04-28 16:57:50 -070067 InContainer bool `json:"in_container"`
68 FirstMessageIndex int `json:"first_message_index"`
Philip Zeyligerd1402952025-04-23 03:54:37 +000069
Philip Zeyliger18532b22025-04-23 21:11:46 +000070 OutsideHostname string `json:"outside_hostname,omitempty"`
71 InsideHostname string `json:"inside_hostname,omitempty"`
72 OutsideOS string `json:"outside_os,omitempty"`
73 InsideOS string `json:"inside_os,omitempty"`
74 OutsideWorkingDir string `json:"outside_working_dir,omitempty"`
75 InsideWorkingDir string `json:"inside_working_dir,omitempty"`
Sean McCulloughd9f13372025-04-21 15:08:49 -070076}
77
Sean McCulloughbaa2b592025-04-23 10:40:08 -070078type InitRequest struct {
79 HostAddr string `json:"host_addr"`
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +000080 OutsideHTTP string `json:"outside_http"`
Sean McCulloughbaa2b592025-04-23 10:40:08 -070081 GitRemoteAddr string `json:"git_remote_addr"`
82 Commit string `json:"commit"`
83 SSHAuthorizedKeys []byte `json:"ssh_authorized_keys"`
84 SSHServerIdentity []byte `json:"ssh_server_identity"`
Philip Zeyligerc72fff52025-04-29 20:17:54 +000085 SSHAvailable bool `json:"ssh_available"`
86 SSHError string `json:"ssh_error,omitempty"`
Sean McCulloughbaa2b592025-04-23 10:40:08 -070087}
88
Earl Lee2e463fb2025-04-17 11:22:22 -070089// Server serves sketch HTTP. Server implements http.Handler.
90type Server struct {
91 mux *http.ServeMux
92 agent loop.CodingAgent
93 hostname string
94 logFile *os.File
95 // Mutex to protect terminalSessions
96 ptyMutex sync.Mutex
97 terminalSessions map[string]*terminalSession
Philip Zeyligerc72fff52025-04-29 20:17:54 +000098 sshAvailable bool
99 sshError string
Earl Lee2e463fb2025-04-17 11:22:22 -0700100}
101
102func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
103 s.mux.ServeHTTP(w, r)
104}
105
106// New creates a new HTTP server.
107func New(agent loop.CodingAgent, logFile *os.File) (*Server, error) {
108 s := &Server{
109 mux: http.NewServeMux(),
110 agent: agent,
111 hostname: getHostname(),
112 logFile: logFile,
113 terminalSessions: make(map[string]*terminalSession),
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000114 sshAvailable: false,
115 sshError: "",
Earl Lee2e463fb2025-04-17 11:22:22 -0700116 }
117
118 webBundle, err := webui.Build()
119 if err != nil {
120 return nil, fmt.Errorf("failed to build web bundle, did you run 'go generate sketch.dev/loop/...'?: %w", err)
121 }
122
123 s.mux.HandleFunc("/diff", func(w http.ResponseWriter, r *http.Request) {
124 // Check if a specific commit hash was requested
125 commit := r.URL.Query().Get("commit")
126
127 // Get the diff, optionally for a specific commit
128 var diff string
129 var err error
130 if commit != "" {
131 // Validate the commit hash format
132 if !isValidGitSHA(commit) {
133 http.Error(w, fmt.Sprintf("Invalid git commit SHA format: %s", commit), http.StatusBadRequest)
134 return
135 }
136
137 diff, err = agent.Diff(&commit)
138 } else {
139 diff, err = agent.Diff(nil)
140 }
141
142 if err != nil {
143 http.Error(w, fmt.Sprintf("Error generating diff: %v", err), http.StatusInternalServerError)
144 return
145 }
146
147 w.Header().Set("Content-Type", "text/plain")
148 w.Write([]byte(diff))
149 })
150
151 // Handler for initialization called by host sketch binary when inside docker.
152 s.mux.HandleFunc("/init", func(w http.ResponseWriter, r *http.Request) {
153 defer func() {
154 if err := recover(); err != nil {
155 slog.ErrorContext(r.Context(), "/init panic", slog.Any("recovered_err", err))
156
157 // Return an error response to the client
158 http.Error(w, fmt.Sprintf("panic: %v\n", err), http.StatusInternalServerError)
159 }
160 }()
161
162 if r.Method != "POST" {
163 http.Error(w, "POST required", http.StatusBadRequest)
164 return
165 }
166
167 body, err := io.ReadAll(r.Body)
168 r.Body.Close()
169 if err != nil {
170 http.Error(w, "failed to read request body: "+err.Error(), http.StatusBadRequest)
171 return
172 }
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700173
174 m := &InitRequest{}
175 if err := json.Unmarshal(body, m); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700176 http.Error(w, "bad request body: "+err.Error(), http.StatusBadRequest)
177 return
178 }
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700179
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000180 // Store SSH availability info
181 s.sshAvailable = m.SSHAvailable
182 s.sshError = m.SSHError
183
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700184 // Start the SSH server if the init request included ssh keys.
185 if len(m.SSHAuthorizedKeys) > 0 && len(m.SSHServerIdentity) > 0 {
186 go func() {
187 ctx := context.Background()
188 if err := s.ServeSSH(ctx, m.SSHServerIdentity, m.SSHAuthorizedKeys); err != nil {
189 slog.ErrorContext(r.Context(), "/init ServeSSH", slog.String("err", err.Error()))
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000190 // Update SSH error if server fails to start
191 s.sshAvailable = false
192 s.sshError = err.Error()
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700193 }
194 }()
195 }
196
Earl Lee2e463fb2025-04-17 11:22:22 -0700197 ini := loop.AgentInit{
198 WorkingDir: "/app",
199 InDocker: true,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700200 Commit: m.Commit,
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000201 OutsideHTTP: m.OutsideHTTP,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700202 GitRemoteAddr: m.GitRemoteAddr,
203 HostAddr: m.HostAddr,
Earl Lee2e463fb2025-04-17 11:22:22 -0700204 }
205 if err := agent.Init(ini); err != nil {
206 http.Error(w, "init failed: "+err.Error(), http.StatusInternalServerError)
207 return
208 }
209 w.Header().Set("Content-Type", "application/json")
210 io.WriteString(w, "{}\n")
211 })
212
213 // Handler for /messages?start=N&end=M (start/end are optional)
214 s.mux.HandleFunc("/messages", func(w http.ResponseWriter, r *http.Request) {
215 w.Header().Set("Content-Type", "application/json")
216
217 // Extract query parameters for range
218 var start, end int
219 var err error
220
221 currentCount := agent.MessageCount()
222
223 startParam := r.URL.Query().Get("start")
224 if startParam != "" {
225 start, err = strconv.Atoi(startParam)
226 if err != nil {
227 http.Error(w, "Invalid 'start' parameter", http.StatusBadRequest)
228 return
229 }
230 }
231
232 endParam := r.URL.Query().Get("end")
233 if endParam != "" {
234 end, err = strconv.Atoi(endParam)
235 if err != nil {
236 http.Error(w, "Invalid 'end' parameter", http.StatusBadRequest)
237 return
238 }
239 } else {
240 end = currentCount
241 }
242
243 if start < 0 || start > end || end > currentCount {
244 http.Error(w, fmt.Sprintf("Invalid range: start %d end %d currentCount %d", start, end, currentCount), http.StatusBadRequest)
245 return
246 }
247
248 start = max(0, start)
249 end = min(agent.MessageCount(), end)
250 messages := agent.Messages(start, end)
251
252 // Create a JSON encoder with indentation for pretty-printing
253 encoder := json.NewEncoder(w)
254 encoder.SetIndent("", " ") // Two spaces for each indentation level
255
256 err = encoder.Encode(messages)
257 if err != nil {
258 http.Error(w, err.Error(), http.StatusInternalServerError)
259 }
260 })
261
262 // Handler for /logs - displays the contents of the log file
263 s.mux.HandleFunc("/logs", func(w http.ResponseWriter, r *http.Request) {
264 if s.logFile == nil {
265 http.Error(w, "log file not set", http.StatusNotFound)
266 return
267 }
268 logContents, err := os.ReadFile(s.logFile.Name())
269 if err != nil {
270 http.Error(w, "error reading log file: "+err.Error(), http.StatusInternalServerError)
271 return
272 }
273 w.Header().Set("Content-Type", "text/html; charset=utf-8")
274 fmt.Fprintf(w, "<!DOCTYPE html>\n<html>\n<head>\n<title>Sketchy Log File</title>\n</head>\n<body>\n")
275 fmt.Fprintf(w, "<pre>%s</pre>\n", html.EscapeString(string(logContents)))
276 fmt.Fprintf(w, "</body>\n</html>")
277 })
278
279 // Handler for /download - downloads both messages and status as a JSON file
280 s.mux.HandleFunc("/download", func(w http.ResponseWriter, r *http.Request) {
281 // Set headers for file download
282 w.Header().Set("Content-Type", "application/octet-stream")
283
284 // Generate filename with format: sketch-YYYYMMDD-HHMMSS.json
285 timestamp := time.Now().Format("20060102-150405")
286 filename := fmt.Sprintf("sketch-%s.json", timestamp)
287
288 w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
289
290 // Get all messages
291 messageCount := agent.MessageCount()
292 messages := agent.Messages(0, messageCount)
293
294 // Get status information (usage and other metadata)
295 totalUsage := agent.TotalUsage()
296 hostname := getHostname()
297 workingDir := getWorkingDir()
298
299 // Create a combined structure with all information
300 downloadData := struct {
301 Messages []loop.AgentMessage `json:"messages"`
302 MessageCount int `json:"message_count"`
303 TotalUsage ant.CumulativeUsage `json:"total_usage"`
304 Hostname string `json:"hostname"`
305 WorkingDir string `json:"working_dir"`
306 DownloadTime string `json:"download_time"`
307 }{
308 Messages: messages,
309 MessageCount: messageCount,
310 TotalUsage: totalUsage,
311 Hostname: hostname,
312 WorkingDir: workingDir,
313 DownloadTime: time.Now().Format(time.RFC3339),
314 }
315
316 // Marshal the JSON with indentation for better readability
317 jsonData, err := json.MarshalIndent(downloadData, "", " ")
318 if err != nil {
319 http.Error(w, err.Error(), http.StatusInternalServerError)
320 return
321 }
322 w.Write(jsonData)
323 })
324
325 // The latter doesn't return until the number of messages has changed (from seen
326 // or from when this was called.)
327 s.mux.HandleFunc("/state", func(w http.ResponseWriter, r *http.Request) {
328 pollParam := r.URL.Query().Get("poll")
329 seenParam := r.URL.Query().Get("seen")
330
331 // Get the client's current message count (if provided)
332 clientMessageCount := -1
333 var err error
334 if seenParam != "" {
335 clientMessageCount, err = strconv.Atoi(seenParam)
336 if err != nil {
337 http.Error(w, "Invalid 'seen' parameter", http.StatusBadRequest)
338 return
339 }
340 }
341
342 serverMessageCount := agent.MessageCount()
343
344 // Let lazy clients not have to specify this.
345 if clientMessageCount == -1 {
346 clientMessageCount = serverMessageCount
347 }
348
349 if pollParam == "true" {
350 ch := make(chan string)
351 go func() {
352 // This is your blocking operation
353 agent.WaitForMessageCount(r.Context(), clientMessageCount)
354 close(ch)
355 }()
356 select {
357 case <-r.Context().Done():
358 slog.DebugContext(r.Context(), "abandoned poll request")
359 return
360 case <-time.After(90 * time.Second):
361 // Let the user call /state again to get the latest to limit how long our long polls hang out.
362 slog.DebugContext(r.Context(), "longish poll request")
363 break
364 case <-ch:
365 break
366 }
367 }
368
369 serverMessageCount = agent.MessageCount()
370 totalUsage := agent.TotalUsage()
371
372 w.Header().Set("Content-Type", "application/json")
373
Sean McCulloughd9f13372025-04-21 15:08:49 -0700374 state := State{
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000375 MessageCount: serverMessageCount,
376 TotalUsage: &totalUsage,
377 Hostname: s.hostname,
378 WorkingDir: getWorkingDir(),
379 InitialCommit: agent.InitialCommit(),
380 Title: agent.Title(),
Josh Bleecher Snyder47b19362025-04-30 01:34:14 +0000381 BranchName: agent.BranchName(),
Philip Zeyliger99a9a022025-04-27 15:15:25 +0000382 OS: agent.OS(),
383 OutsideHostname: agent.OutsideHostname(),
384 InsideHostname: s.hostname,
385 OutsideOS: agent.OutsideOS(),
386 InsideOS: agent.OS(),
387 OutsideWorkingDir: agent.OutsideWorkingDir(),
388 InsideWorkingDir: getWorkingDir(),
389 GitOrigin: agent.GitOrigin(),
390 OutstandingLLMCalls: agent.OutstandingLLMCallCount(),
391 OutstandingToolCalls: agent.OutstandingToolCalls(),
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000392 SessionID: agent.SessionID(),
393 SSHAvailable: s.sshAvailable,
394 SSHError: s.sshError,
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700395 InContainer: agent.IsInContainer(),
396 FirstMessageIndex: agent.FirstMessageIndex(),
Earl Lee2e463fb2025-04-17 11:22:22 -0700397 }
398
399 // Create a JSON encoder with indentation for pretty-printing
400 encoder := json.NewEncoder(w)
401 encoder.SetIndent("", " ") // Two spaces for each indentation level
402
403 err = encoder.Encode(state)
404 if err != nil {
405 http.Error(w, err.Error(), http.StatusInternalServerError)
406 }
407 })
408
Philip Zeyliger176de792025-04-21 12:25:18 -0700409 s.mux.Handle("/static/", http.StripPrefix("/static/", gzhandler.New(webBundle)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700410
411 // Terminal WebSocket handler
412 // Terminal endpoints - predefined terminals 1-9
413 // TODO: The UI doesn't actually know how to use terminals 2-9!
414 s.mux.HandleFunc("/terminal/events/", func(w http.ResponseWriter, r *http.Request) {
415 if r.Method != http.MethodGet {
416 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
417 return
418 }
419 pathParts := strings.Split(r.URL.Path, "/")
420 if len(pathParts) < 4 {
421 http.Error(w, "Invalid terminal ID", http.StatusBadRequest)
422 return
423 }
424
425 sessionID := pathParts[3]
426 // Validate that the terminal ID is between 1-9
427 if len(sessionID) != 1 || sessionID[0] < '1' || sessionID[0] > '9' {
428 http.Error(w, "Terminal ID must be between 1 and 9", http.StatusBadRequest)
429 return
430 }
431
432 s.handleTerminalEvents(w, r, sessionID)
433 })
434
435 s.mux.HandleFunc("/terminal/input/", func(w http.ResponseWriter, r *http.Request) {
436 if r.Method != http.MethodPost {
437 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
438 return
439 }
440 pathParts := strings.Split(r.URL.Path, "/")
441 if len(pathParts) < 4 {
442 http.Error(w, "Invalid terminal ID", http.StatusBadRequest)
443 return
444 }
445 sessionID := pathParts[3]
446 s.handleTerminalInput(w, r, sessionID)
447 })
448
449 s.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
Sean McCullough86b56862025-04-18 13:04:03 -0700450 // Serve the sketch-app-shell.html file directly from the embedded filesystem
451 data, err := fs.ReadFile(webBundle, "sketch-app-shell.html")
Earl Lee2e463fb2025-04-17 11:22:22 -0700452 if err != nil {
453 http.Error(w, "File not found", http.StatusNotFound)
454 return
455 }
456 w.Header().Set("Content-Type", "text/html")
457 w.Write(data)
458 })
459
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700460 // Handler for POST /restart - restarts the conversation
461 s.mux.HandleFunc("/restart", func(w http.ResponseWriter, r *http.Request) {
462 if r.Method != http.MethodPost {
463 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
464 return
465 }
466
467 // Parse the request body
468 var requestBody struct {
469 Revision string `json:"revision"`
470 InitialPrompt string `json:"initial_prompt"`
471 }
472
473 decoder := json.NewDecoder(r.Body)
474 if err := decoder.Decode(&requestBody); err != nil {
475 http.Error(w, "Invalid request body: "+err.Error(), http.StatusBadRequest)
476 return
477 }
478 defer r.Body.Close()
479
480 // Call the restart method
481 err := agent.RestartConversation(r.Context(), requestBody.Revision, requestBody.InitialPrompt)
482 if err != nil {
483 http.Error(w, "Failed to restart conversation: "+err.Error(), http.StatusInternalServerError)
484 return
485 }
486
487 // Return success response
488 w.Header().Set("Content-Type", "application/json")
489 json.NewEncoder(w).Encode(map[string]string{"status": "restarted"})
490 })
491
492 // Handler for /suggest-reprompt - suggests a reprompt based on conversation history
493 // Handler for /commit-description - returns the description of a git commit
494 s.mux.HandleFunc("/commit-description", func(w http.ResponseWriter, r *http.Request) {
495 if r.Method != http.MethodGet {
496 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
497 return
498 }
499
500 // Get the revision parameter
501 revision := r.URL.Query().Get("revision")
502 if revision == "" {
503 http.Error(w, "Missing revision parameter", http.StatusBadRequest)
504 return
505 }
506
507 // Run git command to get commit description
508 cmd := exec.Command("git", "log", "--oneline", "--decorate", "-n", "1", revision)
509 // Use the working directory from the agent
510 cmd.Dir = s.agent.WorkingDir()
511
512 output, err := cmd.CombinedOutput()
513 if err != nil {
514 http.Error(w, "Failed to get commit description: "+err.Error(), http.StatusInternalServerError)
515 return
516 }
517
518 // Prepare the response
519 resp := map[string]string{
520 "description": strings.TrimSpace(string(output)),
521 }
522
523 w.Header().Set("Content-Type", "application/json")
524 if err := json.NewEncoder(w).Encode(resp); err != nil {
525 slog.ErrorContext(r.Context(), "Error encoding commit description response", slog.Any("err", err))
526 }
527 })
528
529 // Handler for /suggest-reprompt - suggests a reprompt based on conversation history
530 s.mux.HandleFunc("/suggest-reprompt", func(w http.ResponseWriter, r *http.Request) {
531 if r.Method != http.MethodGet {
532 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
533 return
534 }
535
536 // Call the suggest reprompt method
537 suggestedPrompt, err := agent.SuggestReprompt(r.Context())
538 if err != nil {
539 http.Error(w, "Failed to suggest reprompt: "+err.Error(), http.StatusInternalServerError)
540 return
541 }
542
543 // Return success response
544 w.Header().Set("Content-Type", "application/json")
545 json.NewEncoder(w).Encode(map[string]string{"prompt": suggestedPrompt})
546 })
547
Earl Lee2e463fb2025-04-17 11:22:22 -0700548 // Handler for POST /chat
549 s.mux.HandleFunc("/chat", func(w http.ResponseWriter, r *http.Request) {
550 if r.Method != http.MethodPost {
551 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
552 return
553 }
554
555 // Parse the request body
556 var requestBody struct {
557 Message string `json:"message"`
558 }
559
560 decoder := json.NewDecoder(r.Body)
561 if err := decoder.Decode(&requestBody); err != nil {
562 http.Error(w, "Invalid request body: "+err.Error(), http.StatusBadRequest)
563 return
564 }
565 defer r.Body.Close()
566
567 if requestBody.Message == "" {
568 http.Error(w, "Message cannot be empty", http.StatusBadRequest)
569 return
570 }
571
572 agent.UserMessage(r.Context(), requestBody.Message)
573
574 w.WriteHeader(http.StatusOK)
575 })
576
577 // Handler for /cancel - cancels the current inner loop in progress
578 s.mux.HandleFunc("/cancel", func(w http.ResponseWriter, r *http.Request) {
579 if r.Method != http.MethodPost {
580 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
581 return
582 }
583
584 // Parse the request body (optional)
585 var requestBody struct {
586 Reason string `json:"reason"`
587 ToolCallID string `json:"tool_call_id"`
588 }
589
590 decoder := json.NewDecoder(r.Body)
591 if err := decoder.Decode(&requestBody); err != nil && err != io.EOF {
592 http.Error(w, "Invalid request body: "+err.Error(), http.StatusBadRequest)
593 return
594 }
595 defer r.Body.Close()
596
597 cancelReason := "user requested cancellation"
598 if requestBody.Reason != "" {
599 cancelReason = requestBody.Reason
600 }
601
602 if requestBody.ToolCallID != "" {
603 err := agent.CancelToolUse(requestBody.ToolCallID, fmt.Errorf("%s", cancelReason))
604 if err != nil {
605 http.Error(w, err.Error(), http.StatusBadRequest)
606 return
607 }
608 // Return a success response
609 w.Header().Set("Content-Type", "application/json")
610 json.NewEncoder(w).Encode(map[string]string{
611 "status": "cancelled",
612 "too_use_id": requestBody.ToolCallID,
Philip Zeyliger8d50d7b2025-04-23 13:12:40 -0700613 "reason": cancelReason,
614 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700615 return
616 }
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000617 // Call the CancelTurn method
618 agent.CancelTurn(fmt.Errorf("%s", cancelReason))
Earl Lee2e463fb2025-04-17 11:22:22 -0700619 // Return a success response
620 w.Header().Set("Content-Type", "application/json")
621 json.NewEncoder(w).Encode(map[string]string{"status": "cancelled", "reason": cancelReason})
622 })
623
624 debugMux := initDebugMux()
625 s.mux.HandleFunc("/debug/", func(w http.ResponseWriter, r *http.Request) {
626 debugMux.ServeHTTP(w, r)
627 })
628
629 return s, nil
630}
631
632// Utility functions
633func getHostname() string {
634 hostname, err := os.Hostname()
635 if err != nil {
636 return "unknown"
637 }
638 return hostname
639}
640
641func getWorkingDir() string {
642 wd, err := os.Getwd()
643 if err != nil {
644 return "unknown"
645 }
646 return wd
647}
648
649// createTerminalSession creates a new terminal session with the given ID
650func (s *Server) createTerminalSession(sessionID string) (*terminalSession, error) {
651 // Start a new shell process
652 shellPath := getShellPath()
653 cmd := exec.Command(shellPath)
654
655 // Get working directory from the agent if possible
656 workDir := getWorkingDir()
657 cmd.Dir = workDir
658
659 // Set up environment
660 cmd.Env = append(os.Environ(), "TERM=xterm-256color")
661
662 // Start the command with a pty
663 ptmx, err := pty.Start(cmd)
664 if err != nil {
665 slog.Error("Failed to start pty", "error", err)
666 return nil, err
667 }
668
669 // Create the terminal session
670 session := &terminalSession{
671 pty: ptmx,
672 eventsClients: make(map[chan []byte]bool),
673 cmd: cmd,
674 }
675
676 // Start goroutine to read from pty and broadcast to all connected SSE clients
677 go s.readFromPtyAndBroadcast(sessionID, session)
678
679 return session, nil
680} // handleTerminalEvents handles SSE connections for terminal output
681func (s *Server) handleTerminalEvents(w http.ResponseWriter, r *http.Request, sessionID string) {
682 // Check if the session exists, if not, create it
683 s.ptyMutex.Lock()
684 session, exists := s.terminalSessions[sessionID]
685
686 if !exists {
687 // Create a new terminal session
688 var err error
689 session, err = s.createTerminalSession(sessionID)
690 if err != nil {
691 s.ptyMutex.Unlock()
692 http.Error(w, fmt.Sprintf("Failed to create terminal: %v", err), http.StatusInternalServerError)
693 return
694 }
695
696 // Store the new session
697 s.terminalSessions[sessionID] = session
698 }
699 s.ptyMutex.Unlock()
700
701 // Set headers for SSE
702 w.Header().Set("Content-Type", "text/event-stream")
703 w.Header().Set("Cache-Control", "no-cache")
704 w.Header().Set("Connection", "keep-alive")
705 w.Header().Set("Access-Control-Allow-Origin", "*")
706
707 // Create a channel for this client
708 events := make(chan []byte, 4096) // Buffer to prevent blocking
709
710 // Register this client's channel
711 session.eventsClientsMutex.Lock()
712 clientID := session.lastEventClientID + 1
713 session.lastEventClientID = clientID
714 session.eventsClients[events] = true
715 session.eventsClientsMutex.Unlock()
716
717 // When the client disconnects, remove their channel
718 defer func() {
719 session.eventsClientsMutex.Lock()
720 delete(session.eventsClients, events)
721 close(events)
722 session.eventsClientsMutex.Unlock()
723 }()
724
725 // Flush to send headers to client immediately
726 if f, ok := w.(http.Flusher); ok {
727 f.Flush()
728 }
729
730 // Send events to the client as they arrive
731 for {
732 select {
733 case <-r.Context().Done():
734 return
735 case data := <-events:
736 // Format as SSE with base64 encoding
737 fmt.Fprintf(w, "data: %s\n\n", base64.StdEncoding.EncodeToString(data))
738
739 // Flush the data immediately
740 if f, ok := w.(http.Flusher); ok {
741 f.Flush()
742 }
743 }
744 }
745}
746
747// handleTerminalInput processes input to the terminal
748func (s *Server) handleTerminalInput(w http.ResponseWriter, r *http.Request, sessionID string) {
749 // Check if the session exists
750 s.ptyMutex.Lock()
751 session, exists := s.terminalSessions[sessionID]
752 s.ptyMutex.Unlock()
753
754 if !exists {
755 http.Error(w, "Terminal session not found", http.StatusNotFound)
756 return
757 }
758
759 // Read the request body (terminal input or resize command)
760 body, err := io.ReadAll(r.Body)
761 if err != nil {
762 http.Error(w, "Failed to read request body", http.StatusBadRequest)
763 return
764 }
765
766 // Check if it's a resize message
767 if len(body) > 0 && body[0] == '{' {
768 var msg TerminalMessage
769 if err := json.Unmarshal(body, &msg); err == nil && msg.Type == "resize" {
770 if msg.Cols > 0 && msg.Rows > 0 {
771 pty.Setsize(session.pty, &pty.Winsize{
772 Cols: msg.Cols,
773 Rows: msg.Rows,
774 })
775
776 // Respond with success
777 w.WriteHeader(http.StatusOK)
778 return
779 }
780 }
781 }
782
783 // Regular terminal input
784 _, err = session.pty.Write(body)
785 if err != nil {
786 slog.Error("Failed to write to pty", "error", err)
787 http.Error(w, "Failed to write to terminal", http.StatusInternalServerError)
788 return
789 }
790
791 // Respond with success
792 w.WriteHeader(http.StatusOK)
793}
794
795// readFromPtyAndBroadcast reads output from the PTY and broadcasts it to all connected clients
796func (s *Server) readFromPtyAndBroadcast(sessionID string, session *terminalSession) {
797 buf := make([]byte, 4096)
798 defer func() {
799 // Clean up when done
800 s.ptyMutex.Lock()
801 delete(s.terminalSessions, sessionID)
802 s.ptyMutex.Unlock()
803
804 // Close the PTY
805 session.pty.Close()
806
807 // Ensure process is terminated
808 if session.cmd.Process != nil {
809 session.cmd.Process.Signal(syscall.SIGTERM)
810 time.Sleep(100 * time.Millisecond)
811 session.cmd.Process.Kill()
812 }
813
814 // Close all client channels
815 session.eventsClientsMutex.Lock()
816 for ch := range session.eventsClients {
817 delete(session.eventsClients, ch)
818 close(ch)
819 }
820 session.eventsClientsMutex.Unlock()
821 }()
822
823 for {
824 n, err := session.pty.Read(buf)
825 if err != nil {
826 if err != io.EOF {
827 slog.Error("Failed to read from pty", "error", err)
828 }
829 break
830 }
831
832 // Make a copy of the data for each client
833 data := make([]byte, n)
834 copy(data, buf[:n])
835
836 // Broadcast to all connected clients
837 session.eventsClientsMutex.Lock()
838 for ch := range session.eventsClients {
839 // Try to send, but don't block if channel is full
840 select {
841 case ch <- data:
842 default:
843 // Channel is full, drop the message for this client
844 }
845 }
846 session.eventsClientsMutex.Unlock()
847 }
848}
849
850// getShellPath returns the path to the shell to use
851func getShellPath() string {
852 // Try to use the user's preferred shell
853 shell := os.Getenv("SHELL")
854 if shell != "" {
855 return shell
856 }
857
858 // Default to bash on Unix-like systems
859 if _, err := os.Stat("/bin/bash"); err == nil {
860 return "/bin/bash"
861 }
862
863 // Fall back to sh
864 return "/bin/sh"
865}
866
867func initDebugMux() *http.ServeMux {
868 mux := http.NewServeMux()
869 mux.HandleFunc("GET /debug/{$}", func(w http.ResponseWriter, r *http.Request) {
870 w.Header().Set("Content-Type", "text/html; charset=utf-8")
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700871 // TODO: pid is not as useful as "outside pid"
Earl Lee2e463fb2025-04-17 11:22:22 -0700872 fmt.Fprintf(w, `<!doctype html>
873 <html><head><title>sketch debug</title></head><body>
874 <h1>sketch debug</h1>
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700875 pid %d
Earl Lee2e463fb2025-04-17 11:22:22 -0700876 <ul>
877 <li><a href="/debug/pprof/cmdline">pprof/cmdline</a></li>
878 <li><a href="/debug/pprof/profile">pprof/profile</a></li>
879 <li><a href="/debug/pprof/symbol">pprof/symbol</a></li>
880 <li><a href="/debug/pprof/trace">pprof/trace</a></li>
881 <li><a href="/debug/pprof/goroutine?debug=1">pprof/goroutine?debug=1</a></li>
882 <li><a href="/debug/metrics">metrics</a></li>
883 </ul>
884 </body>
885 </html>
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700886 `, os.Getpid())
Earl Lee2e463fb2025-04-17 11:22:22 -0700887 })
888 mux.HandleFunc("GET /debug/pprof/", pprof.Index)
889 mux.HandleFunc("GET /debug/pprof/cmdline", pprof.Cmdline)
890 mux.HandleFunc("GET /debug/pprof/profile", pprof.Profile)
891 mux.HandleFunc("GET /debug/pprof/symbol", pprof.Symbol)
892 mux.HandleFunc("GET /debug/pprof/trace", pprof.Trace)
893 return mux
894}
895
896// isValidGitSHA validates if a string looks like a valid git SHA hash.
897// Git SHAs are hexadecimal strings of at least 4 characters but typically 7, 8, or 40 characters.
898func isValidGitSHA(sha string) bool {
899 // Git SHA must be a hexadecimal string with at least 4 characters
900 if len(sha) < 4 || len(sha) > 40 {
901 return false
902 }
903
904 // Check if the string only contains hexadecimal characters
905 for _, char := range sha {
906 if !(char >= '0' && char <= '9') && !(char >= 'a' && char <= 'f') && !(char >= 'A' && char <= 'F') {
907 return false
908 }
909 }
910
911 return true
912}