blob: 784d20b938ce405bfc7c147d9550234d4c0c9aab [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
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -070058// TodoItem represents a single todo item for task management
59type TodoItem struct {
60 ID string `json:"id"`
61 Task string `json:"task"`
62 Status string `json:"status"` // queued, in-progress, completed
63}
64
65// TodoList represents a collection of todo items
66type TodoList struct {
67 Items []TodoItem `json:"items"`
68}
69
Sean McCulloughd9f13372025-04-21 15:08:49 -070070type State struct {
Philip Zeyligerd03318d2025-05-08 13:09:12 -070071 // null or 1: "old"
72 // 2: supports SSE for message updates
73 StateVersion int `json:"state_version"`
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070074 MessageCount int `json:"message_count"`
75 TotalUsage *conversation.CumulativeUsage `json:"total_usage,omitempty"`
76 InitialCommit string `json:"initial_commit"`
77 Title string `json:"title"`
78 BranchName string `json:"branch_name,omitempty"`
79 Hostname string `json:"hostname"` // deprecated
80 WorkingDir string `json:"working_dir"` // deprecated
81 OS string `json:"os"` // deprecated
82 GitOrigin string `json:"git_origin,omitempty"`
83 OutstandingLLMCalls int `json:"outstanding_llm_calls"`
84 OutstandingToolCalls []string `json:"outstanding_tool_calls"`
85 SessionID string `json:"session_id"`
86 SSHAvailable bool `json:"ssh_available"`
87 SSHError string `json:"ssh_error,omitempty"`
88 InContainer bool `json:"in_container"`
89 FirstMessageIndex int `json:"first_message_index"`
90 AgentState string `json:"agent_state,omitempty"`
91 OutsideHostname string `json:"outside_hostname,omitempty"`
92 InsideHostname string `json:"inside_hostname,omitempty"`
93 OutsideOS string `json:"outside_os,omitempty"`
94 InsideOS string `json:"inside_os,omitempty"`
95 OutsideWorkingDir string `json:"outside_working_dir,omitempty"`
96 InsideWorkingDir string `json:"inside_working_dir,omitempty"`
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -070097 TodoContent string `json:"todo_content,omitempty"` // Contains todo list JSON data
Philip Zeyligerb5739402025-06-02 07:04:34 -070098 End *loop.EndFeedback `json:"end,omitempty"` // End session feedback
Sean McCulloughd9f13372025-04-21 15:08:49 -070099}
100
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700101type InitRequest struct {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700102 // Passed to agent so that the URL it prints in the termui prompt is correct (when skaband is not used)
103 HostAddr string `json:"host_addr"`
104
105 // POST /init will start the SSH server with these configs
Sean McCullough7013e9e2025-05-14 02:03:58 +0000106 SSHAuthorizedKeys []byte `json:"ssh_authorized_keys"`
107 SSHServerIdentity []byte `json:"ssh_server_identity"`
108 SSHContainerCAKey []byte `json:"ssh_container_ca_key"`
109 SSHHostCertificate []byte `json:"ssh_host_certificate"`
110 SSHAvailable bool `json:"ssh_available"`
111 SSHError string `json:"ssh_error,omitempty"`
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700112}
113
Earl Lee2e463fb2025-04-17 11:22:22 -0700114// Server serves sketch HTTP. Server implements http.Handler.
115type Server struct {
116 mux *http.ServeMux
117 agent loop.CodingAgent
118 hostname string
119 logFile *os.File
120 // Mutex to protect terminalSessions
121 ptyMutex sync.Mutex
122 terminalSessions map[string]*terminalSession
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000123 sshAvailable bool
124 sshError string
Philip Zeyligerb5739402025-06-02 07:04:34 -0700125 // WaitGroup for clients waiting for end
126 endWaitGroup sync.WaitGroup
Earl Lee2e463fb2025-04-17 11:22:22 -0700127}
128
129func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
130 s.mux.ServeHTTP(w, r)
131}
132
133// New creates a new HTTP server.
134func New(agent loop.CodingAgent, logFile *os.File) (*Server, error) {
135 s := &Server{
136 mux: http.NewServeMux(),
137 agent: agent,
138 hostname: getHostname(),
139 logFile: logFile,
140 terminalSessions: make(map[string]*terminalSession),
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000141 sshAvailable: false,
142 sshError: "",
Earl Lee2e463fb2025-04-17 11:22:22 -0700143 }
144
145 webBundle, err := webui.Build()
146 if err != nil {
147 return nil, fmt.Errorf("failed to build web bundle, did you run 'go generate sketch.dev/loop/...'?: %w", err)
148 }
149
Philip Zeyliger25f6ff12025-05-02 04:24:10 +0000150 s.mux.HandleFunc("/stream", s.handleSSEStream)
Philip Zeyligerd3ac1122025-05-14 02:54:18 +0000151
152 // Git tool endpoints
153 s.mux.HandleFunc("/git/rawdiff", s.handleGitRawDiff)
154 s.mux.HandleFunc("/git/show", s.handleGitShow)
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700155 s.mux.HandleFunc("/git/cat", s.handleGitCat)
156 s.mux.HandleFunc("/git/save", s.handleGitSave)
Philip Zeyligerd3ac1122025-05-14 02:54:18 +0000157 s.mux.HandleFunc("/git/recentlog", s.handleGitRecentLog)
158
Earl Lee2e463fb2025-04-17 11:22:22 -0700159 s.mux.HandleFunc("/diff", func(w http.ResponseWriter, r *http.Request) {
160 // Check if a specific commit hash was requested
161 commit := r.URL.Query().Get("commit")
162
163 // Get the diff, optionally for a specific commit
164 var diff string
165 var err error
166 if commit != "" {
167 // Validate the commit hash format
168 if !isValidGitSHA(commit) {
169 http.Error(w, fmt.Sprintf("Invalid git commit SHA format: %s", commit), http.StatusBadRequest)
170 return
171 }
172
173 diff, err = agent.Diff(&commit)
174 } else {
175 diff, err = agent.Diff(nil)
176 }
177
178 if err != nil {
179 http.Error(w, fmt.Sprintf("Error generating diff: %v", err), http.StatusInternalServerError)
180 return
181 }
182
183 w.Header().Set("Content-Type", "text/plain")
184 w.Write([]byte(diff))
185 })
186
187 // Handler for initialization called by host sketch binary when inside docker.
188 s.mux.HandleFunc("/init", func(w http.ResponseWriter, r *http.Request) {
189 defer func() {
190 if err := recover(); err != nil {
191 slog.ErrorContext(r.Context(), "/init panic", slog.Any("recovered_err", err))
192
193 // Return an error response to the client
194 http.Error(w, fmt.Sprintf("panic: %v\n", err), http.StatusInternalServerError)
195 }
196 }()
197
198 if r.Method != "POST" {
199 http.Error(w, "POST required", http.StatusBadRequest)
200 return
201 }
202
203 body, err := io.ReadAll(r.Body)
204 r.Body.Close()
205 if err != nil {
206 http.Error(w, "failed to read request body: "+err.Error(), http.StatusBadRequest)
207 return
208 }
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700209
210 m := &InitRequest{}
211 if err := json.Unmarshal(body, m); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700212 http.Error(w, "bad request body: "+err.Error(), http.StatusBadRequest)
213 return
214 }
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700215
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000216 // Store SSH availability info
217 s.sshAvailable = m.SSHAvailable
218 s.sshError = m.SSHError
219
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700220 // Start the SSH server if the init request included ssh keys.
221 if len(m.SSHAuthorizedKeys) > 0 && len(m.SSHServerIdentity) > 0 {
222 go func() {
223 ctx := context.Background()
Sean McCullough7013e9e2025-05-14 02:03:58 +0000224 if err := s.ServeSSH(ctx, m.SSHServerIdentity, m.SSHAuthorizedKeys, m.SSHContainerCAKey, m.SSHHostCertificate); err != nil {
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700225 slog.ErrorContext(r.Context(), "/init ServeSSH", slog.String("err", err.Error()))
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000226 // Update SSH error if server fails to start
227 s.sshAvailable = false
228 s.sshError = err.Error()
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700229 }
230 }()
231 }
232
Earl Lee2e463fb2025-04-17 11:22:22 -0700233 ini := loop.AgentInit{
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700234 InDocker: true,
235 HostAddr: m.HostAddr,
Earl Lee2e463fb2025-04-17 11:22:22 -0700236 }
237 if err := agent.Init(ini); err != nil {
238 http.Error(w, "init failed: "+err.Error(), http.StatusInternalServerError)
239 return
240 }
241 w.Header().Set("Content-Type", "application/json")
242 io.WriteString(w, "{}\n")
243 })
244
Sean McCullough138ec242025-06-02 22:42:06 +0000245 // Handler for /port-events - returns recent port change events
246 s.mux.HandleFunc("/port-events", func(w http.ResponseWriter, r *http.Request) {
247 if r.Method != http.MethodGet {
248 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
249 return
250 }
251
252 w.Header().Set("Content-Type", "application/json")
253
254 // Get the 'since' query parameter for filtering events
255 sinceParam := r.URL.Query().Get("since")
256 var events []loop.PortEvent
257
258 // Get port monitor from agent
259 portMonitor := agent.GetPortMonitor()
260 if portMonitor == nil {
261 // Return empty array if port monitor not available
262 events = []loop.PortEvent{}
263 } else if sinceParam != "" {
264 // Parse the since timestamp
265 sinceTime, err := time.Parse(time.RFC3339, sinceParam)
266 if err != nil {
267 http.Error(w, fmt.Sprintf("Invalid 'since' timestamp format: %v", err), http.StatusBadRequest)
268 return
269 }
270 events = portMonitor.GetRecentEvents(sinceTime)
271 } else {
272 // Return all recent events
273 events = portMonitor.GetAllRecentEvents()
274 }
275
276 // Encode and return the events
277 if err := json.NewEncoder(w).Encode(events); err != nil {
278 slog.ErrorContext(r.Context(), "Error encoding port events response", slog.Any("err", err))
279 http.Error(w, "Internal server error", http.StatusInternalServerError)
280 }
281 })
282
Earl Lee2e463fb2025-04-17 11:22:22 -0700283 // Handler for /messages?start=N&end=M (start/end are optional)
284 s.mux.HandleFunc("/messages", func(w http.ResponseWriter, r *http.Request) {
285 w.Header().Set("Content-Type", "application/json")
286
287 // Extract query parameters for range
288 var start, end int
289 var err error
290
291 currentCount := agent.MessageCount()
292
293 startParam := r.URL.Query().Get("start")
294 if startParam != "" {
295 start, err = strconv.Atoi(startParam)
296 if err != nil {
297 http.Error(w, "Invalid 'start' parameter", http.StatusBadRequest)
298 return
299 }
300 }
301
302 endParam := r.URL.Query().Get("end")
303 if endParam != "" {
304 end, err = strconv.Atoi(endParam)
305 if err != nil {
306 http.Error(w, "Invalid 'end' parameter", http.StatusBadRequest)
307 return
308 }
309 } else {
310 end = currentCount
311 }
312
313 if start < 0 || start > end || end > currentCount {
314 http.Error(w, fmt.Sprintf("Invalid range: start %d end %d currentCount %d", start, end, currentCount), http.StatusBadRequest)
315 return
316 }
317
318 start = max(0, start)
319 end = min(agent.MessageCount(), end)
320 messages := agent.Messages(start, end)
321
322 // Create a JSON encoder with indentation for pretty-printing
323 encoder := json.NewEncoder(w)
324 encoder.SetIndent("", " ") // Two spaces for each indentation level
325
326 err = encoder.Encode(messages)
327 if err != nil {
328 http.Error(w, err.Error(), http.StatusInternalServerError)
329 }
330 })
331
332 // Handler for /logs - displays the contents of the log file
333 s.mux.HandleFunc("/logs", func(w http.ResponseWriter, r *http.Request) {
334 if s.logFile == nil {
335 http.Error(w, "log file not set", http.StatusNotFound)
336 return
337 }
338 logContents, err := os.ReadFile(s.logFile.Name())
339 if err != nil {
340 http.Error(w, "error reading log file: "+err.Error(), http.StatusInternalServerError)
341 return
342 }
343 w.Header().Set("Content-Type", "text/html; charset=utf-8")
344 fmt.Fprintf(w, "<!DOCTYPE html>\n<html>\n<head>\n<title>Sketchy Log File</title>\n</head>\n<body>\n")
345 fmt.Fprintf(w, "<pre>%s</pre>\n", html.EscapeString(string(logContents)))
346 fmt.Fprintf(w, "</body>\n</html>")
347 })
348
349 // Handler for /download - downloads both messages and status as a JSON file
350 s.mux.HandleFunc("/download", func(w http.ResponseWriter, r *http.Request) {
351 // Set headers for file download
352 w.Header().Set("Content-Type", "application/octet-stream")
353
354 // Generate filename with format: sketch-YYYYMMDD-HHMMSS.json
355 timestamp := time.Now().Format("20060102-150405")
356 filename := fmt.Sprintf("sketch-%s.json", timestamp)
357
358 w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
359
360 // Get all messages
361 messageCount := agent.MessageCount()
362 messages := agent.Messages(0, messageCount)
363
364 // Get status information (usage and other metadata)
365 totalUsage := agent.TotalUsage()
366 hostname := getHostname()
367 workingDir := getWorkingDir()
368
369 // Create a combined structure with all information
370 downloadData := struct {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700371 Messages []loop.AgentMessage `json:"messages"`
372 MessageCount int `json:"message_count"`
373 TotalUsage conversation.CumulativeUsage `json:"total_usage"`
374 Hostname string `json:"hostname"`
375 WorkingDir string `json:"working_dir"`
376 DownloadTime string `json:"download_time"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700377 }{
378 Messages: messages,
379 MessageCount: messageCount,
380 TotalUsage: totalUsage,
381 Hostname: hostname,
382 WorkingDir: workingDir,
383 DownloadTime: time.Now().Format(time.RFC3339),
384 }
385
386 // Marshal the JSON with indentation for better readability
387 jsonData, err := json.MarshalIndent(downloadData, "", " ")
388 if err != nil {
389 http.Error(w, err.Error(), http.StatusInternalServerError)
390 return
391 }
392 w.Write(jsonData)
393 })
394
395 // The latter doesn't return until the number of messages has changed (from seen
396 // or from when this was called.)
397 s.mux.HandleFunc("/state", func(w http.ResponseWriter, r *http.Request) {
398 pollParam := r.URL.Query().Get("poll")
399 seenParam := r.URL.Query().Get("seen")
400
401 // Get the client's current message count (if provided)
402 clientMessageCount := -1
403 var err error
404 if seenParam != "" {
405 clientMessageCount, err = strconv.Atoi(seenParam)
406 if err != nil {
407 http.Error(w, "Invalid 'seen' parameter", http.StatusBadRequest)
408 return
409 }
410 }
411
412 serverMessageCount := agent.MessageCount()
413
414 // Let lazy clients not have to specify this.
415 if clientMessageCount == -1 {
416 clientMessageCount = serverMessageCount
417 }
418
419 if pollParam == "true" {
420 ch := make(chan string)
421 go func() {
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700422 it := agent.NewIterator(r.Context(), clientMessageCount)
423 it.Next()
Earl Lee2e463fb2025-04-17 11:22:22 -0700424 close(ch)
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700425 it.Close()
Earl Lee2e463fb2025-04-17 11:22:22 -0700426 }()
427 select {
428 case <-r.Context().Done():
429 slog.DebugContext(r.Context(), "abandoned poll request")
430 return
431 case <-time.After(90 * time.Second):
432 // Let the user call /state again to get the latest to limit how long our long polls hang out.
433 slog.DebugContext(r.Context(), "longish poll request")
434 break
435 case <-ch:
436 break
437 }
438 }
439
Earl Lee2e463fb2025-04-17 11:22:22 -0700440 w.Header().Set("Content-Type", "application/json")
441
Philip Zeyliger25f6ff12025-05-02 04:24:10 +0000442 // Use the shared getState function
443 state := s.getState()
Earl Lee2e463fb2025-04-17 11:22:22 -0700444
445 // Create a JSON encoder with indentation for pretty-printing
446 encoder := json.NewEncoder(w)
447 encoder.SetIndent("", " ") // Two spaces for each indentation level
448
449 err = encoder.Encode(state)
450 if err != nil {
451 http.Error(w, err.Error(), http.StatusInternalServerError)
452 }
453 })
454
Philip Zeyliger176de792025-04-21 12:25:18 -0700455 s.mux.Handle("/static/", http.StripPrefix("/static/", gzhandler.New(webBundle)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700456
457 // Terminal WebSocket handler
458 // Terminal endpoints - predefined terminals 1-9
459 // TODO: The UI doesn't actually know how to use terminals 2-9!
460 s.mux.HandleFunc("/terminal/events/", func(w http.ResponseWriter, r *http.Request) {
461 if r.Method != http.MethodGet {
462 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
463 return
464 }
465 pathParts := strings.Split(r.URL.Path, "/")
466 if len(pathParts) < 4 {
467 http.Error(w, "Invalid terminal ID", http.StatusBadRequest)
468 return
469 }
470
471 sessionID := pathParts[3]
472 // Validate that the terminal ID is between 1-9
473 if len(sessionID) != 1 || sessionID[0] < '1' || sessionID[0] > '9' {
474 http.Error(w, "Terminal ID must be between 1 and 9", http.StatusBadRequest)
475 return
476 }
477
478 s.handleTerminalEvents(w, r, sessionID)
479 })
480
481 s.mux.HandleFunc("/terminal/input/", func(w http.ResponseWriter, r *http.Request) {
482 if r.Method != http.MethodPost {
483 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
484 return
485 }
486 pathParts := strings.Split(r.URL.Path, "/")
487 if len(pathParts) < 4 {
488 http.Error(w, "Invalid terminal ID", http.StatusBadRequest)
489 return
490 }
491 sessionID := pathParts[3]
492 s.handleTerminalInput(w, r, sessionID)
493 })
494
495 s.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
Sean McCullough86b56862025-04-18 13:04:03 -0700496 // Serve the sketch-app-shell.html file directly from the embedded filesystem
497 data, err := fs.ReadFile(webBundle, "sketch-app-shell.html")
Earl Lee2e463fb2025-04-17 11:22:22 -0700498 if err != nil {
499 http.Error(w, "File not found", http.StatusNotFound)
500 return
501 }
502 w.Header().Set("Content-Type", "text/html")
503 w.Write(data)
504 })
505
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700506 // Handler for /commit-description - returns the description of a git commit
507 s.mux.HandleFunc("/commit-description", func(w http.ResponseWriter, r *http.Request) {
508 if r.Method != http.MethodGet {
509 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
510 return
511 }
512
513 // Get the revision parameter
514 revision := r.URL.Query().Get("revision")
515 if revision == "" {
516 http.Error(w, "Missing revision parameter", http.StatusBadRequest)
517 return
518 }
519
520 // Run git command to get commit description
521 cmd := exec.Command("git", "log", "--oneline", "--decorate", "-n", "1", revision)
522 // Use the working directory from the agent
523 cmd.Dir = s.agent.WorkingDir()
524
525 output, err := cmd.CombinedOutput()
526 if err != nil {
527 http.Error(w, "Failed to get commit description: "+err.Error(), http.StatusInternalServerError)
528 return
529 }
530
531 // Prepare the response
532 resp := map[string]string{
533 "description": strings.TrimSpace(string(output)),
534 }
535
536 w.Header().Set("Content-Type", "application/json")
537 if err := json.NewEncoder(w).Encode(resp); err != nil {
538 slog.ErrorContext(r.Context(), "Error encoding commit description response", slog.Any("err", err))
539 }
540 })
541
Philip Zeyliger33d282f2025-05-03 04:01:54 +0000542 // Handler for /screenshot/{id} - serves screenshot images
543 s.mux.HandleFunc("/screenshot/", func(w http.ResponseWriter, r *http.Request) {
544 if r.Method != http.MethodGet {
545 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
546 return
547 }
548
549 // Extract the screenshot ID from the path
550 pathParts := strings.Split(r.URL.Path, "/")
551 if len(pathParts) < 3 {
552 http.Error(w, "Invalid screenshot ID", http.StatusBadRequest)
553 return
554 }
555
556 screenshotID := pathParts[2]
557
558 // Validate the ID format (prevent directory traversal)
559 if strings.Contains(screenshotID, "/") || strings.Contains(screenshotID, "\\") {
560 http.Error(w, "Invalid screenshot ID format", http.StatusBadRequest)
561 return
562 }
563
564 // Get the screenshot file path
565 filePath := browse.GetScreenshotPath(screenshotID)
566
567 // Check if the file exists
568 if _, err := os.Stat(filePath); os.IsNotExist(err) {
569 http.Error(w, "Screenshot not found", http.StatusNotFound)
570 return
571 }
572
573 // Serve the file
574 w.Header().Set("Content-Type", "image/png")
575 w.Header().Set("Cache-Control", "max-age=3600") // Cache for an hour
576 http.ServeFile(w, r, filePath)
577 })
578
Earl Lee2e463fb2025-04-17 11:22:22 -0700579 // Handler for POST /chat
580 s.mux.HandleFunc("/chat", func(w http.ResponseWriter, r *http.Request) {
581 if r.Method != http.MethodPost {
582 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
583 return
584 }
585
586 // Parse the request body
587 var requestBody struct {
588 Message string `json:"message"`
589 }
590
591 decoder := json.NewDecoder(r.Body)
592 if err := decoder.Decode(&requestBody); err != nil {
593 http.Error(w, "Invalid request body: "+err.Error(), http.StatusBadRequest)
594 return
595 }
596 defer r.Body.Close()
597
598 if requestBody.Message == "" {
599 http.Error(w, "Message cannot be empty", http.StatusBadRequest)
600 return
601 }
602
603 agent.UserMessage(r.Context(), requestBody.Message)
604
605 w.WriteHeader(http.StatusOK)
606 })
607
Philip Zeyligerf84e88c2025-05-14 23:19:01 +0000608 // Handler for POST /upload - uploads a file to /tmp
609 s.mux.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
610 if r.Method != http.MethodPost {
611 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
612 return
613 }
614
615 // Limit to 10MB file size
616 r.Body = http.MaxBytesReader(w, r.Body, 10*1024*1024)
617
618 // Parse the multipart form
619 if err := r.ParseMultipartForm(10 * 1024 * 1024); err != nil {
620 http.Error(w, "Failed to parse form: "+err.Error(), http.StatusBadRequest)
621 return
622 }
623
624 // Get the file from the multipart form
625 file, handler, err := r.FormFile("file")
626 if err != nil {
627 http.Error(w, "Failed to get uploaded file: "+err.Error(), http.StatusBadRequest)
628 return
629 }
630 defer file.Close()
631
632 // Generate a unique ID (8 random bytes converted to 16 hex chars)
633 randBytes := make([]byte, 8)
634 if _, err := rand.Read(randBytes); err != nil {
635 http.Error(w, "Failed to generate random filename: "+err.Error(), http.StatusInternalServerError)
636 return
637 }
638
639 // Get file extension from the original filename
640 ext := filepath.Ext(handler.Filename)
641
642 // Create a unique filename in the /tmp directory
643 filename := fmt.Sprintf("/tmp/sketch_file_%s%s", hex.EncodeToString(randBytes), ext)
644
645 // Create the destination file
646 destFile, err := os.Create(filename)
647 if err != nil {
648 http.Error(w, "Failed to create destination file: "+err.Error(), http.StatusInternalServerError)
649 return
650 }
651 defer destFile.Close()
652
653 // Copy the file contents to the destination file
654 if _, err := io.Copy(destFile, file); err != nil {
655 http.Error(w, "Failed to save file: "+err.Error(), http.StatusInternalServerError)
656 return
657 }
658
659 // Return the path to the saved file
660 w.Header().Set("Content-Type", "application/json")
661 json.NewEncoder(w).Encode(map[string]string{"path": filename})
662 })
663
Earl Lee2e463fb2025-04-17 11:22:22 -0700664 // Handler for /cancel - cancels the current inner loop in progress
665 s.mux.HandleFunc("/cancel", func(w http.ResponseWriter, r *http.Request) {
666 if r.Method != http.MethodPost {
667 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
668 return
669 }
670
671 // Parse the request body (optional)
672 var requestBody struct {
673 Reason string `json:"reason"`
674 ToolCallID string `json:"tool_call_id"`
675 }
676
677 decoder := json.NewDecoder(r.Body)
678 if err := decoder.Decode(&requestBody); err != nil && err != io.EOF {
679 http.Error(w, "Invalid request body: "+err.Error(), http.StatusBadRequest)
680 return
681 }
682 defer r.Body.Close()
683
684 cancelReason := "user requested cancellation"
685 if requestBody.Reason != "" {
686 cancelReason = requestBody.Reason
687 }
688
689 if requestBody.ToolCallID != "" {
690 err := agent.CancelToolUse(requestBody.ToolCallID, fmt.Errorf("%s", cancelReason))
691 if err != nil {
692 http.Error(w, err.Error(), http.StatusBadRequest)
693 return
694 }
695 // Return a success response
696 w.Header().Set("Content-Type", "application/json")
697 json.NewEncoder(w).Encode(map[string]string{
698 "status": "cancelled",
699 "too_use_id": requestBody.ToolCallID,
Philip Zeyliger8d50d7b2025-04-23 13:12:40 -0700700 "reason": cancelReason,
701 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700702 return
703 }
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000704 // Call the CancelTurn method
705 agent.CancelTurn(fmt.Errorf("%s", cancelReason))
Earl Lee2e463fb2025-04-17 11:22:22 -0700706 // Return a success response
707 w.Header().Set("Content-Type", "application/json")
708 json.NewEncoder(w).Encode(map[string]string{"status": "cancelled", "reason": cancelReason})
709 })
710
Pokey Rule397871d2025-05-19 15:02:45 +0100711 // Handler for /end - shuts down the inner sketch process
712 s.mux.HandleFunc("/end", func(w http.ResponseWriter, r *http.Request) {
713 if r.Method != http.MethodPost {
714 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
715 return
716 }
717
718 // Parse the request body (optional)
719 var requestBody struct {
Philip Zeyligerb5739402025-06-02 07:04:34 -0700720 Reason string `json:"reason"`
721 Happy *bool `json:"happy,omitempty"`
722 Comment string `json:"comment,omitempty"`
Pokey Rule397871d2025-05-19 15:02:45 +0100723 }
724
725 decoder := json.NewDecoder(r.Body)
726 if err := decoder.Decode(&requestBody); err != nil && err != io.EOF {
727 http.Error(w, "Invalid request body: "+err.Error(), http.StatusBadRequest)
728 return
729 }
730 defer r.Body.Close()
731
732 endReason := "user requested end of session"
733 if requestBody.Reason != "" {
734 endReason = requestBody.Reason
735 }
736
Philip Zeyligerb5739402025-06-02 07:04:34 -0700737 // Store end feedback if provided
738 if requestBody.Happy != nil {
739 feedback := &loop.EndFeedback{
740 Happy: *requestBody.Happy,
741 Comment: requestBody.Comment,
742 }
743 s.agent.SetEndFeedback(feedback)
744 slog.Info("End session feedback received", "happy", feedback.Happy, "comment", feedback.Comment)
745 }
746
Pokey Rule397871d2025-05-19 15:02:45 +0100747 // Send success response before exiting
748 w.Header().Set("Content-Type", "application/json")
749 json.NewEncoder(w).Encode(map[string]string{"status": "ending", "reason": endReason})
750 if f, ok := w.(http.Flusher); ok {
751 f.Flush()
752 }
753
754 // Log that we're shutting down
755 slog.Info("Ending session", "reason", endReason)
756
Philip Zeyligerb5739402025-06-02 07:04:34 -0700757 // Wait for skaband clients that are waiting for end (with timeout)
Pokey Rule397871d2025-05-19 15:02:45 +0100758 go func() {
Philip Zeyligerb5739402025-06-02 07:04:34 -0700759 startTime := time.Now()
760 // Wait up to 2 seconds for waiting clients to receive the end message
761 done := make(chan struct{})
762 go func() {
763 s.endWaitGroup.Wait()
764 close(done)
765 }()
766
767 select {
768 case <-done:
769 slog.Info("All waiting clients notified of end")
770 case <-time.After(2 * time.Second):
771 slog.Info("Timeout waiting for clients, proceeding with shutdown")
772 }
773
774 // Ensure we've been running for at least 100ms to allow response to be sent
775 elapsed := time.Since(startTime)
776 if elapsed < 100*time.Millisecond {
777 time.Sleep(100*time.Millisecond - elapsed)
778 }
779
Pokey Rule397871d2025-05-19 15:02:45 +0100780 os.Exit(0)
781 }()
782 })
783
Earl Lee2e463fb2025-04-17 11:22:22 -0700784 debugMux := initDebugMux()
785 s.mux.HandleFunc("/debug/", func(w http.ResponseWriter, r *http.Request) {
786 debugMux.ServeHTTP(w, r)
787 })
788
789 return s, nil
790}
791
792// Utility functions
793func getHostname() string {
794 hostname, err := os.Hostname()
795 if err != nil {
796 return "unknown"
797 }
798 return hostname
799}
800
801func getWorkingDir() string {
802 wd, err := os.Getwd()
803 if err != nil {
804 return "unknown"
805 }
806 return wd
807}
808
809// createTerminalSession creates a new terminal session with the given ID
810func (s *Server) createTerminalSession(sessionID string) (*terminalSession, error) {
811 // Start a new shell process
812 shellPath := getShellPath()
813 cmd := exec.Command(shellPath)
814
815 // Get working directory from the agent if possible
816 workDir := getWorkingDir()
817 cmd.Dir = workDir
818
819 // Set up environment
820 cmd.Env = append(os.Environ(), "TERM=xterm-256color")
821
822 // Start the command with a pty
823 ptmx, err := pty.Start(cmd)
824 if err != nil {
825 slog.Error("Failed to start pty", "error", err)
826 return nil, err
827 }
828
829 // Create the terminal session
830 session := &terminalSession{
831 pty: ptmx,
832 eventsClients: make(map[chan []byte]bool),
833 cmd: cmd,
834 }
835
836 // Start goroutine to read from pty and broadcast to all connected SSE clients
837 go s.readFromPtyAndBroadcast(sessionID, session)
838
839 return session, nil
840} // handleTerminalEvents handles SSE connections for terminal output
841func (s *Server) handleTerminalEvents(w http.ResponseWriter, r *http.Request, sessionID string) {
842 // Check if the session exists, if not, create it
843 s.ptyMutex.Lock()
844 session, exists := s.terminalSessions[sessionID]
845
846 if !exists {
847 // Create a new terminal session
848 var err error
849 session, err = s.createTerminalSession(sessionID)
850 if err != nil {
851 s.ptyMutex.Unlock()
852 http.Error(w, fmt.Sprintf("Failed to create terminal: %v", err), http.StatusInternalServerError)
853 return
854 }
855
856 // Store the new session
857 s.terminalSessions[sessionID] = session
858 }
859 s.ptyMutex.Unlock()
860
861 // Set headers for SSE
862 w.Header().Set("Content-Type", "text/event-stream")
863 w.Header().Set("Cache-Control", "no-cache")
864 w.Header().Set("Connection", "keep-alive")
865 w.Header().Set("Access-Control-Allow-Origin", "*")
866
867 // Create a channel for this client
868 events := make(chan []byte, 4096) // Buffer to prevent blocking
869
870 // Register this client's channel
871 session.eventsClientsMutex.Lock()
872 clientID := session.lastEventClientID + 1
873 session.lastEventClientID = clientID
874 session.eventsClients[events] = true
875 session.eventsClientsMutex.Unlock()
876
877 // When the client disconnects, remove their channel
878 defer func() {
879 session.eventsClientsMutex.Lock()
880 delete(session.eventsClients, events)
881 close(events)
882 session.eventsClientsMutex.Unlock()
883 }()
884
885 // Flush to send headers to client immediately
886 if f, ok := w.(http.Flusher); ok {
887 f.Flush()
888 }
889
890 // Send events to the client as they arrive
891 for {
892 select {
893 case <-r.Context().Done():
894 return
895 case data := <-events:
896 // Format as SSE with base64 encoding
897 fmt.Fprintf(w, "data: %s\n\n", base64.StdEncoding.EncodeToString(data))
898
899 // Flush the data immediately
900 if f, ok := w.(http.Flusher); ok {
901 f.Flush()
902 }
903 }
904 }
905}
906
907// handleTerminalInput processes input to the terminal
908func (s *Server) handleTerminalInput(w http.ResponseWriter, r *http.Request, sessionID string) {
909 // Check if the session exists
910 s.ptyMutex.Lock()
911 session, exists := s.terminalSessions[sessionID]
912 s.ptyMutex.Unlock()
913
914 if !exists {
915 http.Error(w, "Terminal session not found", http.StatusNotFound)
916 return
917 }
918
919 // Read the request body (terminal input or resize command)
920 body, err := io.ReadAll(r.Body)
921 if err != nil {
922 http.Error(w, "Failed to read request body", http.StatusBadRequest)
923 return
924 }
925
926 // Check if it's a resize message
927 if len(body) > 0 && body[0] == '{' {
928 var msg TerminalMessage
929 if err := json.Unmarshal(body, &msg); err == nil && msg.Type == "resize" {
930 if msg.Cols > 0 && msg.Rows > 0 {
931 pty.Setsize(session.pty, &pty.Winsize{
932 Cols: msg.Cols,
933 Rows: msg.Rows,
934 })
935
936 // Respond with success
937 w.WriteHeader(http.StatusOK)
938 return
939 }
940 }
941 }
942
943 // Regular terminal input
944 _, err = session.pty.Write(body)
945 if err != nil {
946 slog.Error("Failed to write to pty", "error", err)
947 http.Error(w, "Failed to write to terminal", http.StatusInternalServerError)
948 return
949 }
950
951 // Respond with success
952 w.WriteHeader(http.StatusOK)
953}
954
955// readFromPtyAndBroadcast reads output from the PTY and broadcasts it to all connected clients
956func (s *Server) readFromPtyAndBroadcast(sessionID string, session *terminalSession) {
957 buf := make([]byte, 4096)
958 defer func() {
959 // Clean up when done
960 s.ptyMutex.Lock()
961 delete(s.terminalSessions, sessionID)
962 s.ptyMutex.Unlock()
963
964 // Close the PTY
965 session.pty.Close()
966
967 // Ensure process is terminated
968 if session.cmd.Process != nil {
969 session.cmd.Process.Signal(syscall.SIGTERM)
970 time.Sleep(100 * time.Millisecond)
971 session.cmd.Process.Kill()
972 }
973
974 // Close all client channels
975 session.eventsClientsMutex.Lock()
976 for ch := range session.eventsClients {
977 delete(session.eventsClients, ch)
978 close(ch)
979 }
980 session.eventsClientsMutex.Unlock()
981 }()
982
983 for {
984 n, err := session.pty.Read(buf)
985 if err != nil {
986 if err != io.EOF {
987 slog.Error("Failed to read from pty", "error", err)
988 }
989 break
990 }
991
992 // Make a copy of the data for each client
993 data := make([]byte, n)
994 copy(data, buf[:n])
995
996 // Broadcast to all connected clients
997 session.eventsClientsMutex.Lock()
998 for ch := range session.eventsClients {
999 // Try to send, but don't block if channel is full
1000 select {
1001 case ch <- data:
1002 default:
1003 // Channel is full, drop the message for this client
1004 }
1005 }
1006 session.eventsClientsMutex.Unlock()
1007 }
1008}
1009
1010// getShellPath returns the path to the shell to use
1011func getShellPath() string {
1012 // Try to use the user's preferred shell
1013 shell := os.Getenv("SHELL")
1014 if shell != "" {
1015 return shell
1016 }
1017
1018 // Default to bash on Unix-like systems
1019 if _, err := os.Stat("/bin/bash"); err == nil {
1020 return "/bin/bash"
1021 }
1022
1023 // Fall back to sh
1024 return "/bin/sh"
1025}
1026
1027func initDebugMux() *http.ServeMux {
1028 mux := http.NewServeMux()
Philip Zeyliger8d8b7ac2025-05-21 09:57:23 -07001029 build := "unknown build"
1030 bi, ok := debug.ReadBuildInfo()
1031 if ok {
1032 build = fmt.Sprintf("%s@%v\n", bi.Path, bi.Main.Version)
1033 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001034 mux.HandleFunc("GET /debug/{$}", func(w http.ResponseWriter, r *http.Request) {
1035 w.Header().Set("Content-Type", "text/html; charset=utf-8")
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001036 // TODO: pid is not as useful as "outside pid"
Earl Lee2e463fb2025-04-17 11:22:22 -07001037 fmt.Fprintf(w, `<!doctype html>
1038 <html><head><title>sketch debug</title></head><body>
1039 <h1>sketch debug</h1>
Philip Zeyliger8d8b7ac2025-05-21 09:57:23 -07001040 pid %d<br>
1041 build %s<br>
Earl Lee2e463fb2025-04-17 11:22:22 -07001042 <ul>
1043 <li><a href="/debug/pprof/cmdline">pprof/cmdline</a></li>
1044 <li><a href="/debug/pprof/profile">pprof/profile</a></li>
1045 <li><a href="/debug/pprof/symbol">pprof/symbol</a></li>
1046 <li><a href="/debug/pprof/trace">pprof/trace</a></li>
1047 <li><a href="/debug/pprof/goroutine?debug=1">pprof/goroutine?debug=1</a></li>
1048 <li><a href="/debug/metrics">metrics</a></li>
1049 </ul>
1050 </body>
1051 </html>
Philip Zeyliger8d8b7ac2025-05-21 09:57:23 -07001052 `, os.Getpid(), build)
Earl Lee2e463fb2025-04-17 11:22:22 -07001053 })
1054 mux.HandleFunc("GET /debug/pprof/", pprof.Index)
1055 mux.HandleFunc("GET /debug/pprof/cmdline", pprof.Cmdline)
1056 mux.HandleFunc("GET /debug/pprof/profile", pprof.Profile)
1057 mux.HandleFunc("GET /debug/pprof/symbol", pprof.Symbol)
1058 mux.HandleFunc("GET /debug/pprof/trace", pprof.Trace)
1059 return mux
1060}
1061
1062// isValidGitSHA validates if a string looks like a valid git SHA hash.
1063// Git SHAs are hexadecimal strings of at least 4 characters but typically 7, 8, or 40 characters.
1064func isValidGitSHA(sha string) bool {
1065 // Git SHA must be a hexadecimal string with at least 4 characters
1066 if len(sha) < 4 || len(sha) > 40 {
1067 return false
1068 }
1069
1070 // Check if the string only contains hexadecimal characters
1071 for _, char := range sha {
1072 if !(char >= '0' && char <= '9') && !(char >= 'a' && char <= 'f') && !(char >= 'A' && char <= 'F') {
1073 return false
1074 }
1075 }
1076
1077 return true
1078}
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001079
1080// /stream?from=N endpoint for Server-Sent Events
1081func (s *Server) handleSSEStream(w http.ResponseWriter, r *http.Request) {
1082 w.Header().Set("Content-Type", "text/event-stream")
1083 w.Header().Set("Cache-Control", "no-cache")
1084 w.Header().Set("Connection", "keep-alive")
1085 w.Header().Set("Access-Control-Allow-Origin", "*")
1086
1087 // Extract the 'from' parameter
1088 fromParam := r.URL.Query().Get("from")
1089 var fromIndex int
1090 var err error
1091 if fromParam != "" {
1092 fromIndex, err = strconv.Atoi(fromParam)
1093 if err != nil {
1094 http.Error(w, "Invalid 'from' parameter", http.StatusBadRequest)
1095 return
1096 }
1097 }
1098
Philip Zeyligerb5739402025-06-02 07:04:34 -07001099 // Check if this client is waiting for end
1100 waitForEnd := r.URL.Query().Get("wait_for_end") == "true"
1101 if waitForEnd {
1102 s.endWaitGroup.Add(1)
1103 defer func() {
1104 if waitForEnd {
1105 s.endWaitGroup.Done()
1106 }
1107 }()
1108 }
1109
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001110 // Ensure 'from' is valid
1111 currentCount := s.agent.MessageCount()
1112 if fromIndex < 0 {
1113 fromIndex = 0
1114 } else if fromIndex > currentCount {
1115 fromIndex = currentCount
1116 }
1117
1118 // Send the current state immediately
1119 state := s.getState()
1120
1121 // Create JSON encoder
1122 encoder := json.NewEncoder(w)
1123
1124 // Send state as an event
1125 fmt.Fprintf(w, "event: state\n")
1126 fmt.Fprintf(w, "data: ")
1127 encoder.Encode(state)
1128 fmt.Fprintf(w, "\n\n")
1129
1130 if f, ok := w.(http.Flusher); ok {
1131 f.Flush()
1132 }
1133
1134 // Create a context for the SSE stream
1135 ctx := r.Context()
1136
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001137 // Setup heartbeat timer
1138 heartbeatTicker := time.NewTicker(45 * time.Second)
1139 defer heartbeatTicker.Stop()
1140
1141 // Create a channel for messages
1142 messageChan := make(chan *loop.AgentMessage, 10)
1143
Philip Zeyligereab12de2025-05-14 02:35:53 +00001144 // Create a channel for state transitions
1145 stateChan := make(chan *loop.StateTransition, 10)
1146
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001147 // Start a goroutine to read messages without blocking the heartbeat
1148 go func() {
Pokey Rule9d7f0cc2025-05-20 11:43:26 +01001149 // Create an iterator to receive new messages as they arrive
1150 iterator := s.agent.NewIterator(ctx, fromIndex) // Start from the requested index
1151 defer iterator.Close()
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001152 defer close(messageChan)
1153 for {
1154 // This can block, but it's in its own goroutine
1155 newMessage := iterator.Next()
1156 if newMessage == nil {
1157 // No message available (likely due to context cancellation)
1158 slog.InfoContext(ctx, "No more messages available, ending message stream")
1159 return
1160 }
1161
1162 select {
1163 case messageChan <- newMessage:
1164 // Message sent to channel
1165 case <-ctx.Done():
1166 // Context cancelled
1167 return
1168 }
1169 }
1170 }()
1171
Philip Zeyligereab12de2025-05-14 02:35:53 +00001172 // Start a goroutine to read state transitions
1173 go func() {
Pokey Rule9d7f0cc2025-05-20 11:43:26 +01001174 // Create an iterator to receive state transitions
1175 stateIterator := s.agent.NewStateTransitionIterator(ctx)
1176 defer stateIterator.Close()
Philip Zeyligereab12de2025-05-14 02:35:53 +00001177 defer close(stateChan)
1178 for {
1179 // This can block, but it's in its own goroutine
1180 newTransition := stateIterator.Next()
1181 if newTransition == nil {
1182 // No transition available (likely due to context cancellation)
1183 slog.InfoContext(ctx, "No more state transitions available, ending state stream")
1184 return
1185 }
1186
1187 select {
1188 case stateChan <- newTransition:
1189 // Transition sent to channel
1190 case <-ctx.Done():
1191 // Context cancelled
1192 return
1193 }
1194 }
1195 }()
1196
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001197 // Stay connected and stream real-time updates
1198 for {
1199 select {
1200 case <-heartbeatTicker.C:
1201 // Send heartbeat event
1202 fmt.Fprintf(w, "event: heartbeat\n")
1203 fmt.Fprintf(w, "data: %d\n\n", time.Now().Unix())
1204
1205 // Flush to send the heartbeat immediately
1206 if f, ok := w.(http.Flusher); ok {
1207 f.Flush()
1208 }
1209
1210 case <-ctx.Done():
1211 // Client disconnected
1212 slog.InfoContext(ctx, "Client disconnected from SSE stream")
1213 return
1214
Philip Zeyligereab12de2025-05-14 02:35:53 +00001215 case _, ok := <-stateChan:
1216 if !ok {
1217 // Channel closed
1218 slog.InfoContext(ctx, "State transition channel closed, ending SSE stream")
1219 return
1220 }
1221
1222 // Get updated state
1223 state = s.getState()
1224
Philip Zeyligerb5739402025-06-02 07:04:34 -07001225 // Check if end feedback is present and this client was waiting for it
1226 if waitForEnd && state.End != nil {
1227 s.endWaitGroup.Done()
1228 waitForEnd = false // Mark that we've handled the end condition
1229 }
1230
Philip Zeyligereab12de2025-05-14 02:35:53 +00001231 // Send updated state after the state transition
1232 fmt.Fprintf(w, "event: state\n")
1233 fmt.Fprintf(w, "data: ")
1234 encoder.Encode(state)
1235 fmt.Fprintf(w, "\n\n")
1236
1237 // Flush to send the state immediately
1238 if f, ok := w.(http.Flusher); ok {
1239 f.Flush()
1240 }
1241
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001242 case newMessage, ok := <-messageChan:
1243 if !ok {
1244 // Channel closed
1245 slog.InfoContext(ctx, "Message channel closed, ending SSE stream")
1246 return
1247 }
1248
1249 // Send the new message as an event
1250 fmt.Fprintf(w, "event: message\n")
1251 fmt.Fprintf(w, "data: ")
1252 encoder.Encode(newMessage)
1253 fmt.Fprintf(w, "\n\n")
1254
1255 // Get updated state
1256 state = s.getState()
1257
Philip Zeyligerb5739402025-06-02 07:04:34 -07001258 // Check if end feedback is present and this client was waiting for it
1259 if waitForEnd && state.End != nil {
1260 s.endWaitGroup.Done()
1261 waitForEnd = false // Mark that we've handled the end condition
1262 }
1263
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001264 // Send updated state after the message
1265 fmt.Fprintf(w, "event: state\n")
1266 fmt.Fprintf(w, "data: ")
1267 encoder.Encode(state)
1268 fmt.Fprintf(w, "\n\n")
1269
1270 // Flush to send the message and state immediately
1271 if f, ok := w.(http.Flusher); ok {
1272 f.Flush()
1273 }
1274 }
1275 }
1276}
1277
1278// Helper function to get the current state
1279func (s *Server) getState() State {
1280 serverMessageCount := s.agent.MessageCount()
1281 totalUsage := s.agent.TotalUsage()
1282
1283 return State{
Philip Zeyliger49edc922025-05-14 09:45:45 -07001284 StateVersion: 2,
1285 MessageCount: serverMessageCount,
1286 TotalUsage: &totalUsage,
1287 Hostname: s.hostname,
1288 WorkingDir: getWorkingDir(),
1289 // TODO: Rename this field to sketch-base?
1290 InitialCommit: s.agent.SketchGitBase(),
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001291 Title: s.agent.Title(),
1292 BranchName: s.agent.BranchName(),
1293 OS: s.agent.OS(),
1294 OutsideHostname: s.agent.OutsideHostname(),
1295 InsideHostname: s.hostname,
1296 OutsideOS: s.agent.OutsideOS(),
1297 InsideOS: s.agent.OS(),
1298 OutsideWorkingDir: s.agent.OutsideWorkingDir(),
1299 InsideWorkingDir: getWorkingDir(),
1300 GitOrigin: s.agent.GitOrigin(),
1301 OutstandingLLMCalls: s.agent.OutstandingLLMCallCount(),
1302 OutstandingToolCalls: s.agent.OutstandingToolCalls(),
1303 SessionID: s.agent.SessionID(),
1304 SSHAvailable: s.sshAvailable,
1305 SSHError: s.sshError,
1306 InContainer: s.agent.IsInContainer(),
1307 FirstMessageIndex: s.agent.FirstMessageIndex(),
1308 AgentState: s.agent.CurrentStateName(),
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -07001309 TodoContent: s.agent.CurrentTodoContent(),
Philip Zeyligerb5739402025-06-02 07:04:34 -07001310 End: s.agent.GetEndFeedback(),
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001311 }
1312}
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001313
1314func (s *Server) handleGitRawDiff(w http.ResponseWriter, r *http.Request) {
1315 if r.Method != "GET" {
1316 w.WriteHeader(http.StatusMethodNotAllowed)
1317 return
1318 }
1319
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +00001320 // Get the git repository root directory from agent
1321 repoDir := s.agent.RepoRoot()
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001322
1323 // Parse query parameters
1324 query := r.URL.Query()
1325 commit := query.Get("commit")
1326 from := query.Get("from")
1327 to := query.Get("to")
1328
1329 // If commit is specified, use commit^ and commit as from and to
1330 if commit != "" {
1331 from = commit + "^"
1332 to = commit
1333 }
1334
1335 // Check if we have enough parameters
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001336 if from == "" {
1337 http.Error(w, "Missing required parameter: either 'commit' or at least 'from'", http.StatusBadRequest)
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001338 return
1339 }
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001340 // Note: 'to' can be empty to indicate working directory (unstaged changes)
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001341
1342 // Call the git_tools function
1343 diff, err := git_tools.GitRawDiff(repoDir, from, to)
1344 if err != nil {
1345 http.Error(w, fmt.Sprintf("Error getting git diff: %v", err), http.StatusInternalServerError)
1346 return
1347 }
1348
1349 // Return the result as JSON
1350 w.Header().Set("Content-Type", "application/json")
1351 if err := json.NewEncoder(w).Encode(diff); err != nil {
1352 http.Error(w, fmt.Sprintf("Error encoding response: %v", err), http.StatusInternalServerError)
1353 return
1354 }
1355}
1356
1357func (s *Server) handleGitShow(w http.ResponseWriter, r *http.Request) {
1358 if r.Method != "GET" {
1359 w.WriteHeader(http.StatusMethodNotAllowed)
1360 return
1361 }
1362
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +00001363 // Get the git repository root directory from agent
1364 repoDir := s.agent.RepoRoot()
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001365
1366 // Parse query parameters
1367 hash := r.URL.Query().Get("hash")
1368 if hash == "" {
1369 http.Error(w, "Missing required parameter: 'hash'", http.StatusBadRequest)
1370 return
1371 }
1372
1373 // Call the git_tools function
1374 show, err := git_tools.GitShow(repoDir, hash)
1375 if err != nil {
1376 http.Error(w, fmt.Sprintf("Error running git show: %v", err), http.StatusInternalServerError)
1377 return
1378 }
1379
1380 // Create a JSON response
1381 response := map[string]string{
1382 "hash": hash,
1383 "output": show,
1384 }
1385
1386 // Return the result as JSON
1387 w.Header().Set("Content-Type", "application/json")
1388 if err := json.NewEncoder(w).Encode(response); err != nil {
1389 http.Error(w, fmt.Sprintf("Error encoding response: %v", err), http.StatusInternalServerError)
1390 return
1391 }
1392}
1393
1394func (s *Server) handleGitRecentLog(w http.ResponseWriter, r *http.Request) {
1395 if r.Method != "GET" {
1396 w.WriteHeader(http.StatusMethodNotAllowed)
1397 return
1398 }
1399
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +00001400 // Get the git repository root directory and initial commit from agent
1401 repoDir := s.agent.RepoRoot()
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001402 initialCommit := s.agent.SketchGitBaseRef()
1403
1404 // Call the git_tools function
1405 log, err := git_tools.GitRecentLog(repoDir, initialCommit)
1406 if err != nil {
1407 http.Error(w, fmt.Sprintf("Error getting git log: %v", err), http.StatusInternalServerError)
1408 return
1409 }
1410
1411 // Return the result as JSON
1412 w.Header().Set("Content-Type", "application/json")
1413 if err := json.NewEncoder(w).Encode(log); err != nil {
1414 http.Error(w, fmt.Sprintf("Error encoding response: %v", err), http.StatusInternalServerError)
1415 return
1416 }
1417}
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001418
1419func (s *Server) handleGitCat(w http.ResponseWriter, r *http.Request) {
1420 if r.Method != "GET" {
1421 w.WriteHeader(http.StatusMethodNotAllowed)
1422 return
1423 }
1424
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +00001425 // Get the git repository root directory from agent
1426 repoDir := s.agent.RepoRoot()
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001427
1428 // Parse query parameters
1429 query := r.URL.Query()
1430 path := query.Get("path")
1431
1432 // Check if path is provided
1433 if path == "" {
1434 http.Error(w, "Missing required parameter: path", http.StatusBadRequest)
1435 return
1436 }
1437
1438 // Get file content using GitCat
1439 content, err := git_tools.GitCat(repoDir, path)
1440 if err != nil {
1441 http.Error(w, fmt.Sprintf("Error reading file: %v", err), http.StatusInternalServerError)
1442 return
1443 }
1444
1445 // Return the content as JSON for consistency with other endpoints
1446 w.Header().Set("Content-Type", "application/json")
1447 if err := json.NewEncoder(w).Encode(map[string]string{"output": content}); err != nil {
1448 http.Error(w, fmt.Sprintf("Error encoding response: %v", err), http.StatusInternalServerError)
1449 return
1450 }
1451}
1452
1453func (s *Server) handleGitSave(w http.ResponseWriter, r *http.Request) {
1454 if r.Method != "POST" {
1455 w.WriteHeader(http.StatusMethodNotAllowed)
1456 return
1457 }
1458
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +00001459 // Get the git repository root directory from agent
1460 repoDir := s.agent.RepoRoot()
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001461
1462 // Parse request body
1463 var requestBody struct {
1464 Path string `json:"path"`
1465 Content string `json:"content"`
1466 }
1467
1468 if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {
1469 http.Error(w, fmt.Sprintf("Error parsing request body: %v", err), http.StatusBadRequest)
1470 return
1471 }
1472 defer r.Body.Close()
1473
1474 // Check if path is provided
1475 if requestBody.Path == "" {
1476 http.Error(w, "Missing required parameter: path", http.StatusBadRequest)
1477 return
1478 }
1479
1480 // Save file content using GitSaveFile
1481 err := git_tools.GitSaveFile(repoDir, requestBody.Path, requestBody.Content)
1482 if err != nil {
1483 http.Error(w, fmt.Sprintf("Error saving file: %v", err), http.StatusInternalServerError)
1484 return
1485 }
1486
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001487 // Auto-commit the changes
1488 err = git_tools.AutoCommitDiffViewChanges(r.Context(), repoDir, requestBody.Path)
1489 if err != nil {
1490 http.Error(w, fmt.Sprintf("Error auto-committing changes: %v", err), http.StatusInternalServerError)
1491 return
1492 }
1493
1494 // Detect git changes to push and notify user
Philip Zeyliger9bca61e2025-05-22 12:40:06 -07001495 if err = s.agent.DetectGitChanges(r.Context()); err != nil {
1496 http.Error(w, fmt.Sprintf("Error detecting git changes: %v", err), http.StatusInternalServerError)
1497 return
1498 }
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001499
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001500 // Return simple success response
1501 w.WriteHeader(http.StatusOK)
1502 w.Write([]byte("ok"))
1503}