blob: 5a657f80788d33ddd3a8abfe9cfffc99235f1074 [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"`
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -070077 Slug string `json:"slug,omitempty"`
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070078 BranchName string `json:"branch_name,omitempty"`
Philip Zeyligerbe7802a2025-06-04 20:15:25 +000079 BranchPrefix string `json:"branch_prefix,omitempty"`
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070080 Hostname string `json:"hostname"` // deprecated
81 WorkingDir string `json:"working_dir"` // deprecated
82 OS string `json:"os"` // deprecated
83 GitOrigin string `json:"git_origin,omitempty"`
84 OutstandingLLMCalls int `json:"outstanding_llm_calls"`
85 OutstandingToolCalls []string `json:"outstanding_tool_calls"`
86 SessionID string `json:"session_id"`
87 SSHAvailable bool `json:"ssh_available"`
88 SSHError string `json:"ssh_error,omitempty"`
89 InContainer bool `json:"in_container"`
90 FirstMessageIndex int `json:"first_message_index"`
91 AgentState string `json:"agent_state,omitempty"`
92 OutsideHostname string `json:"outside_hostname,omitempty"`
93 InsideHostname string `json:"inside_hostname,omitempty"`
94 OutsideOS string `json:"outside_os,omitempty"`
95 InsideOS string `json:"inside_os,omitempty"`
96 OutsideWorkingDir string `json:"outside_working_dir,omitempty"`
97 InsideWorkingDir string `json:"inside_working_dir,omitempty"`
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -070098 TodoContent string `json:"todo_content,omitempty"` // Contains todo list JSON data
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
737 // Send success response before exiting
738 w.Header().Set("Content-Type", "application/json")
739 json.NewEncoder(w).Encode(map[string]string{"status": "ending", "reason": endReason})
740 if f, ok := w.(http.Flusher); ok {
741 f.Flush()
742 }
743
744 // Log that we're shutting down
745 slog.Info("Ending session", "reason", endReason)
746
Philip Zeyligerb5739402025-06-02 07:04:34 -0700747 // Wait for skaband clients that are waiting for end (with timeout)
Pokey Rule397871d2025-05-19 15:02:45 +0100748 go func() {
Philip Zeyligerb5739402025-06-02 07:04:34 -0700749 startTime := time.Now()
750 // Wait up to 2 seconds for waiting clients to receive the end message
751 done := make(chan struct{})
752 go func() {
753 s.endWaitGroup.Wait()
754 close(done)
755 }()
756
757 select {
758 case <-done:
759 slog.Info("All waiting clients notified of end")
760 case <-time.After(2 * time.Second):
761 slog.Info("Timeout waiting for clients, proceeding with shutdown")
762 }
763
764 // Ensure we've been running for at least 100ms to allow response to be sent
765 elapsed := time.Since(startTime)
766 if elapsed < 100*time.Millisecond {
767 time.Sleep(100*time.Millisecond - elapsed)
768 }
769
Pokey Rule397871d2025-05-19 15:02:45 +0100770 os.Exit(0)
771 }()
772 })
773
Earl Lee2e463fb2025-04-17 11:22:22 -0700774 debugMux := initDebugMux()
775 s.mux.HandleFunc("/debug/", func(w http.ResponseWriter, r *http.Request) {
776 debugMux.ServeHTTP(w, r)
777 })
778
779 return s, nil
780}
781
782// Utility functions
783func getHostname() string {
784 hostname, err := os.Hostname()
785 if err != nil {
786 return "unknown"
787 }
788 return hostname
789}
790
791func getWorkingDir() string {
792 wd, err := os.Getwd()
793 if err != nil {
794 return "unknown"
795 }
796 return wd
797}
798
799// createTerminalSession creates a new terminal session with the given ID
800func (s *Server) createTerminalSession(sessionID string) (*terminalSession, error) {
801 // Start a new shell process
802 shellPath := getShellPath()
803 cmd := exec.Command(shellPath)
804
805 // Get working directory from the agent if possible
806 workDir := getWorkingDir()
807 cmd.Dir = workDir
808
809 // Set up environment
810 cmd.Env = append(os.Environ(), "TERM=xterm-256color")
811
812 // Start the command with a pty
813 ptmx, err := pty.Start(cmd)
814 if err != nil {
815 slog.Error("Failed to start pty", "error", err)
816 return nil, err
817 }
818
819 // Create the terminal session
820 session := &terminalSession{
821 pty: ptmx,
822 eventsClients: make(map[chan []byte]bool),
823 cmd: cmd,
824 }
825
826 // Start goroutine to read from pty and broadcast to all connected SSE clients
827 go s.readFromPtyAndBroadcast(sessionID, session)
828
829 return session, nil
830} // handleTerminalEvents handles SSE connections for terminal output
831func (s *Server) handleTerminalEvents(w http.ResponseWriter, r *http.Request, sessionID string) {
832 // Check if the session exists, if not, create it
833 s.ptyMutex.Lock()
834 session, exists := s.terminalSessions[sessionID]
835
836 if !exists {
837 // Create a new terminal session
838 var err error
839 session, err = s.createTerminalSession(sessionID)
840 if err != nil {
841 s.ptyMutex.Unlock()
842 http.Error(w, fmt.Sprintf("Failed to create terminal: %v", err), http.StatusInternalServerError)
843 return
844 }
845
846 // Store the new session
847 s.terminalSessions[sessionID] = session
848 }
849 s.ptyMutex.Unlock()
850
851 // Set headers for SSE
852 w.Header().Set("Content-Type", "text/event-stream")
853 w.Header().Set("Cache-Control", "no-cache")
854 w.Header().Set("Connection", "keep-alive")
855 w.Header().Set("Access-Control-Allow-Origin", "*")
856
857 // Create a channel for this client
858 events := make(chan []byte, 4096) // Buffer to prevent blocking
859
860 // Register this client's channel
861 session.eventsClientsMutex.Lock()
862 clientID := session.lastEventClientID + 1
863 session.lastEventClientID = clientID
864 session.eventsClients[events] = true
865 session.eventsClientsMutex.Unlock()
866
867 // When the client disconnects, remove their channel
868 defer func() {
869 session.eventsClientsMutex.Lock()
870 delete(session.eventsClients, events)
871 close(events)
872 session.eventsClientsMutex.Unlock()
873 }()
874
875 // Flush to send headers to client immediately
876 if f, ok := w.(http.Flusher); ok {
877 f.Flush()
878 }
879
880 // Send events to the client as they arrive
881 for {
882 select {
883 case <-r.Context().Done():
884 return
885 case data := <-events:
886 // Format as SSE with base64 encoding
887 fmt.Fprintf(w, "data: %s\n\n", base64.StdEncoding.EncodeToString(data))
888
889 // Flush the data immediately
890 if f, ok := w.(http.Flusher); ok {
891 f.Flush()
892 }
893 }
894 }
895}
896
897// handleTerminalInput processes input to the terminal
898func (s *Server) handleTerminalInput(w http.ResponseWriter, r *http.Request, sessionID string) {
899 // Check if the session exists
900 s.ptyMutex.Lock()
901 session, exists := s.terminalSessions[sessionID]
902 s.ptyMutex.Unlock()
903
904 if !exists {
905 http.Error(w, "Terminal session not found", http.StatusNotFound)
906 return
907 }
908
909 // Read the request body (terminal input or resize command)
910 body, err := io.ReadAll(r.Body)
911 if err != nil {
912 http.Error(w, "Failed to read request body", http.StatusBadRequest)
913 return
914 }
915
916 // Check if it's a resize message
917 if len(body) > 0 && body[0] == '{' {
918 var msg TerminalMessage
919 if err := json.Unmarshal(body, &msg); err == nil && msg.Type == "resize" {
920 if msg.Cols > 0 && msg.Rows > 0 {
921 pty.Setsize(session.pty, &pty.Winsize{
922 Cols: msg.Cols,
923 Rows: msg.Rows,
924 })
925
926 // Respond with success
927 w.WriteHeader(http.StatusOK)
928 return
929 }
930 }
931 }
932
933 // Regular terminal input
934 _, err = session.pty.Write(body)
935 if err != nil {
936 slog.Error("Failed to write to pty", "error", err)
937 http.Error(w, "Failed to write to terminal", http.StatusInternalServerError)
938 return
939 }
940
941 // Respond with success
942 w.WriteHeader(http.StatusOK)
943}
944
945// readFromPtyAndBroadcast reads output from the PTY and broadcasts it to all connected clients
946func (s *Server) readFromPtyAndBroadcast(sessionID string, session *terminalSession) {
947 buf := make([]byte, 4096)
948 defer func() {
949 // Clean up when done
950 s.ptyMutex.Lock()
951 delete(s.terminalSessions, sessionID)
952 s.ptyMutex.Unlock()
953
954 // Close the PTY
955 session.pty.Close()
956
957 // Ensure process is terminated
958 if session.cmd.Process != nil {
959 session.cmd.Process.Signal(syscall.SIGTERM)
960 time.Sleep(100 * time.Millisecond)
961 session.cmd.Process.Kill()
962 }
963
964 // Close all client channels
965 session.eventsClientsMutex.Lock()
966 for ch := range session.eventsClients {
967 delete(session.eventsClients, ch)
968 close(ch)
969 }
970 session.eventsClientsMutex.Unlock()
971 }()
972
973 for {
974 n, err := session.pty.Read(buf)
975 if err != nil {
976 if err != io.EOF {
977 slog.Error("Failed to read from pty", "error", err)
978 }
979 break
980 }
981
982 // Make a copy of the data for each client
983 data := make([]byte, n)
984 copy(data, buf[:n])
985
986 // Broadcast to all connected clients
987 session.eventsClientsMutex.Lock()
988 for ch := range session.eventsClients {
989 // Try to send, but don't block if channel is full
990 select {
991 case ch <- data:
992 default:
993 // Channel is full, drop the message for this client
994 }
995 }
996 session.eventsClientsMutex.Unlock()
997 }
998}
999
1000// getShellPath returns the path to the shell to use
1001func getShellPath() string {
1002 // Try to use the user's preferred shell
1003 shell := os.Getenv("SHELL")
1004 if shell != "" {
1005 return shell
1006 }
1007
1008 // Default to bash on Unix-like systems
1009 if _, err := os.Stat("/bin/bash"); err == nil {
1010 return "/bin/bash"
1011 }
1012
1013 // Fall back to sh
1014 return "/bin/sh"
1015}
1016
1017func initDebugMux() *http.ServeMux {
1018 mux := http.NewServeMux()
Philip Zeyliger8d8b7ac2025-05-21 09:57:23 -07001019 build := "unknown build"
1020 bi, ok := debug.ReadBuildInfo()
1021 if ok {
1022 build = fmt.Sprintf("%s@%v\n", bi.Path, bi.Main.Version)
1023 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001024 mux.HandleFunc("GET /debug/{$}", func(w http.ResponseWriter, r *http.Request) {
1025 w.Header().Set("Content-Type", "text/html; charset=utf-8")
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001026 // TODO: pid is not as useful as "outside pid"
Earl Lee2e463fb2025-04-17 11:22:22 -07001027 fmt.Fprintf(w, `<!doctype html>
1028 <html><head><title>sketch debug</title></head><body>
1029 <h1>sketch debug</h1>
Philip Zeyliger8d8b7ac2025-05-21 09:57:23 -07001030 pid %d<br>
1031 build %s<br>
Earl Lee2e463fb2025-04-17 11:22:22 -07001032 <ul>
1033 <li><a href="/debug/pprof/cmdline">pprof/cmdline</a></li>
1034 <li><a href="/debug/pprof/profile">pprof/profile</a></li>
1035 <li><a href="/debug/pprof/symbol">pprof/symbol</a></li>
1036 <li><a href="/debug/pprof/trace">pprof/trace</a></li>
1037 <li><a href="/debug/pprof/goroutine?debug=1">pprof/goroutine?debug=1</a></li>
1038 <li><a href="/debug/metrics">metrics</a></li>
1039 </ul>
1040 </body>
1041 </html>
Philip Zeyliger8d8b7ac2025-05-21 09:57:23 -07001042 `, os.Getpid(), build)
Earl Lee2e463fb2025-04-17 11:22:22 -07001043 })
1044 mux.HandleFunc("GET /debug/pprof/", pprof.Index)
1045 mux.HandleFunc("GET /debug/pprof/cmdline", pprof.Cmdline)
1046 mux.HandleFunc("GET /debug/pprof/profile", pprof.Profile)
1047 mux.HandleFunc("GET /debug/pprof/symbol", pprof.Symbol)
1048 mux.HandleFunc("GET /debug/pprof/trace", pprof.Trace)
1049 return mux
1050}
1051
1052// isValidGitSHA validates if a string looks like a valid git SHA hash.
1053// Git SHAs are hexadecimal strings of at least 4 characters but typically 7, 8, or 40 characters.
1054func isValidGitSHA(sha string) bool {
1055 // Git SHA must be a hexadecimal string with at least 4 characters
1056 if len(sha) < 4 || len(sha) > 40 {
1057 return false
1058 }
1059
1060 // Check if the string only contains hexadecimal characters
1061 for _, char := range sha {
1062 if !(char >= '0' && char <= '9') && !(char >= 'a' && char <= 'f') && !(char >= 'A' && char <= 'F') {
1063 return false
1064 }
1065 }
1066
1067 return true
1068}
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001069
1070// /stream?from=N endpoint for Server-Sent Events
1071func (s *Server) handleSSEStream(w http.ResponseWriter, r *http.Request) {
1072 w.Header().Set("Content-Type", "text/event-stream")
1073 w.Header().Set("Cache-Control", "no-cache")
1074 w.Header().Set("Connection", "keep-alive")
1075 w.Header().Set("Access-Control-Allow-Origin", "*")
1076
1077 // Extract the 'from' parameter
1078 fromParam := r.URL.Query().Get("from")
1079 var fromIndex int
1080 var err error
1081 if fromParam != "" {
1082 fromIndex, err = strconv.Atoi(fromParam)
1083 if err != nil {
1084 http.Error(w, "Invalid 'from' parameter", http.StatusBadRequest)
1085 return
1086 }
1087 }
1088
Philip Zeyligerb5739402025-06-02 07:04:34 -07001089 // Check if this client is waiting for end
1090 waitForEnd := r.URL.Query().Get("wait_for_end") == "true"
1091 if waitForEnd {
1092 s.endWaitGroup.Add(1)
1093 defer func() {
1094 if waitForEnd {
1095 s.endWaitGroup.Done()
1096 }
1097 }()
1098 }
1099
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001100 // Ensure 'from' is valid
1101 currentCount := s.agent.MessageCount()
1102 if fromIndex < 0 {
1103 fromIndex = 0
1104 } else if fromIndex > currentCount {
1105 fromIndex = currentCount
1106 }
1107
1108 // Send the current state immediately
1109 state := s.getState()
1110
1111 // Create JSON encoder
1112 encoder := json.NewEncoder(w)
1113
1114 // Send state as an event
1115 fmt.Fprintf(w, "event: state\n")
1116 fmt.Fprintf(w, "data: ")
1117 encoder.Encode(state)
1118 fmt.Fprintf(w, "\n\n")
1119
1120 if f, ok := w.(http.Flusher); ok {
1121 f.Flush()
1122 }
1123
1124 // Create a context for the SSE stream
1125 ctx := r.Context()
1126
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001127 // Setup heartbeat timer
1128 heartbeatTicker := time.NewTicker(45 * time.Second)
1129 defer heartbeatTicker.Stop()
1130
1131 // Create a channel for messages
1132 messageChan := make(chan *loop.AgentMessage, 10)
1133
Philip Zeyligereab12de2025-05-14 02:35:53 +00001134 // Create a channel for state transitions
1135 stateChan := make(chan *loop.StateTransition, 10)
1136
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001137 // Start a goroutine to read messages without blocking the heartbeat
1138 go func() {
Pokey Rule9d7f0cc2025-05-20 11:43:26 +01001139 // Create an iterator to receive new messages as they arrive
1140 iterator := s.agent.NewIterator(ctx, fromIndex) // Start from the requested index
1141 defer iterator.Close()
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001142 defer close(messageChan)
1143 for {
1144 // This can block, but it's in its own goroutine
1145 newMessage := iterator.Next()
1146 if newMessage == nil {
1147 // No message available (likely due to context cancellation)
1148 slog.InfoContext(ctx, "No more messages available, ending message stream")
1149 return
1150 }
1151
1152 select {
1153 case messageChan <- newMessage:
1154 // Message sent to channel
1155 case <-ctx.Done():
1156 // Context cancelled
1157 return
1158 }
1159 }
1160 }()
1161
Philip Zeyligereab12de2025-05-14 02:35:53 +00001162 // Start a goroutine to read state transitions
1163 go func() {
Pokey Rule9d7f0cc2025-05-20 11:43:26 +01001164 // Create an iterator to receive state transitions
1165 stateIterator := s.agent.NewStateTransitionIterator(ctx)
1166 defer stateIterator.Close()
Philip Zeyligereab12de2025-05-14 02:35:53 +00001167 defer close(stateChan)
1168 for {
1169 // This can block, but it's in its own goroutine
1170 newTransition := stateIterator.Next()
1171 if newTransition == nil {
1172 // No transition available (likely due to context cancellation)
1173 slog.InfoContext(ctx, "No more state transitions available, ending state stream")
1174 return
1175 }
1176
1177 select {
1178 case stateChan <- newTransition:
1179 // Transition sent to channel
1180 case <-ctx.Done():
1181 // Context cancelled
1182 return
1183 }
1184 }
1185 }()
1186
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001187 // Stay connected and stream real-time updates
1188 for {
1189 select {
1190 case <-heartbeatTicker.C:
1191 // Send heartbeat event
1192 fmt.Fprintf(w, "event: heartbeat\n")
1193 fmt.Fprintf(w, "data: %d\n\n", time.Now().Unix())
1194
1195 // Flush to send the heartbeat immediately
1196 if f, ok := w.(http.Flusher); ok {
1197 f.Flush()
1198 }
1199
1200 case <-ctx.Done():
1201 // Client disconnected
1202 slog.InfoContext(ctx, "Client disconnected from SSE stream")
1203 return
1204
Philip Zeyligereab12de2025-05-14 02:35:53 +00001205 case _, ok := <-stateChan:
1206 if !ok {
1207 // Channel closed
1208 slog.InfoContext(ctx, "State transition channel closed, ending SSE stream")
1209 return
1210 }
1211
1212 // Get updated state
1213 state = s.getState()
1214
1215 // Send updated state after the state transition
1216 fmt.Fprintf(w, "event: state\n")
1217 fmt.Fprintf(w, "data: ")
1218 encoder.Encode(state)
1219 fmt.Fprintf(w, "\n\n")
1220
1221 // Flush to send the state immediately
1222 if f, ok := w.(http.Flusher); ok {
1223 f.Flush()
1224 }
1225
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001226 case newMessage, ok := <-messageChan:
1227 if !ok {
1228 // Channel closed
1229 slog.InfoContext(ctx, "Message channel closed, ending SSE stream")
1230 return
1231 }
1232
1233 // Send the new message as an event
1234 fmt.Fprintf(w, "event: message\n")
1235 fmt.Fprintf(w, "data: ")
1236 encoder.Encode(newMessage)
1237 fmt.Fprintf(w, "\n\n")
1238
1239 // Get updated state
1240 state = s.getState()
1241
1242 // Send updated state after the message
1243 fmt.Fprintf(w, "event: state\n")
1244 fmt.Fprintf(w, "data: ")
1245 encoder.Encode(state)
1246 fmt.Fprintf(w, "\n\n")
1247
1248 // Flush to send the message and state immediately
1249 if f, ok := w.(http.Flusher); ok {
1250 f.Flush()
1251 }
1252 }
1253 }
1254}
1255
1256// Helper function to get the current state
1257func (s *Server) getState() State {
1258 serverMessageCount := s.agent.MessageCount()
1259 totalUsage := s.agent.TotalUsage()
1260
1261 return State{
Philip Zeyliger49edc922025-05-14 09:45:45 -07001262 StateVersion: 2,
1263 MessageCount: serverMessageCount,
1264 TotalUsage: &totalUsage,
1265 Hostname: s.hostname,
1266 WorkingDir: getWorkingDir(),
1267 // TODO: Rename this field to sketch-base?
1268 InitialCommit: s.agent.SketchGitBase(),
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001269 Slug: s.agent.Slug(),
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001270 BranchName: s.agent.BranchName(),
Philip Zeyligerbe7802a2025-06-04 20:15:25 +00001271 BranchPrefix: s.agent.BranchPrefix(),
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001272 OS: s.agent.OS(),
1273 OutsideHostname: s.agent.OutsideHostname(),
1274 InsideHostname: s.hostname,
1275 OutsideOS: s.agent.OutsideOS(),
1276 InsideOS: s.agent.OS(),
1277 OutsideWorkingDir: s.agent.OutsideWorkingDir(),
1278 InsideWorkingDir: getWorkingDir(),
1279 GitOrigin: s.agent.GitOrigin(),
1280 OutstandingLLMCalls: s.agent.OutstandingLLMCallCount(),
1281 OutstandingToolCalls: s.agent.OutstandingToolCalls(),
1282 SessionID: s.agent.SessionID(),
1283 SSHAvailable: s.sshAvailable,
1284 SSHError: s.sshError,
1285 InContainer: s.agent.IsInContainer(),
1286 FirstMessageIndex: s.agent.FirstMessageIndex(),
1287 AgentState: s.agent.CurrentStateName(),
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -07001288 TodoContent: s.agent.CurrentTodoContent(),
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001289 }
1290}
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001291
1292func (s *Server) handleGitRawDiff(w http.ResponseWriter, r *http.Request) {
1293 if r.Method != "GET" {
1294 w.WriteHeader(http.StatusMethodNotAllowed)
1295 return
1296 }
1297
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +00001298 // Get the git repository root directory from agent
1299 repoDir := s.agent.RepoRoot()
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001300
1301 // Parse query parameters
1302 query := r.URL.Query()
1303 commit := query.Get("commit")
1304 from := query.Get("from")
1305 to := query.Get("to")
1306
1307 // If commit is specified, use commit^ and commit as from and to
1308 if commit != "" {
1309 from = commit + "^"
1310 to = commit
1311 }
1312
1313 // Check if we have enough parameters
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001314 if from == "" {
1315 http.Error(w, "Missing required parameter: either 'commit' or at least 'from'", http.StatusBadRequest)
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001316 return
1317 }
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001318 // Note: 'to' can be empty to indicate working directory (unstaged changes)
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001319
1320 // Call the git_tools function
1321 diff, err := git_tools.GitRawDiff(repoDir, from, to)
1322 if err != nil {
1323 http.Error(w, fmt.Sprintf("Error getting git diff: %v", err), http.StatusInternalServerError)
1324 return
1325 }
1326
1327 // Return the result as JSON
1328 w.Header().Set("Content-Type", "application/json")
1329 if err := json.NewEncoder(w).Encode(diff); err != nil {
1330 http.Error(w, fmt.Sprintf("Error encoding response: %v", err), http.StatusInternalServerError)
1331 return
1332 }
1333}
1334
1335func (s *Server) handleGitShow(w http.ResponseWriter, r *http.Request) {
1336 if r.Method != "GET" {
1337 w.WriteHeader(http.StatusMethodNotAllowed)
1338 return
1339 }
1340
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +00001341 // Get the git repository root directory from agent
1342 repoDir := s.agent.RepoRoot()
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001343
1344 // Parse query parameters
1345 hash := r.URL.Query().Get("hash")
1346 if hash == "" {
1347 http.Error(w, "Missing required parameter: 'hash'", http.StatusBadRequest)
1348 return
1349 }
1350
1351 // Call the git_tools function
1352 show, err := git_tools.GitShow(repoDir, hash)
1353 if err != nil {
1354 http.Error(w, fmt.Sprintf("Error running git show: %v", err), http.StatusInternalServerError)
1355 return
1356 }
1357
1358 // Create a JSON response
1359 response := map[string]string{
1360 "hash": hash,
1361 "output": show,
1362 }
1363
1364 // Return the result as JSON
1365 w.Header().Set("Content-Type", "application/json")
1366 if err := json.NewEncoder(w).Encode(response); err != nil {
1367 http.Error(w, fmt.Sprintf("Error encoding response: %v", err), http.StatusInternalServerError)
1368 return
1369 }
1370}
1371
1372func (s *Server) handleGitRecentLog(w http.ResponseWriter, r *http.Request) {
1373 if r.Method != "GET" {
1374 w.WriteHeader(http.StatusMethodNotAllowed)
1375 return
1376 }
1377
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +00001378 // Get the git repository root directory and initial commit from agent
1379 repoDir := s.agent.RepoRoot()
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001380 initialCommit := s.agent.SketchGitBaseRef()
1381
1382 // Call the git_tools function
1383 log, err := git_tools.GitRecentLog(repoDir, initialCommit)
1384 if err != nil {
1385 http.Error(w, fmt.Sprintf("Error getting git log: %v", err), http.StatusInternalServerError)
1386 return
1387 }
1388
1389 // Return the result as JSON
1390 w.Header().Set("Content-Type", "application/json")
1391 if err := json.NewEncoder(w).Encode(log); err != nil {
1392 http.Error(w, fmt.Sprintf("Error encoding response: %v", err), http.StatusInternalServerError)
1393 return
1394 }
1395}
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001396
1397func (s *Server) handleGitCat(w http.ResponseWriter, r *http.Request) {
1398 if r.Method != "GET" {
1399 w.WriteHeader(http.StatusMethodNotAllowed)
1400 return
1401 }
1402
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +00001403 // Get the git repository root directory from agent
1404 repoDir := s.agent.RepoRoot()
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001405
1406 // Parse query parameters
1407 query := r.URL.Query()
1408 path := query.Get("path")
1409
1410 // Check if path is provided
1411 if path == "" {
1412 http.Error(w, "Missing required parameter: path", http.StatusBadRequest)
1413 return
1414 }
1415
1416 // Get file content using GitCat
1417 content, err := git_tools.GitCat(repoDir, path)
1418 if err != nil {
1419 http.Error(w, fmt.Sprintf("Error reading file: %v", err), http.StatusInternalServerError)
1420 return
1421 }
1422
1423 // Return the content as JSON for consistency with other endpoints
1424 w.Header().Set("Content-Type", "application/json")
1425 if err := json.NewEncoder(w).Encode(map[string]string{"output": content}); err != nil {
1426 http.Error(w, fmt.Sprintf("Error encoding response: %v", err), http.StatusInternalServerError)
1427 return
1428 }
1429}
1430
1431func (s *Server) handleGitSave(w http.ResponseWriter, r *http.Request) {
1432 if r.Method != "POST" {
1433 w.WriteHeader(http.StatusMethodNotAllowed)
1434 return
1435 }
1436
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +00001437 // Get the git repository root directory from agent
1438 repoDir := s.agent.RepoRoot()
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001439
1440 // Parse request body
1441 var requestBody struct {
1442 Path string `json:"path"`
1443 Content string `json:"content"`
1444 }
1445
1446 if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {
1447 http.Error(w, fmt.Sprintf("Error parsing request body: %v", err), http.StatusBadRequest)
1448 return
1449 }
1450 defer r.Body.Close()
1451
1452 // Check if path is provided
1453 if requestBody.Path == "" {
1454 http.Error(w, "Missing required parameter: path", http.StatusBadRequest)
1455 return
1456 }
1457
1458 // Save file content using GitSaveFile
1459 err := git_tools.GitSaveFile(repoDir, requestBody.Path, requestBody.Content)
1460 if err != nil {
1461 http.Error(w, fmt.Sprintf("Error saving file: %v", err), http.StatusInternalServerError)
1462 return
1463 }
1464
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001465 // Auto-commit the changes
1466 err = git_tools.AutoCommitDiffViewChanges(r.Context(), repoDir, requestBody.Path)
1467 if err != nil {
1468 http.Error(w, fmt.Sprintf("Error auto-committing changes: %v", err), http.StatusInternalServerError)
1469 return
1470 }
1471
1472 // Detect git changes to push and notify user
Philip Zeyliger9bca61e2025-05-22 12:40:06 -07001473 if err = s.agent.DetectGitChanges(r.Context()); err != nil {
1474 http.Error(w, fmt.Sprintf("Error detecting git changes: %v", err), http.StatusInternalServerError)
1475 return
1476 }
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001477
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001478 // Return simple success response
1479 w.WriteHeader(http.StatusOK)
1480 w.Write([]byte("ok"))
1481}