blob: ede1644acc9321feb67876a89c66b5ead68c9020 [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"
Philip Zeyligerf84e88c2025-05-14 23:19:01 +00006 "crypto/rand"
Earl Lee2e463fb2025-04-17 11:22:22 -07007 "encoding/base64"
Philip Zeyligerf84e88c2025-05-14 23:19:01 +00008 "encoding/hex"
Earl Lee2e463fb2025-04-17 11:22:22 -07009 "encoding/json"
10 "fmt"
11 "html"
12 "io"
13 "io/fs"
14 "log/slog"
15 "net/http"
16 "net/http/pprof"
17 "os"
18 "os/exec"
Philip Zeyligerf84e88c2025-05-14 23:19:01 +000019 "path/filepath"
Philip Zeyliger8d8b7ac2025-05-21 09:57:23 -070020 "runtime/debug"
Earl Lee2e463fb2025-04-17 11:22:22 -070021 "strconv"
22 "strings"
23 "sync"
24 "syscall"
25 "time"
26
Philip Zeyligerd3ac1122025-05-14 02:54:18 +000027 "sketch.dev/git_tools"
Philip Zeyliger176de792025-04-21 12:25:18 -070028 "sketch.dev/loop/server/gzhandler"
29
Earl Lee2e463fb2025-04-17 11:22:22 -070030 "github.com/creack/pty"
Philip Zeyliger33d282f2025-05-03 04:01:54 +000031 "sketch.dev/claudetool/browse"
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070032 "sketch.dev/llm/conversation"
Earl Lee2e463fb2025-04-17 11:22:22 -070033 "sketch.dev/loop"
Philip Zeyliger2032b1c2025-04-23 19:40:42 -070034 "sketch.dev/webui"
Earl Lee2e463fb2025-04-17 11:22:22 -070035)
36
37// terminalSession represents a terminal session with its PTY and the event channel
38type terminalSession struct {
39 pty *os.File
40 eventsClients map[chan []byte]bool
41 lastEventClientID int
42 eventsClientsMutex sync.Mutex
43 cmd *exec.Cmd
44}
45
46// TerminalMessage represents a message sent from the client for terminal resize events
47type TerminalMessage struct {
48 Type string `json:"type"`
49 Cols uint16 `json:"cols"`
50 Rows uint16 `json:"rows"`
51}
52
53// TerminalResponse represents the response for a new terminal creation
54type TerminalResponse struct {
55 SessionID string `json:"sessionId"`
56}
57
Sean McCulloughd9f13372025-04-21 15:08:49 -070058type State struct {
Philip Zeyligerd03318d2025-05-08 13:09:12 -070059 // null or 1: "old"
60 // 2: supports SSE for message updates
61 StateVersion int `json:"state_version"`
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070062 MessageCount int `json:"message_count"`
63 TotalUsage *conversation.CumulativeUsage `json:"total_usage,omitempty"`
64 InitialCommit string `json:"initial_commit"`
65 Title string `json:"title"`
66 BranchName string `json:"branch_name,omitempty"`
67 Hostname string `json:"hostname"` // deprecated
68 WorkingDir string `json:"working_dir"` // deprecated
69 OS string `json:"os"` // deprecated
70 GitOrigin string `json:"git_origin,omitempty"`
71 OutstandingLLMCalls int `json:"outstanding_llm_calls"`
72 OutstandingToolCalls []string `json:"outstanding_tool_calls"`
73 SessionID string `json:"session_id"`
74 SSHAvailable bool `json:"ssh_available"`
75 SSHError string `json:"ssh_error,omitempty"`
76 InContainer bool `json:"in_container"`
77 FirstMessageIndex int `json:"first_message_index"`
78 AgentState string `json:"agent_state,omitempty"`
79 OutsideHostname string `json:"outside_hostname,omitempty"`
80 InsideHostname string `json:"inside_hostname,omitempty"`
81 OutsideOS string `json:"outside_os,omitempty"`
82 InsideOS string `json:"inside_os,omitempty"`
83 OutsideWorkingDir string `json:"outside_working_dir,omitempty"`
84 InsideWorkingDir string `json:"inside_working_dir,omitempty"`
Sean McCulloughd9f13372025-04-21 15:08:49 -070085}
86
Sean McCulloughbaa2b592025-04-23 10:40:08 -070087type InitRequest struct {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -070088 // Passed to agent so that the URL it prints in the termui prompt is correct (when skaband is not used)
89 HostAddr string `json:"host_addr"`
90
91 // POST /init will start the SSH server with these configs
Sean McCullough7013e9e2025-05-14 02:03:58 +000092 SSHAuthorizedKeys []byte `json:"ssh_authorized_keys"`
93 SSHServerIdentity []byte `json:"ssh_server_identity"`
94 SSHContainerCAKey []byte `json:"ssh_container_ca_key"`
95 SSHHostCertificate []byte `json:"ssh_host_certificate"`
96 SSHAvailable bool `json:"ssh_available"`
97 SSHError string `json:"ssh_error,omitempty"`
Sean McCulloughbaa2b592025-04-23 10:40:08 -070098}
99
Earl Lee2e463fb2025-04-17 11:22:22 -0700100// Server serves sketch HTTP. Server implements http.Handler.
101type Server struct {
102 mux *http.ServeMux
103 agent loop.CodingAgent
104 hostname string
105 logFile *os.File
106 // Mutex to protect terminalSessions
107 ptyMutex sync.Mutex
108 terminalSessions map[string]*terminalSession
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000109 sshAvailable bool
110 sshError string
Earl Lee2e463fb2025-04-17 11:22:22 -0700111}
112
113func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
114 s.mux.ServeHTTP(w, r)
115}
116
117// New creates a new HTTP server.
118func New(agent loop.CodingAgent, logFile *os.File) (*Server, error) {
119 s := &Server{
120 mux: http.NewServeMux(),
121 agent: agent,
122 hostname: getHostname(),
123 logFile: logFile,
124 terminalSessions: make(map[string]*terminalSession),
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000125 sshAvailable: false,
126 sshError: "",
Earl Lee2e463fb2025-04-17 11:22:22 -0700127 }
128
129 webBundle, err := webui.Build()
130 if err != nil {
131 return nil, fmt.Errorf("failed to build web bundle, did you run 'go generate sketch.dev/loop/...'?: %w", err)
132 }
133
Philip Zeyliger25f6ff12025-05-02 04:24:10 +0000134 s.mux.HandleFunc("/stream", s.handleSSEStream)
Philip Zeyligerd3ac1122025-05-14 02:54:18 +0000135
136 // Git tool endpoints
137 s.mux.HandleFunc("/git/rawdiff", s.handleGitRawDiff)
138 s.mux.HandleFunc("/git/show", s.handleGitShow)
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700139 s.mux.HandleFunc("/git/cat", s.handleGitCat)
140 s.mux.HandleFunc("/git/save", s.handleGitSave)
Philip Zeyligerd3ac1122025-05-14 02:54:18 +0000141 s.mux.HandleFunc("/git/recentlog", s.handleGitRecentLog)
142
Earl Lee2e463fb2025-04-17 11:22:22 -0700143 s.mux.HandleFunc("/diff", func(w http.ResponseWriter, r *http.Request) {
144 // Check if a specific commit hash was requested
145 commit := r.URL.Query().Get("commit")
146
147 // Get the diff, optionally for a specific commit
148 var diff string
149 var err error
150 if commit != "" {
151 // Validate the commit hash format
152 if !isValidGitSHA(commit) {
153 http.Error(w, fmt.Sprintf("Invalid git commit SHA format: %s", commit), http.StatusBadRequest)
154 return
155 }
156
157 diff, err = agent.Diff(&commit)
158 } else {
159 diff, err = agent.Diff(nil)
160 }
161
162 if err != nil {
163 http.Error(w, fmt.Sprintf("Error generating diff: %v", err), http.StatusInternalServerError)
164 return
165 }
166
167 w.Header().Set("Content-Type", "text/plain")
168 w.Write([]byte(diff))
169 })
170
171 // Handler for initialization called by host sketch binary when inside docker.
172 s.mux.HandleFunc("/init", func(w http.ResponseWriter, r *http.Request) {
173 defer func() {
174 if err := recover(); err != nil {
175 slog.ErrorContext(r.Context(), "/init panic", slog.Any("recovered_err", err))
176
177 // Return an error response to the client
178 http.Error(w, fmt.Sprintf("panic: %v\n", err), http.StatusInternalServerError)
179 }
180 }()
181
182 if r.Method != "POST" {
183 http.Error(w, "POST required", http.StatusBadRequest)
184 return
185 }
186
187 body, err := io.ReadAll(r.Body)
188 r.Body.Close()
189 if err != nil {
190 http.Error(w, "failed to read request body: "+err.Error(), http.StatusBadRequest)
191 return
192 }
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700193
194 m := &InitRequest{}
195 if err := json.Unmarshal(body, m); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700196 http.Error(w, "bad request body: "+err.Error(), http.StatusBadRequest)
197 return
198 }
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700199
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000200 // Store SSH availability info
201 s.sshAvailable = m.SSHAvailable
202 s.sshError = m.SSHError
203
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700204 // Start the SSH server if the init request included ssh keys.
205 if len(m.SSHAuthorizedKeys) > 0 && len(m.SSHServerIdentity) > 0 {
206 go func() {
207 ctx := context.Background()
Sean McCullough7013e9e2025-05-14 02:03:58 +0000208 if err := s.ServeSSH(ctx, m.SSHServerIdentity, m.SSHAuthorizedKeys, m.SSHContainerCAKey, m.SSHHostCertificate); err != nil {
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700209 slog.ErrorContext(r.Context(), "/init ServeSSH", slog.String("err", err.Error()))
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000210 // Update SSH error if server fails to start
211 s.sshAvailable = false
212 s.sshError = err.Error()
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700213 }
214 }()
215 }
216
Earl Lee2e463fb2025-04-17 11:22:22 -0700217 ini := loop.AgentInit{
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700218 InDocker: true,
219 HostAddr: m.HostAddr,
Earl Lee2e463fb2025-04-17 11:22:22 -0700220 }
221 if err := agent.Init(ini); err != nil {
222 http.Error(w, "init failed: "+err.Error(), http.StatusInternalServerError)
223 return
224 }
225 w.Header().Set("Content-Type", "application/json")
226 io.WriteString(w, "{}\n")
227 })
228
229 // Handler for /messages?start=N&end=M (start/end are optional)
230 s.mux.HandleFunc("/messages", func(w http.ResponseWriter, r *http.Request) {
231 w.Header().Set("Content-Type", "application/json")
232
233 // Extract query parameters for range
234 var start, end int
235 var err error
236
237 currentCount := agent.MessageCount()
238
239 startParam := r.URL.Query().Get("start")
240 if startParam != "" {
241 start, err = strconv.Atoi(startParam)
242 if err != nil {
243 http.Error(w, "Invalid 'start' parameter", http.StatusBadRequest)
244 return
245 }
246 }
247
248 endParam := r.URL.Query().Get("end")
249 if endParam != "" {
250 end, err = strconv.Atoi(endParam)
251 if err != nil {
252 http.Error(w, "Invalid 'end' parameter", http.StatusBadRequest)
253 return
254 }
255 } else {
256 end = currentCount
257 }
258
259 if start < 0 || start > end || end > currentCount {
260 http.Error(w, fmt.Sprintf("Invalid range: start %d end %d currentCount %d", start, end, currentCount), http.StatusBadRequest)
261 return
262 }
263
264 start = max(0, start)
265 end = min(agent.MessageCount(), end)
266 messages := agent.Messages(start, end)
267
268 // Create a JSON encoder with indentation for pretty-printing
269 encoder := json.NewEncoder(w)
270 encoder.SetIndent("", " ") // Two spaces for each indentation level
271
272 err = encoder.Encode(messages)
273 if err != nil {
274 http.Error(w, err.Error(), http.StatusInternalServerError)
275 }
276 })
277
278 // Handler for /logs - displays the contents of the log file
279 s.mux.HandleFunc("/logs", func(w http.ResponseWriter, r *http.Request) {
280 if s.logFile == nil {
281 http.Error(w, "log file not set", http.StatusNotFound)
282 return
283 }
284 logContents, err := os.ReadFile(s.logFile.Name())
285 if err != nil {
286 http.Error(w, "error reading log file: "+err.Error(), http.StatusInternalServerError)
287 return
288 }
289 w.Header().Set("Content-Type", "text/html; charset=utf-8")
290 fmt.Fprintf(w, "<!DOCTYPE html>\n<html>\n<head>\n<title>Sketchy Log File</title>\n</head>\n<body>\n")
291 fmt.Fprintf(w, "<pre>%s</pre>\n", html.EscapeString(string(logContents)))
292 fmt.Fprintf(w, "</body>\n</html>")
293 })
294
295 // Handler for /download - downloads both messages and status as a JSON file
296 s.mux.HandleFunc("/download", func(w http.ResponseWriter, r *http.Request) {
297 // Set headers for file download
298 w.Header().Set("Content-Type", "application/octet-stream")
299
300 // Generate filename with format: sketch-YYYYMMDD-HHMMSS.json
301 timestamp := time.Now().Format("20060102-150405")
302 filename := fmt.Sprintf("sketch-%s.json", timestamp)
303
304 w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
305
306 // Get all messages
307 messageCount := agent.MessageCount()
308 messages := agent.Messages(0, messageCount)
309
310 // Get status information (usage and other metadata)
311 totalUsage := agent.TotalUsage()
312 hostname := getHostname()
313 workingDir := getWorkingDir()
314
315 // Create a combined structure with all information
316 downloadData := struct {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700317 Messages []loop.AgentMessage `json:"messages"`
318 MessageCount int `json:"message_count"`
319 TotalUsage conversation.CumulativeUsage `json:"total_usage"`
320 Hostname string `json:"hostname"`
321 WorkingDir string `json:"working_dir"`
322 DownloadTime string `json:"download_time"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700323 }{
324 Messages: messages,
325 MessageCount: messageCount,
326 TotalUsage: totalUsage,
327 Hostname: hostname,
328 WorkingDir: workingDir,
329 DownloadTime: time.Now().Format(time.RFC3339),
330 }
331
332 // Marshal the JSON with indentation for better readability
333 jsonData, err := json.MarshalIndent(downloadData, "", " ")
334 if err != nil {
335 http.Error(w, err.Error(), http.StatusInternalServerError)
336 return
337 }
338 w.Write(jsonData)
339 })
340
341 // The latter doesn't return until the number of messages has changed (from seen
342 // or from when this was called.)
343 s.mux.HandleFunc("/state", func(w http.ResponseWriter, r *http.Request) {
344 pollParam := r.URL.Query().Get("poll")
345 seenParam := r.URL.Query().Get("seen")
346
347 // Get the client's current message count (if provided)
348 clientMessageCount := -1
349 var err error
350 if seenParam != "" {
351 clientMessageCount, err = strconv.Atoi(seenParam)
352 if err != nil {
353 http.Error(w, "Invalid 'seen' parameter", http.StatusBadRequest)
354 return
355 }
356 }
357
358 serverMessageCount := agent.MessageCount()
359
360 // Let lazy clients not have to specify this.
361 if clientMessageCount == -1 {
362 clientMessageCount = serverMessageCount
363 }
364
365 if pollParam == "true" {
366 ch := make(chan string)
367 go func() {
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700368 it := agent.NewIterator(r.Context(), clientMessageCount)
369 it.Next()
Earl Lee2e463fb2025-04-17 11:22:22 -0700370 close(ch)
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700371 it.Close()
Earl Lee2e463fb2025-04-17 11:22:22 -0700372 }()
373 select {
374 case <-r.Context().Done():
375 slog.DebugContext(r.Context(), "abandoned poll request")
376 return
377 case <-time.After(90 * time.Second):
378 // Let the user call /state again to get the latest to limit how long our long polls hang out.
379 slog.DebugContext(r.Context(), "longish poll request")
380 break
381 case <-ch:
382 break
383 }
384 }
385
Earl Lee2e463fb2025-04-17 11:22:22 -0700386 w.Header().Set("Content-Type", "application/json")
387
Philip Zeyliger25f6ff12025-05-02 04:24:10 +0000388 // Use the shared getState function
389 state := s.getState()
Earl Lee2e463fb2025-04-17 11:22:22 -0700390
391 // Create a JSON encoder with indentation for pretty-printing
392 encoder := json.NewEncoder(w)
393 encoder.SetIndent("", " ") // Two spaces for each indentation level
394
395 err = encoder.Encode(state)
396 if err != nil {
397 http.Error(w, err.Error(), http.StatusInternalServerError)
398 }
399 })
400
Philip Zeyliger176de792025-04-21 12:25:18 -0700401 s.mux.Handle("/static/", http.StripPrefix("/static/", gzhandler.New(webBundle)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700402
403 // Terminal WebSocket handler
404 // Terminal endpoints - predefined terminals 1-9
405 // TODO: The UI doesn't actually know how to use terminals 2-9!
406 s.mux.HandleFunc("/terminal/events/", func(w http.ResponseWriter, r *http.Request) {
407 if r.Method != http.MethodGet {
408 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
409 return
410 }
411 pathParts := strings.Split(r.URL.Path, "/")
412 if len(pathParts) < 4 {
413 http.Error(w, "Invalid terminal ID", http.StatusBadRequest)
414 return
415 }
416
417 sessionID := pathParts[3]
418 // Validate that the terminal ID is between 1-9
419 if len(sessionID) != 1 || sessionID[0] < '1' || sessionID[0] > '9' {
420 http.Error(w, "Terminal ID must be between 1 and 9", http.StatusBadRequest)
421 return
422 }
423
424 s.handleTerminalEvents(w, r, sessionID)
425 })
426
427 s.mux.HandleFunc("/terminal/input/", func(w http.ResponseWriter, r *http.Request) {
428 if r.Method != http.MethodPost {
429 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
430 return
431 }
432 pathParts := strings.Split(r.URL.Path, "/")
433 if len(pathParts) < 4 {
434 http.Error(w, "Invalid terminal ID", http.StatusBadRequest)
435 return
436 }
437 sessionID := pathParts[3]
438 s.handleTerminalInput(w, r, sessionID)
439 })
440
441 s.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
Sean McCullough86b56862025-04-18 13:04:03 -0700442 // Serve the sketch-app-shell.html file directly from the embedded filesystem
443 data, err := fs.ReadFile(webBundle, "sketch-app-shell.html")
Earl Lee2e463fb2025-04-17 11:22:22 -0700444 if err != nil {
445 http.Error(w, "File not found", http.StatusNotFound)
446 return
447 }
448 w.Header().Set("Content-Type", "text/html")
449 w.Write(data)
450 })
451
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700452 // Handler for /commit-description - returns the description of a git commit
453 s.mux.HandleFunc("/commit-description", func(w http.ResponseWriter, r *http.Request) {
454 if r.Method != http.MethodGet {
455 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
456 return
457 }
458
459 // Get the revision parameter
460 revision := r.URL.Query().Get("revision")
461 if revision == "" {
462 http.Error(w, "Missing revision parameter", http.StatusBadRequest)
463 return
464 }
465
466 // Run git command to get commit description
467 cmd := exec.Command("git", "log", "--oneline", "--decorate", "-n", "1", revision)
468 // Use the working directory from the agent
469 cmd.Dir = s.agent.WorkingDir()
470
471 output, err := cmd.CombinedOutput()
472 if err != nil {
473 http.Error(w, "Failed to get commit description: "+err.Error(), http.StatusInternalServerError)
474 return
475 }
476
477 // Prepare the response
478 resp := map[string]string{
479 "description": strings.TrimSpace(string(output)),
480 }
481
482 w.Header().Set("Content-Type", "application/json")
483 if err := json.NewEncoder(w).Encode(resp); err != nil {
484 slog.ErrorContext(r.Context(), "Error encoding commit description response", slog.Any("err", err))
485 }
486 })
487
Philip Zeyliger33d282f2025-05-03 04:01:54 +0000488 // Handler for /screenshot/{id} - serves screenshot images
489 s.mux.HandleFunc("/screenshot/", func(w http.ResponseWriter, r *http.Request) {
490 if r.Method != http.MethodGet {
491 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
492 return
493 }
494
495 // Extract the screenshot ID from the path
496 pathParts := strings.Split(r.URL.Path, "/")
497 if len(pathParts) < 3 {
498 http.Error(w, "Invalid screenshot ID", http.StatusBadRequest)
499 return
500 }
501
502 screenshotID := pathParts[2]
503
504 // Validate the ID format (prevent directory traversal)
505 if strings.Contains(screenshotID, "/") || strings.Contains(screenshotID, "\\") {
506 http.Error(w, "Invalid screenshot ID format", http.StatusBadRequest)
507 return
508 }
509
510 // Get the screenshot file path
511 filePath := browse.GetScreenshotPath(screenshotID)
512
513 // Check if the file exists
514 if _, err := os.Stat(filePath); os.IsNotExist(err) {
515 http.Error(w, "Screenshot not found", http.StatusNotFound)
516 return
517 }
518
519 // Serve the file
520 w.Header().Set("Content-Type", "image/png")
521 w.Header().Set("Cache-Control", "max-age=3600") // Cache for an hour
522 http.ServeFile(w, r, filePath)
523 })
524
Earl Lee2e463fb2025-04-17 11:22:22 -0700525 // Handler for POST /chat
526 s.mux.HandleFunc("/chat", func(w http.ResponseWriter, r *http.Request) {
527 if r.Method != http.MethodPost {
528 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
529 return
530 }
531
532 // Parse the request body
533 var requestBody struct {
534 Message string `json:"message"`
535 }
536
537 decoder := json.NewDecoder(r.Body)
538 if err := decoder.Decode(&requestBody); err != nil {
539 http.Error(w, "Invalid request body: "+err.Error(), http.StatusBadRequest)
540 return
541 }
542 defer r.Body.Close()
543
544 if requestBody.Message == "" {
545 http.Error(w, "Message cannot be empty", http.StatusBadRequest)
546 return
547 }
548
549 agent.UserMessage(r.Context(), requestBody.Message)
550
551 w.WriteHeader(http.StatusOK)
552 })
553
Philip Zeyligerf84e88c2025-05-14 23:19:01 +0000554 // Handler for POST /upload - uploads a file to /tmp
555 s.mux.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
556 if r.Method != http.MethodPost {
557 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
558 return
559 }
560
561 // Limit to 10MB file size
562 r.Body = http.MaxBytesReader(w, r.Body, 10*1024*1024)
563
564 // Parse the multipart form
565 if err := r.ParseMultipartForm(10 * 1024 * 1024); err != nil {
566 http.Error(w, "Failed to parse form: "+err.Error(), http.StatusBadRequest)
567 return
568 }
569
570 // Get the file from the multipart form
571 file, handler, err := r.FormFile("file")
572 if err != nil {
573 http.Error(w, "Failed to get uploaded file: "+err.Error(), http.StatusBadRequest)
574 return
575 }
576 defer file.Close()
577
578 // Generate a unique ID (8 random bytes converted to 16 hex chars)
579 randBytes := make([]byte, 8)
580 if _, err := rand.Read(randBytes); err != nil {
581 http.Error(w, "Failed to generate random filename: "+err.Error(), http.StatusInternalServerError)
582 return
583 }
584
585 // Get file extension from the original filename
586 ext := filepath.Ext(handler.Filename)
587
588 // Create a unique filename in the /tmp directory
589 filename := fmt.Sprintf("/tmp/sketch_file_%s%s", hex.EncodeToString(randBytes), ext)
590
591 // Create the destination file
592 destFile, err := os.Create(filename)
593 if err != nil {
594 http.Error(w, "Failed to create destination file: "+err.Error(), http.StatusInternalServerError)
595 return
596 }
597 defer destFile.Close()
598
599 // Copy the file contents to the destination file
600 if _, err := io.Copy(destFile, file); err != nil {
601 http.Error(w, "Failed to save file: "+err.Error(), http.StatusInternalServerError)
602 return
603 }
604
605 // Return the path to the saved file
606 w.Header().Set("Content-Type", "application/json")
607 json.NewEncoder(w).Encode(map[string]string{"path": filename})
608 })
609
Earl Lee2e463fb2025-04-17 11:22:22 -0700610 // Handler for /cancel - cancels the current inner loop in progress
611 s.mux.HandleFunc("/cancel", func(w http.ResponseWriter, r *http.Request) {
612 if r.Method != http.MethodPost {
613 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
614 return
615 }
616
617 // Parse the request body (optional)
618 var requestBody struct {
619 Reason string `json:"reason"`
620 ToolCallID string `json:"tool_call_id"`
621 }
622
623 decoder := json.NewDecoder(r.Body)
624 if err := decoder.Decode(&requestBody); err != nil && err != io.EOF {
625 http.Error(w, "Invalid request body: "+err.Error(), http.StatusBadRequest)
626 return
627 }
628 defer r.Body.Close()
629
630 cancelReason := "user requested cancellation"
631 if requestBody.Reason != "" {
632 cancelReason = requestBody.Reason
633 }
634
635 if requestBody.ToolCallID != "" {
636 err := agent.CancelToolUse(requestBody.ToolCallID, fmt.Errorf("%s", cancelReason))
637 if err != nil {
638 http.Error(w, err.Error(), http.StatusBadRequest)
639 return
640 }
641 // Return a success response
642 w.Header().Set("Content-Type", "application/json")
643 json.NewEncoder(w).Encode(map[string]string{
644 "status": "cancelled",
645 "too_use_id": requestBody.ToolCallID,
Philip Zeyliger8d50d7b2025-04-23 13:12:40 -0700646 "reason": cancelReason,
647 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700648 return
649 }
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000650 // Call the CancelTurn method
651 agent.CancelTurn(fmt.Errorf("%s", cancelReason))
Earl Lee2e463fb2025-04-17 11:22:22 -0700652 // Return a success response
653 w.Header().Set("Content-Type", "application/json")
654 json.NewEncoder(w).Encode(map[string]string{"status": "cancelled", "reason": cancelReason})
655 })
656
Pokey Rule397871d2025-05-19 15:02:45 +0100657 // Handler for /end - shuts down the inner sketch process
658 s.mux.HandleFunc("/end", func(w http.ResponseWriter, r *http.Request) {
659 if r.Method != http.MethodPost {
660 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
661 return
662 }
663
664 // Parse the request body (optional)
665 var requestBody struct {
666 Reason string `json:"reason"`
667 }
668
669 decoder := json.NewDecoder(r.Body)
670 if err := decoder.Decode(&requestBody); err != nil && err != io.EOF {
671 http.Error(w, "Invalid request body: "+err.Error(), http.StatusBadRequest)
672 return
673 }
674 defer r.Body.Close()
675
676 endReason := "user requested end of session"
677 if requestBody.Reason != "" {
678 endReason = requestBody.Reason
679 }
680
681 // Send success response before exiting
682 w.Header().Set("Content-Type", "application/json")
683 json.NewEncoder(w).Encode(map[string]string{"status": "ending", "reason": endReason})
684 if f, ok := w.(http.Flusher); ok {
685 f.Flush()
686 }
687
688 // Log that we're shutting down
689 slog.Info("Ending session", "reason", endReason)
690
691 // Exit the process after a short delay to allow response to be sent
692 go func() {
693 time.Sleep(100 * time.Millisecond)
694 os.Exit(0)
695 }()
696 })
697
Earl Lee2e463fb2025-04-17 11:22:22 -0700698 debugMux := initDebugMux()
699 s.mux.HandleFunc("/debug/", func(w http.ResponseWriter, r *http.Request) {
700 debugMux.ServeHTTP(w, r)
701 })
702
703 return s, nil
704}
705
706// Utility functions
707func getHostname() string {
708 hostname, err := os.Hostname()
709 if err != nil {
710 return "unknown"
711 }
712 return hostname
713}
714
715func getWorkingDir() string {
716 wd, err := os.Getwd()
717 if err != nil {
718 return "unknown"
719 }
720 return wd
721}
722
723// createTerminalSession creates a new terminal session with the given ID
724func (s *Server) createTerminalSession(sessionID string) (*terminalSession, error) {
725 // Start a new shell process
726 shellPath := getShellPath()
727 cmd := exec.Command(shellPath)
728
729 // Get working directory from the agent if possible
730 workDir := getWorkingDir()
731 cmd.Dir = workDir
732
733 // Set up environment
734 cmd.Env = append(os.Environ(), "TERM=xterm-256color")
735
736 // Start the command with a pty
737 ptmx, err := pty.Start(cmd)
738 if err != nil {
739 slog.Error("Failed to start pty", "error", err)
740 return nil, err
741 }
742
743 // Create the terminal session
744 session := &terminalSession{
745 pty: ptmx,
746 eventsClients: make(map[chan []byte]bool),
747 cmd: cmd,
748 }
749
750 // Start goroutine to read from pty and broadcast to all connected SSE clients
751 go s.readFromPtyAndBroadcast(sessionID, session)
752
753 return session, nil
754} // handleTerminalEvents handles SSE connections for terminal output
755func (s *Server) handleTerminalEvents(w http.ResponseWriter, r *http.Request, sessionID string) {
756 // Check if the session exists, if not, create it
757 s.ptyMutex.Lock()
758 session, exists := s.terminalSessions[sessionID]
759
760 if !exists {
761 // Create a new terminal session
762 var err error
763 session, err = s.createTerminalSession(sessionID)
764 if err != nil {
765 s.ptyMutex.Unlock()
766 http.Error(w, fmt.Sprintf("Failed to create terminal: %v", err), http.StatusInternalServerError)
767 return
768 }
769
770 // Store the new session
771 s.terminalSessions[sessionID] = session
772 }
773 s.ptyMutex.Unlock()
774
775 // Set headers for SSE
776 w.Header().Set("Content-Type", "text/event-stream")
777 w.Header().Set("Cache-Control", "no-cache")
778 w.Header().Set("Connection", "keep-alive")
779 w.Header().Set("Access-Control-Allow-Origin", "*")
780
781 // Create a channel for this client
782 events := make(chan []byte, 4096) // Buffer to prevent blocking
783
784 // Register this client's channel
785 session.eventsClientsMutex.Lock()
786 clientID := session.lastEventClientID + 1
787 session.lastEventClientID = clientID
788 session.eventsClients[events] = true
789 session.eventsClientsMutex.Unlock()
790
791 // When the client disconnects, remove their channel
792 defer func() {
793 session.eventsClientsMutex.Lock()
794 delete(session.eventsClients, events)
795 close(events)
796 session.eventsClientsMutex.Unlock()
797 }()
798
799 // Flush to send headers to client immediately
800 if f, ok := w.(http.Flusher); ok {
801 f.Flush()
802 }
803
804 // Send events to the client as they arrive
805 for {
806 select {
807 case <-r.Context().Done():
808 return
809 case data := <-events:
810 // Format as SSE with base64 encoding
811 fmt.Fprintf(w, "data: %s\n\n", base64.StdEncoding.EncodeToString(data))
812
813 // Flush the data immediately
814 if f, ok := w.(http.Flusher); ok {
815 f.Flush()
816 }
817 }
818 }
819}
820
821// handleTerminalInput processes input to the terminal
822func (s *Server) handleTerminalInput(w http.ResponseWriter, r *http.Request, sessionID string) {
823 // Check if the session exists
824 s.ptyMutex.Lock()
825 session, exists := s.terminalSessions[sessionID]
826 s.ptyMutex.Unlock()
827
828 if !exists {
829 http.Error(w, "Terminal session not found", http.StatusNotFound)
830 return
831 }
832
833 // Read the request body (terminal input or resize command)
834 body, err := io.ReadAll(r.Body)
835 if err != nil {
836 http.Error(w, "Failed to read request body", http.StatusBadRequest)
837 return
838 }
839
840 // Check if it's a resize message
841 if len(body) > 0 && body[0] == '{' {
842 var msg TerminalMessage
843 if err := json.Unmarshal(body, &msg); err == nil && msg.Type == "resize" {
844 if msg.Cols > 0 && msg.Rows > 0 {
845 pty.Setsize(session.pty, &pty.Winsize{
846 Cols: msg.Cols,
847 Rows: msg.Rows,
848 })
849
850 // Respond with success
851 w.WriteHeader(http.StatusOK)
852 return
853 }
854 }
855 }
856
857 // Regular terminal input
858 _, err = session.pty.Write(body)
859 if err != nil {
860 slog.Error("Failed to write to pty", "error", err)
861 http.Error(w, "Failed to write to terminal", http.StatusInternalServerError)
862 return
863 }
864
865 // Respond with success
866 w.WriteHeader(http.StatusOK)
867}
868
869// readFromPtyAndBroadcast reads output from the PTY and broadcasts it to all connected clients
870func (s *Server) readFromPtyAndBroadcast(sessionID string, session *terminalSession) {
871 buf := make([]byte, 4096)
872 defer func() {
873 // Clean up when done
874 s.ptyMutex.Lock()
875 delete(s.terminalSessions, sessionID)
876 s.ptyMutex.Unlock()
877
878 // Close the PTY
879 session.pty.Close()
880
881 // Ensure process is terminated
882 if session.cmd.Process != nil {
883 session.cmd.Process.Signal(syscall.SIGTERM)
884 time.Sleep(100 * time.Millisecond)
885 session.cmd.Process.Kill()
886 }
887
888 // Close all client channels
889 session.eventsClientsMutex.Lock()
890 for ch := range session.eventsClients {
891 delete(session.eventsClients, ch)
892 close(ch)
893 }
894 session.eventsClientsMutex.Unlock()
895 }()
896
897 for {
898 n, err := session.pty.Read(buf)
899 if err != nil {
900 if err != io.EOF {
901 slog.Error("Failed to read from pty", "error", err)
902 }
903 break
904 }
905
906 // Make a copy of the data for each client
907 data := make([]byte, n)
908 copy(data, buf[:n])
909
910 // Broadcast to all connected clients
911 session.eventsClientsMutex.Lock()
912 for ch := range session.eventsClients {
913 // Try to send, but don't block if channel is full
914 select {
915 case ch <- data:
916 default:
917 // Channel is full, drop the message for this client
918 }
919 }
920 session.eventsClientsMutex.Unlock()
921 }
922}
923
924// getShellPath returns the path to the shell to use
925func getShellPath() string {
926 // Try to use the user's preferred shell
927 shell := os.Getenv("SHELL")
928 if shell != "" {
929 return shell
930 }
931
932 // Default to bash on Unix-like systems
933 if _, err := os.Stat("/bin/bash"); err == nil {
934 return "/bin/bash"
935 }
936
937 // Fall back to sh
938 return "/bin/sh"
939}
940
941func initDebugMux() *http.ServeMux {
942 mux := http.NewServeMux()
Philip Zeyliger8d8b7ac2025-05-21 09:57:23 -0700943 build := "unknown build"
944 bi, ok := debug.ReadBuildInfo()
945 if ok {
946 build = fmt.Sprintf("%s@%v\n", bi.Path, bi.Main.Version)
947 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700948 mux.HandleFunc("GET /debug/{$}", func(w http.ResponseWriter, r *http.Request) {
949 w.Header().Set("Content-Type", "text/html; charset=utf-8")
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700950 // TODO: pid is not as useful as "outside pid"
Earl Lee2e463fb2025-04-17 11:22:22 -0700951 fmt.Fprintf(w, `<!doctype html>
952 <html><head><title>sketch debug</title></head><body>
953 <h1>sketch debug</h1>
Philip Zeyliger8d8b7ac2025-05-21 09:57:23 -0700954 pid %d<br>
955 build %s<br>
Earl Lee2e463fb2025-04-17 11:22:22 -0700956 <ul>
957 <li><a href="/debug/pprof/cmdline">pprof/cmdline</a></li>
958 <li><a href="/debug/pprof/profile">pprof/profile</a></li>
959 <li><a href="/debug/pprof/symbol">pprof/symbol</a></li>
960 <li><a href="/debug/pprof/trace">pprof/trace</a></li>
961 <li><a href="/debug/pprof/goroutine?debug=1">pprof/goroutine?debug=1</a></li>
962 <li><a href="/debug/metrics">metrics</a></li>
963 </ul>
964 </body>
965 </html>
Philip Zeyliger8d8b7ac2025-05-21 09:57:23 -0700966 `, os.Getpid(), build)
Earl Lee2e463fb2025-04-17 11:22:22 -0700967 })
968 mux.HandleFunc("GET /debug/pprof/", pprof.Index)
969 mux.HandleFunc("GET /debug/pprof/cmdline", pprof.Cmdline)
970 mux.HandleFunc("GET /debug/pprof/profile", pprof.Profile)
971 mux.HandleFunc("GET /debug/pprof/symbol", pprof.Symbol)
972 mux.HandleFunc("GET /debug/pprof/trace", pprof.Trace)
973 return mux
974}
975
976// isValidGitSHA validates if a string looks like a valid git SHA hash.
977// Git SHAs are hexadecimal strings of at least 4 characters but typically 7, 8, or 40 characters.
978func isValidGitSHA(sha string) bool {
979 // Git SHA must be a hexadecimal string with at least 4 characters
980 if len(sha) < 4 || len(sha) > 40 {
981 return false
982 }
983
984 // Check if the string only contains hexadecimal characters
985 for _, char := range sha {
986 if !(char >= '0' && char <= '9') && !(char >= 'a' && char <= 'f') && !(char >= 'A' && char <= 'F') {
987 return false
988 }
989 }
990
991 return true
992}
Philip Zeyliger25f6ff12025-05-02 04:24:10 +0000993
994// /stream?from=N endpoint for Server-Sent Events
995func (s *Server) handleSSEStream(w http.ResponseWriter, r *http.Request) {
996 w.Header().Set("Content-Type", "text/event-stream")
997 w.Header().Set("Cache-Control", "no-cache")
998 w.Header().Set("Connection", "keep-alive")
999 w.Header().Set("Access-Control-Allow-Origin", "*")
1000
1001 // Extract the 'from' parameter
1002 fromParam := r.URL.Query().Get("from")
1003 var fromIndex int
1004 var err error
1005 if fromParam != "" {
1006 fromIndex, err = strconv.Atoi(fromParam)
1007 if err != nil {
1008 http.Error(w, "Invalid 'from' parameter", http.StatusBadRequest)
1009 return
1010 }
1011 }
1012
1013 // Ensure 'from' is valid
1014 currentCount := s.agent.MessageCount()
1015 if fromIndex < 0 {
1016 fromIndex = 0
1017 } else if fromIndex > currentCount {
1018 fromIndex = currentCount
1019 }
1020
1021 // Send the current state immediately
1022 state := s.getState()
1023
1024 // Create JSON encoder
1025 encoder := json.NewEncoder(w)
1026
1027 // Send state as an event
1028 fmt.Fprintf(w, "event: state\n")
1029 fmt.Fprintf(w, "data: ")
1030 encoder.Encode(state)
1031 fmt.Fprintf(w, "\n\n")
1032
1033 if f, ok := w.(http.Flusher); ok {
1034 f.Flush()
1035 }
1036
1037 // Create a context for the SSE stream
1038 ctx := r.Context()
1039
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001040 // Setup heartbeat timer
1041 heartbeatTicker := time.NewTicker(45 * time.Second)
1042 defer heartbeatTicker.Stop()
1043
1044 // Create a channel for messages
1045 messageChan := make(chan *loop.AgentMessage, 10)
1046
Philip Zeyligereab12de2025-05-14 02:35:53 +00001047 // Create a channel for state transitions
1048 stateChan := make(chan *loop.StateTransition, 10)
1049
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001050 // Start a goroutine to read messages without blocking the heartbeat
1051 go func() {
Pokey Rule9d7f0cc2025-05-20 11:43:26 +01001052 // Create an iterator to receive new messages as they arrive
1053 iterator := s.agent.NewIterator(ctx, fromIndex) // Start from the requested index
1054 defer iterator.Close()
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001055 defer close(messageChan)
1056 for {
1057 // This can block, but it's in its own goroutine
1058 newMessage := iterator.Next()
1059 if newMessage == nil {
1060 // No message available (likely due to context cancellation)
1061 slog.InfoContext(ctx, "No more messages available, ending message stream")
1062 return
1063 }
1064
1065 select {
1066 case messageChan <- newMessage:
1067 // Message sent to channel
1068 case <-ctx.Done():
1069 // Context cancelled
1070 return
1071 }
1072 }
1073 }()
1074
Philip Zeyligereab12de2025-05-14 02:35:53 +00001075 // Start a goroutine to read state transitions
1076 go func() {
Pokey Rule9d7f0cc2025-05-20 11:43:26 +01001077 // Create an iterator to receive state transitions
1078 stateIterator := s.agent.NewStateTransitionIterator(ctx)
1079 defer stateIterator.Close()
Philip Zeyligereab12de2025-05-14 02:35:53 +00001080 defer close(stateChan)
1081 for {
1082 // This can block, but it's in its own goroutine
1083 newTransition := stateIterator.Next()
1084 if newTransition == nil {
1085 // No transition available (likely due to context cancellation)
1086 slog.InfoContext(ctx, "No more state transitions available, ending state stream")
1087 return
1088 }
1089
1090 select {
1091 case stateChan <- newTransition:
1092 // Transition sent to channel
1093 case <-ctx.Done():
1094 // Context cancelled
1095 return
1096 }
1097 }
1098 }()
1099
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001100 // Stay connected and stream real-time updates
1101 for {
1102 select {
1103 case <-heartbeatTicker.C:
1104 // Send heartbeat event
1105 fmt.Fprintf(w, "event: heartbeat\n")
1106 fmt.Fprintf(w, "data: %d\n\n", time.Now().Unix())
1107
1108 // Flush to send the heartbeat immediately
1109 if f, ok := w.(http.Flusher); ok {
1110 f.Flush()
1111 }
1112
1113 case <-ctx.Done():
1114 // Client disconnected
1115 slog.InfoContext(ctx, "Client disconnected from SSE stream")
1116 return
1117
Philip Zeyligereab12de2025-05-14 02:35:53 +00001118 case _, ok := <-stateChan:
1119 if !ok {
1120 // Channel closed
1121 slog.InfoContext(ctx, "State transition channel closed, ending SSE stream")
1122 return
1123 }
1124
1125 // Get updated state
1126 state = s.getState()
1127
1128 // Send updated state after the state transition
1129 fmt.Fprintf(w, "event: state\n")
1130 fmt.Fprintf(w, "data: ")
1131 encoder.Encode(state)
1132 fmt.Fprintf(w, "\n\n")
1133
1134 // Flush to send the state immediately
1135 if f, ok := w.(http.Flusher); ok {
1136 f.Flush()
1137 }
1138
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001139 case newMessage, ok := <-messageChan:
1140 if !ok {
1141 // Channel closed
1142 slog.InfoContext(ctx, "Message channel closed, ending SSE stream")
1143 return
1144 }
1145
1146 // Send the new message as an event
1147 fmt.Fprintf(w, "event: message\n")
1148 fmt.Fprintf(w, "data: ")
1149 encoder.Encode(newMessage)
1150 fmt.Fprintf(w, "\n\n")
1151
1152 // Get updated state
1153 state = s.getState()
1154
1155 // Send updated state after the message
1156 fmt.Fprintf(w, "event: state\n")
1157 fmt.Fprintf(w, "data: ")
1158 encoder.Encode(state)
1159 fmt.Fprintf(w, "\n\n")
1160
1161 // Flush to send the message and state immediately
1162 if f, ok := w.(http.Flusher); ok {
1163 f.Flush()
1164 }
1165 }
1166 }
1167}
1168
1169// Helper function to get the current state
1170func (s *Server) getState() State {
1171 serverMessageCount := s.agent.MessageCount()
1172 totalUsage := s.agent.TotalUsage()
1173
1174 return State{
Philip Zeyliger49edc922025-05-14 09:45:45 -07001175 StateVersion: 2,
1176 MessageCount: serverMessageCount,
1177 TotalUsage: &totalUsage,
1178 Hostname: s.hostname,
1179 WorkingDir: getWorkingDir(),
1180 // TODO: Rename this field to sketch-base?
1181 InitialCommit: s.agent.SketchGitBase(),
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001182 Title: s.agent.Title(),
1183 BranchName: s.agent.BranchName(),
1184 OS: s.agent.OS(),
1185 OutsideHostname: s.agent.OutsideHostname(),
1186 InsideHostname: s.hostname,
1187 OutsideOS: s.agent.OutsideOS(),
1188 InsideOS: s.agent.OS(),
1189 OutsideWorkingDir: s.agent.OutsideWorkingDir(),
1190 InsideWorkingDir: getWorkingDir(),
1191 GitOrigin: s.agent.GitOrigin(),
1192 OutstandingLLMCalls: s.agent.OutstandingLLMCallCount(),
1193 OutstandingToolCalls: s.agent.OutstandingToolCalls(),
1194 SessionID: s.agent.SessionID(),
1195 SSHAvailable: s.sshAvailable,
1196 SSHError: s.sshError,
1197 InContainer: s.agent.IsInContainer(),
1198 FirstMessageIndex: s.agent.FirstMessageIndex(),
1199 AgentState: s.agent.CurrentStateName(),
1200 }
1201}
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001202
1203func (s *Server) handleGitRawDiff(w http.ResponseWriter, r *http.Request) {
1204 if r.Method != "GET" {
1205 w.WriteHeader(http.StatusMethodNotAllowed)
1206 return
1207 }
1208
1209 // Get the git working directory from agent
1210 repoDir := s.agent.WorkingDir()
1211
1212 // Parse query parameters
1213 query := r.URL.Query()
1214 commit := query.Get("commit")
1215 from := query.Get("from")
1216 to := query.Get("to")
1217
1218 // If commit is specified, use commit^ and commit as from and to
1219 if commit != "" {
1220 from = commit + "^"
1221 to = commit
1222 }
1223
1224 // Check if we have enough parameters
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001225 if from == "" {
1226 http.Error(w, "Missing required parameter: either 'commit' or at least 'from'", http.StatusBadRequest)
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001227 return
1228 }
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001229 // Note: 'to' can be empty to indicate working directory (unstaged changes)
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001230
1231 // Call the git_tools function
1232 diff, err := git_tools.GitRawDiff(repoDir, from, to)
1233 if err != nil {
1234 http.Error(w, fmt.Sprintf("Error getting git diff: %v", err), http.StatusInternalServerError)
1235 return
1236 }
1237
1238 // Return the result as JSON
1239 w.Header().Set("Content-Type", "application/json")
1240 if err := json.NewEncoder(w).Encode(diff); err != nil {
1241 http.Error(w, fmt.Sprintf("Error encoding response: %v", err), http.StatusInternalServerError)
1242 return
1243 }
1244}
1245
1246func (s *Server) handleGitShow(w http.ResponseWriter, r *http.Request) {
1247 if r.Method != "GET" {
1248 w.WriteHeader(http.StatusMethodNotAllowed)
1249 return
1250 }
1251
1252 // Get the git working directory from agent
1253 repoDir := s.agent.WorkingDir()
1254
1255 // Parse query parameters
1256 hash := r.URL.Query().Get("hash")
1257 if hash == "" {
1258 http.Error(w, "Missing required parameter: 'hash'", http.StatusBadRequest)
1259 return
1260 }
1261
1262 // Call the git_tools function
1263 show, err := git_tools.GitShow(repoDir, hash)
1264 if err != nil {
1265 http.Error(w, fmt.Sprintf("Error running git show: %v", err), http.StatusInternalServerError)
1266 return
1267 }
1268
1269 // Create a JSON response
1270 response := map[string]string{
1271 "hash": hash,
1272 "output": show,
1273 }
1274
1275 // Return the result as JSON
1276 w.Header().Set("Content-Type", "application/json")
1277 if err := json.NewEncoder(w).Encode(response); err != nil {
1278 http.Error(w, fmt.Sprintf("Error encoding response: %v", err), http.StatusInternalServerError)
1279 return
1280 }
1281}
1282
1283func (s *Server) handleGitRecentLog(w http.ResponseWriter, r *http.Request) {
1284 if r.Method != "GET" {
1285 w.WriteHeader(http.StatusMethodNotAllowed)
1286 return
1287 }
1288
1289 // Get the git working directory and initial commit from agent
1290 repoDir := s.agent.WorkingDir()
1291 initialCommit := s.agent.SketchGitBaseRef()
1292
1293 // Call the git_tools function
1294 log, err := git_tools.GitRecentLog(repoDir, initialCommit)
1295 if err != nil {
1296 http.Error(w, fmt.Sprintf("Error getting git log: %v", err), http.StatusInternalServerError)
1297 return
1298 }
1299
1300 // Return the result as JSON
1301 w.Header().Set("Content-Type", "application/json")
1302 if err := json.NewEncoder(w).Encode(log); err != nil {
1303 http.Error(w, fmt.Sprintf("Error encoding response: %v", err), http.StatusInternalServerError)
1304 return
1305 }
1306}
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001307
1308func (s *Server) handleGitCat(w http.ResponseWriter, r *http.Request) {
1309 if r.Method != "GET" {
1310 w.WriteHeader(http.StatusMethodNotAllowed)
1311 return
1312 }
1313
1314 // Get the git working directory from agent
1315 repoDir := s.agent.WorkingDir()
1316
1317 // Parse query parameters
1318 query := r.URL.Query()
1319 path := query.Get("path")
1320
1321 // Check if path is provided
1322 if path == "" {
1323 http.Error(w, "Missing required parameter: path", http.StatusBadRequest)
1324 return
1325 }
1326
1327 // Get file content using GitCat
1328 content, err := git_tools.GitCat(repoDir, path)
1329 if err != nil {
1330 http.Error(w, fmt.Sprintf("Error reading file: %v", err), http.StatusInternalServerError)
1331 return
1332 }
1333
1334 // Return the content as JSON for consistency with other endpoints
1335 w.Header().Set("Content-Type", "application/json")
1336 if err := json.NewEncoder(w).Encode(map[string]string{"output": content}); err != nil {
1337 http.Error(w, fmt.Sprintf("Error encoding response: %v", err), http.StatusInternalServerError)
1338 return
1339 }
1340}
1341
1342func (s *Server) handleGitSave(w http.ResponseWriter, r *http.Request) {
1343 if r.Method != "POST" {
1344 w.WriteHeader(http.StatusMethodNotAllowed)
1345 return
1346 }
1347
1348 // Get the git working directory from agent
1349 repoDir := s.agent.WorkingDir()
1350
1351 // Parse request body
1352 var requestBody struct {
1353 Path string `json:"path"`
1354 Content string `json:"content"`
1355 }
1356
1357 if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {
1358 http.Error(w, fmt.Sprintf("Error parsing request body: %v", err), http.StatusBadRequest)
1359 return
1360 }
1361 defer r.Body.Close()
1362
1363 // Check if path is provided
1364 if requestBody.Path == "" {
1365 http.Error(w, "Missing required parameter: path", http.StatusBadRequest)
1366 return
1367 }
1368
1369 // Save file content using GitSaveFile
1370 err := git_tools.GitSaveFile(repoDir, requestBody.Path, requestBody.Content)
1371 if err != nil {
1372 http.Error(w, fmt.Sprintf("Error saving file: %v", err), http.StatusInternalServerError)
1373 return
1374 }
1375
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001376 // Auto-commit the changes
1377 err = git_tools.AutoCommitDiffViewChanges(r.Context(), repoDir, requestBody.Path)
1378 if err != nil {
1379 http.Error(w, fmt.Sprintf("Error auto-committing changes: %v", err), http.StatusInternalServerError)
1380 return
1381 }
1382
1383 // Detect git changes to push and notify user
Philip Zeyliger9bca61e2025-05-22 12:40:06 -07001384 if err = s.agent.DetectGitChanges(r.Context()); err != nil {
1385 http.Error(w, fmt.Sprintf("Error detecting git changes: %v", err), http.StatusInternalServerError)
1386 return
1387 }
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001388
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001389 // Return simple success response
1390 w.WriteHeader(http.StatusOK)
1391 w.Write([]byte("ok"))
1392}