blob: b5fddb4dfdb298935bba88e9b3c83004bd74ae35 [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"`
philip.zeyliger8773e682025-06-11 21:36:21 -070098 TodoContent string `json:"todo_content,omitempty"` // Contains todo list JSON data
99 SkabandAddr string `json:"skaband_addr,omitempty"` // URL of the skaband server
100 LinkToGitHub bool `json:"link_to_github,omitempty"` // Enable GitHub branch linking in UI
101 SSHConnectionString string `json:"ssh_connection_string,omitempty"` // SSH connection string for container
Philip Zeyliger64f60462025-06-16 13:57:10 -0700102 DiffLinesAdded int `json:"diff_lines_added"` // Lines added from sketch-base to HEAD
103 DiffLinesRemoved int `json:"diff_lines_removed"` // Lines removed from sketch-base to HEAD
Sean McCulloughd9f13372025-04-21 15:08:49 -0700104}
105
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700106type InitRequest struct {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700107 // Passed to agent so that the URL it prints in the termui prompt is correct (when skaband is not used)
108 HostAddr string `json:"host_addr"`
109
110 // POST /init will start the SSH server with these configs
Sean McCullough7013e9e2025-05-14 02:03:58 +0000111 SSHAuthorizedKeys []byte `json:"ssh_authorized_keys"`
112 SSHServerIdentity []byte `json:"ssh_server_identity"`
113 SSHContainerCAKey []byte `json:"ssh_container_ca_key"`
114 SSHHostCertificate []byte `json:"ssh_host_certificate"`
115 SSHAvailable bool `json:"ssh_available"`
116 SSHError string `json:"ssh_error,omitempty"`
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700117}
118
Earl Lee2e463fb2025-04-17 11:22:22 -0700119// Server serves sketch HTTP. Server implements http.Handler.
120type Server struct {
121 mux *http.ServeMux
122 agent loop.CodingAgent
123 hostname string
124 logFile *os.File
125 // Mutex to protect terminalSessions
126 ptyMutex sync.Mutex
127 terminalSessions map[string]*terminalSession
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000128 sshAvailable bool
129 sshError string
Earl Lee2e463fb2025-04-17 11:22:22 -0700130}
131
132func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
133 s.mux.ServeHTTP(w, r)
134}
135
136// New creates a new HTTP server.
137func New(agent loop.CodingAgent, logFile *os.File) (*Server, error) {
138 s := &Server{
139 mux: http.NewServeMux(),
140 agent: agent,
141 hostname: getHostname(),
142 logFile: logFile,
143 terminalSessions: make(map[string]*terminalSession),
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000144 sshAvailable: false,
145 sshError: "",
Earl Lee2e463fb2025-04-17 11:22:22 -0700146 }
147
148 webBundle, err := webui.Build()
149 if err != nil {
150 return nil, fmt.Errorf("failed to build web bundle, did you run 'go generate sketch.dev/loop/...'?: %w", err)
151 }
152
Philip Zeyliger25f6ff12025-05-02 04:24:10 +0000153 s.mux.HandleFunc("/stream", s.handleSSEStream)
Philip Zeyligerd3ac1122025-05-14 02:54:18 +0000154
155 // Git tool endpoints
156 s.mux.HandleFunc("/git/rawdiff", s.handleGitRawDiff)
157 s.mux.HandleFunc("/git/show", s.handleGitShow)
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700158 s.mux.HandleFunc("/git/cat", s.handleGitCat)
159 s.mux.HandleFunc("/git/save", s.handleGitSave)
Philip Zeyligerd3ac1122025-05-14 02:54:18 +0000160 s.mux.HandleFunc("/git/recentlog", s.handleGitRecentLog)
161
Earl Lee2e463fb2025-04-17 11:22:22 -0700162 s.mux.HandleFunc("/diff", func(w http.ResponseWriter, r *http.Request) {
163 // Check if a specific commit hash was requested
164 commit := r.URL.Query().Get("commit")
165
166 // Get the diff, optionally for a specific commit
167 var diff string
168 var err error
169 if commit != "" {
170 // Validate the commit hash format
171 if !isValidGitSHA(commit) {
172 http.Error(w, fmt.Sprintf("Invalid git commit SHA format: %s", commit), http.StatusBadRequest)
173 return
174 }
175
176 diff, err = agent.Diff(&commit)
177 } else {
178 diff, err = agent.Diff(nil)
179 }
180
181 if err != nil {
182 http.Error(w, fmt.Sprintf("Error generating diff: %v", err), http.StatusInternalServerError)
183 return
184 }
185
186 w.Header().Set("Content-Type", "text/plain")
187 w.Write([]byte(diff))
188 })
189
190 // Handler for initialization called by host sketch binary when inside docker.
191 s.mux.HandleFunc("/init", func(w http.ResponseWriter, r *http.Request) {
192 defer func() {
193 if err := recover(); err != nil {
194 slog.ErrorContext(r.Context(), "/init panic", slog.Any("recovered_err", err))
195
196 // Return an error response to the client
197 http.Error(w, fmt.Sprintf("panic: %v\n", err), http.StatusInternalServerError)
198 }
199 }()
200
201 if r.Method != "POST" {
202 http.Error(w, "POST required", http.StatusBadRequest)
203 return
204 }
205
206 body, err := io.ReadAll(r.Body)
207 r.Body.Close()
208 if err != nil {
209 http.Error(w, "failed to read request body: "+err.Error(), http.StatusBadRequest)
210 return
211 }
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700212
213 m := &InitRequest{}
214 if err := json.Unmarshal(body, m); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700215 http.Error(w, "bad request body: "+err.Error(), http.StatusBadRequest)
216 return
217 }
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700218
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000219 // Store SSH availability info
220 s.sshAvailable = m.SSHAvailable
221 s.sshError = m.SSHError
222
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700223 // Start the SSH server if the init request included ssh keys.
224 if len(m.SSHAuthorizedKeys) > 0 && len(m.SSHServerIdentity) > 0 {
225 go func() {
226 ctx := context.Background()
Sean McCullough7013e9e2025-05-14 02:03:58 +0000227 if err := s.ServeSSH(ctx, m.SSHServerIdentity, m.SSHAuthorizedKeys, m.SSHContainerCAKey, m.SSHHostCertificate); err != nil {
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700228 slog.ErrorContext(r.Context(), "/init ServeSSH", slog.String("err", err.Error()))
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000229 // Update SSH error if server fails to start
230 s.sshAvailable = false
231 s.sshError = err.Error()
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700232 }
233 }()
234 }
235
Earl Lee2e463fb2025-04-17 11:22:22 -0700236 ini := loop.AgentInit{
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700237 InDocker: true,
238 HostAddr: m.HostAddr,
Earl Lee2e463fb2025-04-17 11:22:22 -0700239 }
240 if err := agent.Init(ini); err != nil {
241 http.Error(w, "init failed: "+err.Error(), http.StatusInternalServerError)
242 return
243 }
244 w.Header().Set("Content-Type", "application/json")
245 io.WriteString(w, "{}\n")
246 })
247
Sean McCullough138ec242025-06-02 22:42:06 +0000248 // Handler for /port-events - returns recent port change events
249 s.mux.HandleFunc("/port-events", func(w http.ResponseWriter, r *http.Request) {
250 if r.Method != http.MethodGet {
251 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
252 return
253 }
254
255 w.Header().Set("Content-Type", "application/json")
256
257 // Get the 'since' query parameter for filtering events
258 sinceParam := r.URL.Query().Get("since")
259 var events []loop.PortEvent
260
261 // Get port monitor from agent
262 portMonitor := agent.GetPortMonitor()
263 if portMonitor == nil {
264 // Return empty array if port monitor not available
265 events = []loop.PortEvent{}
266 } else if sinceParam != "" {
267 // Parse the since timestamp
268 sinceTime, err := time.Parse(time.RFC3339, sinceParam)
269 if err != nil {
270 http.Error(w, fmt.Sprintf("Invalid 'since' timestamp format: %v", err), http.StatusBadRequest)
271 return
272 }
273 events = portMonitor.GetRecentEvents(sinceTime)
274 } else {
275 // Return all recent events
276 events = portMonitor.GetAllRecentEvents()
277 }
278
279 // Encode and return the events
280 if err := json.NewEncoder(w).Encode(events); err != nil {
281 slog.ErrorContext(r.Context(), "Error encoding port events response", slog.Any("err", err))
282 http.Error(w, "Internal server error", http.StatusInternalServerError)
283 }
284 })
285
Earl Lee2e463fb2025-04-17 11:22:22 -0700286 // Handler for /messages?start=N&end=M (start/end are optional)
287 s.mux.HandleFunc("/messages", func(w http.ResponseWriter, r *http.Request) {
288 w.Header().Set("Content-Type", "application/json")
289
290 // Extract query parameters for range
291 var start, end int
292 var err error
293
294 currentCount := agent.MessageCount()
295
296 startParam := r.URL.Query().Get("start")
297 if startParam != "" {
298 start, err = strconv.Atoi(startParam)
299 if err != nil {
300 http.Error(w, "Invalid 'start' parameter", http.StatusBadRequest)
301 return
302 }
303 }
304
305 endParam := r.URL.Query().Get("end")
306 if endParam != "" {
307 end, err = strconv.Atoi(endParam)
308 if err != nil {
309 http.Error(w, "Invalid 'end' parameter", http.StatusBadRequest)
310 return
311 }
312 } else {
313 end = currentCount
314 }
315
316 if start < 0 || start > end || end > currentCount {
317 http.Error(w, fmt.Sprintf("Invalid range: start %d end %d currentCount %d", start, end, currentCount), http.StatusBadRequest)
318 return
319 }
320
321 start = max(0, start)
322 end = min(agent.MessageCount(), end)
323 messages := agent.Messages(start, end)
324
325 // Create a JSON encoder with indentation for pretty-printing
326 encoder := json.NewEncoder(w)
327 encoder.SetIndent("", " ") // Two spaces for each indentation level
328
329 err = encoder.Encode(messages)
330 if err != nil {
331 http.Error(w, err.Error(), http.StatusInternalServerError)
332 }
333 })
334
335 // Handler for /logs - displays the contents of the log file
336 s.mux.HandleFunc("/logs", func(w http.ResponseWriter, r *http.Request) {
337 if s.logFile == nil {
338 http.Error(w, "log file not set", http.StatusNotFound)
339 return
340 }
341 logContents, err := os.ReadFile(s.logFile.Name())
342 if err != nil {
343 http.Error(w, "error reading log file: "+err.Error(), http.StatusInternalServerError)
344 return
345 }
346 w.Header().Set("Content-Type", "text/html; charset=utf-8")
347 fmt.Fprintf(w, "<!DOCTYPE html>\n<html>\n<head>\n<title>Sketchy Log File</title>\n</head>\n<body>\n")
348 fmt.Fprintf(w, "<pre>%s</pre>\n", html.EscapeString(string(logContents)))
349 fmt.Fprintf(w, "</body>\n</html>")
350 })
351
352 // Handler for /download - downloads both messages and status as a JSON file
353 s.mux.HandleFunc("/download", func(w http.ResponseWriter, r *http.Request) {
354 // Set headers for file download
355 w.Header().Set("Content-Type", "application/octet-stream")
356
357 // Generate filename with format: sketch-YYYYMMDD-HHMMSS.json
358 timestamp := time.Now().Format("20060102-150405")
359 filename := fmt.Sprintf("sketch-%s.json", timestamp)
360
361 w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
362
363 // Get all messages
364 messageCount := agent.MessageCount()
365 messages := agent.Messages(0, messageCount)
366
367 // Get status information (usage and other metadata)
368 totalUsage := agent.TotalUsage()
369 hostname := getHostname()
370 workingDir := getWorkingDir()
371
372 // Create a combined structure with all information
373 downloadData := struct {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700374 Messages []loop.AgentMessage `json:"messages"`
375 MessageCount int `json:"message_count"`
376 TotalUsage conversation.CumulativeUsage `json:"total_usage"`
377 Hostname string `json:"hostname"`
378 WorkingDir string `json:"working_dir"`
379 DownloadTime string `json:"download_time"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700380 }{
381 Messages: messages,
382 MessageCount: messageCount,
383 TotalUsage: totalUsage,
384 Hostname: hostname,
385 WorkingDir: workingDir,
386 DownloadTime: time.Now().Format(time.RFC3339),
387 }
388
389 // Marshal the JSON with indentation for better readability
390 jsonData, err := json.MarshalIndent(downloadData, "", " ")
391 if err != nil {
392 http.Error(w, err.Error(), http.StatusInternalServerError)
393 return
394 }
395 w.Write(jsonData)
396 })
397
398 // The latter doesn't return until the number of messages has changed (from seen
399 // or from when this was called.)
400 s.mux.HandleFunc("/state", func(w http.ResponseWriter, r *http.Request) {
401 pollParam := r.URL.Query().Get("poll")
402 seenParam := r.URL.Query().Get("seen")
403
404 // Get the client's current message count (if provided)
405 clientMessageCount := -1
406 var err error
407 if seenParam != "" {
408 clientMessageCount, err = strconv.Atoi(seenParam)
409 if err != nil {
410 http.Error(w, "Invalid 'seen' parameter", http.StatusBadRequest)
411 return
412 }
413 }
414
415 serverMessageCount := agent.MessageCount()
416
417 // Let lazy clients not have to specify this.
418 if clientMessageCount == -1 {
419 clientMessageCount = serverMessageCount
420 }
421
422 if pollParam == "true" {
423 ch := make(chan string)
424 go func() {
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700425 it := agent.NewIterator(r.Context(), clientMessageCount)
426 it.Next()
Earl Lee2e463fb2025-04-17 11:22:22 -0700427 close(ch)
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700428 it.Close()
Earl Lee2e463fb2025-04-17 11:22:22 -0700429 }()
430 select {
431 case <-r.Context().Done():
432 slog.DebugContext(r.Context(), "abandoned poll request")
433 return
434 case <-time.After(90 * time.Second):
435 // Let the user call /state again to get the latest to limit how long our long polls hang out.
436 slog.DebugContext(r.Context(), "longish poll request")
437 break
438 case <-ch:
439 break
440 }
441 }
442
Earl Lee2e463fb2025-04-17 11:22:22 -0700443 w.Header().Set("Content-Type", "application/json")
444
Philip Zeyliger25f6ff12025-05-02 04:24:10 +0000445 // Use the shared getState function
446 state := s.getState()
Earl Lee2e463fb2025-04-17 11:22:22 -0700447
448 // Create a JSON encoder with indentation for pretty-printing
449 encoder := json.NewEncoder(w)
450 encoder.SetIndent("", " ") // Two spaces for each indentation level
451
452 err = encoder.Encode(state)
453 if err != nil {
454 http.Error(w, err.Error(), http.StatusInternalServerError)
455 }
456 })
457
Philip Zeyliger176de792025-04-21 12:25:18 -0700458 s.mux.Handle("/static/", http.StripPrefix("/static/", gzhandler.New(webBundle)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700459
460 // Terminal WebSocket handler
461 // Terminal endpoints - predefined terminals 1-9
462 // TODO: The UI doesn't actually know how to use terminals 2-9!
463 s.mux.HandleFunc("/terminal/events/", func(w http.ResponseWriter, r *http.Request) {
464 if r.Method != http.MethodGet {
465 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
466 return
467 }
468 pathParts := strings.Split(r.URL.Path, "/")
469 if len(pathParts) < 4 {
470 http.Error(w, "Invalid terminal ID", http.StatusBadRequest)
471 return
472 }
473
474 sessionID := pathParts[3]
475 // Validate that the terminal ID is between 1-9
476 if len(sessionID) != 1 || sessionID[0] < '1' || sessionID[0] > '9' {
477 http.Error(w, "Terminal ID must be between 1 and 9", http.StatusBadRequest)
478 return
479 }
480
481 s.handleTerminalEvents(w, r, sessionID)
482 })
483
484 s.mux.HandleFunc("/terminal/input/", func(w http.ResponseWriter, r *http.Request) {
485 if r.Method != http.MethodPost {
486 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
487 return
488 }
489 pathParts := strings.Split(r.URL.Path, "/")
490 if len(pathParts) < 4 {
491 http.Error(w, "Invalid terminal ID", http.StatusBadRequest)
492 return
493 }
494 sessionID := pathParts[3]
495 s.handleTerminalInput(w, r, sessionID)
496 })
497
Philip Zeyligere08c7ff2025-06-06 13:22:12 -0700498 // Handler for interface selection via URL parameters (?m for mobile, ?d for desktop, auto-detect by default)
Earl Lee2e463fb2025-04-17 11:22:22 -0700499 s.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
Philip Zeyligere08c7ff2025-06-06 13:22:12 -0700500 // Check URL parameters for interface selection
501 queryParams := r.URL.Query()
502
503 // Check if mobile interface is requested (?m parameter)
504 if queryParams.Has("m") {
505 // Serve the mobile-app-shell.html file
506 data, err := fs.ReadFile(webBundle, "mobile-app-shell.html")
507 if err != nil {
508 http.Error(w, "Mobile interface not found", http.StatusNotFound)
509 return
510 }
511 w.Header().Set("Content-Type", "text/html")
512 w.Write(data)
513 return
514 }
515
516 // Check if desktop interface is explicitly requested (?d parameter)
517 // or serve desktop by default
Sean McCullough86b56862025-04-18 13:04:03 -0700518 data, err := fs.ReadFile(webBundle, "sketch-app-shell.html")
Earl Lee2e463fb2025-04-17 11:22:22 -0700519 if err != nil {
520 http.Error(w, "File not found", http.StatusNotFound)
521 return
522 }
523 w.Header().Set("Content-Type", "text/html")
524 w.Write(data)
525 })
526
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700527 // Handler for /commit-description - returns the description of a git commit
528 s.mux.HandleFunc("/commit-description", func(w http.ResponseWriter, r *http.Request) {
529 if r.Method != http.MethodGet {
530 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
531 return
532 }
533
534 // Get the revision parameter
535 revision := r.URL.Query().Get("revision")
536 if revision == "" {
537 http.Error(w, "Missing revision parameter", http.StatusBadRequest)
538 return
539 }
540
541 // Run git command to get commit description
542 cmd := exec.Command("git", "log", "--oneline", "--decorate", "-n", "1", revision)
543 // Use the working directory from the agent
544 cmd.Dir = s.agent.WorkingDir()
545
546 output, err := cmd.CombinedOutput()
547 if err != nil {
548 http.Error(w, "Failed to get commit description: "+err.Error(), http.StatusInternalServerError)
549 return
550 }
551
552 // Prepare the response
553 resp := map[string]string{
554 "description": strings.TrimSpace(string(output)),
555 }
556
557 w.Header().Set("Content-Type", "application/json")
558 if err := json.NewEncoder(w).Encode(resp); err != nil {
559 slog.ErrorContext(r.Context(), "Error encoding commit description response", slog.Any("err", err))
560 }
561 })
562
Philip Zeyliger33d282f2025-05-03 04:01:54 +0000563 // Handler for /screenshot/{id} - serves screenshot images
564 s.mux.HandleFunc("/screenshot/", func(w http.ResponseWriter, r *http.Request) {
565 if r.Method != http.MethodGet {
566 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
567 return
568 }
569
570 // Extract the screenshot ID from the path
571 pathParts := strings.Split(r.URL.Path, "/")
572 if len(pathParts) < 3 {
573 http.Error(w, "Invalid screenshot ID", http.StatusBadRequest)
574 return
575 }
576
577 screenshotID := pathParts[2]
578
579 // Validate the ID format (prevent directory traversal)
580 if strings.Contains(screenshotID, "/") || strings.Contains(screenshotID, "\\") {
581 http.Error(w, "Invalid screenshot ID format", http.StatusBadRequest)
582 return
583 }
584
585 // Get the screenshot file path
586 filePath := browse.GetScreenshotPath(screenshotID)
587
588 // Check if the file exists
589 if _, err := os.Stat(filePath); os.IsNotExist(err) {
590 http.Error(w, "Screenshot not found", http.StatusNotFound)
591 return
592 }
593
594 // Serve the file
595 w.Header().Set("Content-Type", "image/png")
596 w.Header().Set("Cache-Control", "max-age=3600") // Cache for an hour
597 http.ServeFile(w, r, filePath)
598 })
599
Earl Lee2e463fb2025-04-17 11:22:22 -0700600 // Handler for POST /chat
601 s.mux.HandleFunc("/chat", func(w http.ResponseWriter, r *http.Request) {
602 if r.Method != http.MethodPost {
603 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
604 return
605 }
606
607 // Parse the request body
608 var requestBody struct {
609 Message string `json:"message"`
610 }
611
612 decoder := json.NewDecoder(r.Body)
613 if err := decoder.Decode(&requestBody); err != nil {
614 http.Error(w, "Invalid request body: "+err.Error(), http.StatusBadRequest)
615 return
616 }
617 defer r.Body.Close()
618
619 if requestBody.Message == "" {
620 http.Error(w, "Message cannot be empty", http.StatusBadRequest)
621 return
622 }
623
624 agent.UserMessage(r.Context(), requestBody.Message)
625
626 w.WriteHeader(http.StatusOK)
627 })
628
Philip Zeyligerf84e88c2025-05-14 23:19:01 +0000629 // Handler for POST /upload - uploads a file to /tmp
630 s.mux.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
631 if r.Method != http.MethodPost {
632 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
633 return
634 }
635
636 // Limit to 10MB file size
637 r.Body = http.MaxBytesReader(w, r.Body, 10*1024*1024)
638
639 // Parse the multipart form
640 if err := r.ParseMultipartForm(10 * 1024 * 1024); err != nil {
641 http.Error(w, "Failed to parse form: "+err.Error(), http.StatusBadRequest)
642 return
643 }
644
645 // Get the file from the multipart form
646 file, handler, err := r.FormFile("file")
647 if err != nil {
648 http.Error(w, "Failed to get uploaded file: "+err.Error(), http.StatusBadRequest)
649 return
650 }
651 defer file.Close()
652
653 // Generate a unique ID (8 random bytes converted to 16 hex chars)
654 randBytes := make([]byte, 8)
655 if _, err := rand.Read(randBytes); err != nil {
656 http.Error(w, "Failed to generate random filename: "+err.Error(), http.StatusInternalServerError)
657 return
658 }
659
660 // Get file extension from the original filename
661 ext := filepath.Ext(handler.Filename)
662
663 // Create a unique filename in the /tmp directory
664 filename := fmt.Sprintf("/tmp/sketch_file_%s%s", hex.EncodeToString(randBytes), ext)
665
666 // Create the destination file
667 destFile, err := os.Create(filename)
668 if err != nil {
669 http.Error(w, "Failed to create destination file: "+err.Error(), http.StatusInternalServerError)
670 return
671 }
672 defer destFile.Close()
673
674 // Copy the file contents to the destination file
675 if _, err := io.Copy(destFile, file); err != nil {
676 http.Error(w, "Failed to save file: "+err.Error(), http.StatusInternalServerError)
677 return
678 }
679
680 // Return the path to the saved file
681 w.Header().Set("Content-Type", "application/json")
682 json.NewEncoder(w).Encode(map[string]string{"path": filename})
683 })
684
Earl Lee2e463fb2025-04-17 11:22:22 -0700685 // Handler for /cancel - cancels the current inner loop in progress
686 s.mux.HandleFunc("/cancel", func(w http.ResponseWriter, r *http.Request) {
687 if r.Method != http.MethodPost {
688 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
689 return
690 }
691
692 // Parse the request body (optional)
693 var requestBody struct {
694 Reason string `json:"reason"`
695 ToolCallID string `json:"tool_call_id"`
696 }
697
698 decoder := json.NewDecoder(r.Body)
699 if err := decoder.Decode(&requestBody); err != nil && err != io.EOF {
700 http.Error(w, "Invalid request body: "+err.Error(), http.StatusBadRequest)
701 return
702 }
703 defer r.Body.Close()
704
705 cancelReason := "user requested cancellation"
706 if requestBody.Reason != "" {
707 cancelReason = requestBody.Reason
708 }
709
710 if requestBody.ToolCallID != "" {
711 err := agent.CancelToolUse(requestBody.ToolCallID, fmt.Errorf("%s", cancelReason))
712 if err != nil {
713 http.Error(w, err.Error(), http.StatusBadRequest)
714 return
715 }
716 // Return a success response
717 w.Header().Set("Content-Type", "application/json")
718 json.NewEncoder(w).Encode(map[string]string{
719 "status": "cancelled",
720 "too_use_id": requestBody.ToolCallID,
Philip Zeyliger8d50d7b2025-04-23 13:12:40 -0700721 "reason": cancelReason,
722 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700723 return
724 }
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000725 // Call the CancelTurn method
726 agent.CancelTurn(fmt.Errorf("%s", cancelReason))
Earl Lee2e463fb2025-04-17 11:22:22 -0700727 // Return a success response
728 w.Header().Set("Content-Type", "application/json")
729 json.NewEncoder(w).Encode(map[string]string{"status": "cancelled", "reason": cancelReason})
730 })
731
Pokey Rule397871d2025-05-19 15:02:45 +0100732 // Handler for /end - shuts down the inner sketch process
733 s.mux.HandleFunc("/end", func(w http.ResponseWriter, r *http.Request) {
734 if r.Method != http.MethodPost {
735 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
736 return
737 }
738
739 // Parse the request body (optional)
740 var requestBody struct {
Philip Zeyligerb5739402025-06-02 07:04:34 -0700741 Reason string `json:"reason"`
742 Happy *bool `json:"happy,omitempty"`
743 Comment string `json:"comment,omitempty"`
Pokey Rule397871d2025-05-19 15:02:45 +0100744 }
745
746 decoder := json.NewDecoder(r.Body)
747 if err := decoder.Decode(&requestBody); err != nil && err != io.EOF {
748 http.Error(w, "Invalid request body: "+err.Error(), http.StatusBadRequest)
749 return
750 }
751 defer r.Body.Close()
752
753 endReason := "user requested end of session"
754 if requestBody.Reason != "" {
755 endReason = requestBody.Reason
756 }
757
758 // Send success response before exiting
759 w.Header().Set("Content-Type", "application/json")
760 json.NewEncoder(w).Encode(map[string]string{"status": "ending", "reason": endReason})
761 if f, ok := w.(http.Flusher); ok {
762 f.Flush()
763 }
764
765 // Log that we're shutting down
766 slog.Info("Ending session", "reason", endReason)
767
philip.zeyliger28e39ac2025-06-16 22:04:35 +0000768 // Give a brief moment for the response to be sent before exiting
Pokey Rule397871d2025-05-19 15:02:45 +0100769 go func() {
philip.zeyliger28e39ac2025-06-16 22:04:35 +0000770 time.Sleep(100 * time.Millisecond)
Pokey Rule397871d2025-05-19 15:02:45 +0100771 os.Exit(0)
772 }()
773 })
774
Earl Lee2e463fb2025-04-17 11:22:22 -0700775 debugMux := initDebugMux()
776 s.mux.HandleFunc("/debug/", func(w http.ResponseWriter, r *http.Request) {
777 debugMux.ServeHTTP(w, r)
778 })
779
780 return s, nil
781}
782
783// Utility functions
784func getHostname() string {
785 hostname, err := os.Hostname()
786 if err != nil {
787 return "unknown"
788 }
789 return hostname
790}
791
792func getWorkingDir() string {
793 wd, err := os.Getwd()
794 if err != nil {
795 return "unknown"
796 }
797 return wd
798}
799
800// createTerminalSession creates a new terminal session with the given ID
801func (s *Server) createTerminalSession(sessionID string) (*terminalSession, error) {
802 // Start a new shell process
803 shellPath := getShellPath()
804 cmd := exec.Command(shellPath)
805
806 // Get working directory from the agent if possible
807 workDir := getWorkingDir()
808 cmd.Dir = workDir
809
810 // Set up environment
811 cmd.Env = append(os.Environ(), "TERM=xterm-256color")
812
813 // Start the command with a pty
814 ptmx, err := pty.Start(cmd)
815 if err != nil {
816 slog.Error("Failed to start pty", "error", err)
817 return nil, err
818 }
819
820 // Create the terminal session
821 session := &terminalSession{
822 pty: ptmx,
823 eventsClients: make(map[chan []byte]bool),
824 cmd: cmd,
825 }
826
827 // Start goroutine to read from pty and broadcast to all connected SSE clients
828 go s.readFromPtyAndBroadcast(sessionID, session)
829
830 return session, nil
831} // handleTerminalEvents handles SSE connections for terminal output
832func (s *Server) handleTerminalEvents(w http.ResponseWriter, r *http.Request, sessionID string) {
833 // Check if the session exists, if not, create it
834 s.ptyMutex.Lock()
835 session, exists := s.terminalSessions[sessionID]
836
837 if !exists {
838 // Create a new terminal session
839 var err error
840 session, err = s.createTerminalSession(sessionID)
841 if err != nil {
842 s.ptyMutex.Unlock()
843 http.Error(w, fmt.Sprintf("Failed to create terminal: %v", err), http.StatusInternalServerError)
844 return
845 }
846
847 // Store the new session
848 s.terminalSessions[sessionID] = session
849 }
850 s.ptyMutex.Unlock()
851
852 // Set headers for SSE
853 w.Header().Set("Content-Type", "text/event-stream")
854 w.Header().Set("Cache-Control", "no-cache")
855 w.Header().Set("Connection", "keep-alive")
856 w.Header().Set("Access-Control-Allow-Origin", "*")
857
858 // Create a channel for this client
859 events := make(chan []byte, 4096) // Buffer to prevent blocking
860
861 // Register this client's channel
862 session.eventsClientsMutex.Lock()
863 clientID := session.lastEventClientID + 1
864 session.lastEventClientID = clientID
865 session.eventsClients[events] = true
866 session.eventsClientsMutex.Unlock()
867
868 // When the client disconnects, remove their channel
869 defer func() {
870 session.eventsClientsMutex.Lock()
871 delete(session.eventsClients, events)
872 close(events)
873 session.eventsClientsMutex.Unlock()
874 }()
875
876 // Flush to send headers to client immediately
877 if f, ok := w.(http.Flusher); ok {
878 f.Flush()
879 }
880
881 // Send events to the client as they arrive
882 for {
883 select {
884 case <-r.Context().Done():
885 return
886 case data := <-events:
887 // Format as SSE with base64 encoding
888 fmt.Fprintf(w, "data: %s\n\n", base64.StdEncoding.EncodeToString(data))
889
890 // Flush the data immediately
891 if f, ok := w.(http.Flusher); ok {
892 f.Flush()
893 }
894 }
895 }
896}
897
898// handleTerminalInput processes input to the terminal
899func (s *Server) handleTerminalInput(w http.ResponseWriter, r *http.Request, sessionID string) {
900 // Check if the session exists
901 s.ptyMutex.Lock()
902 session, exists := s.terminalSessions[sessionID]
903 s.ptyMutex.Unlock()
904
905 if !exists {
906 http.Error(w, "Terminal session not found", http.StatusNotFound)
907 return
908 }
909
910 // Read the request body (terminal input or resize command)
911 body, err := io.ReadAll(r.Body)
912 if err != nil {
913 http.Error(w, "Failed to read request body", http.StatusBadRequest)
914 return
915 }
916
917 // Check if it's a resize message
918 if len(body) > 0 && body[0] == '{' {
919 var msg TerminalMessage
920 if err := json.Unmarshal(body, &msg); err == nil && msg.Type == "resize" {
921 if msg.Cols > 0 && msg.Rows > 0 {
922 pty.Setsize(session.pty, &pty.Winsize{
923 Cols: msg.Cols,
924 Rows: msg.Rows,
925 })
926
927 // Respond with success
928 w.WriteHeader(http.StatusOK)
929 return
930 }
931 }
932 }
933
934 // Regular terminal input
935 _, err = session.pty.Write(body)
936 if err != nil {
937 slog.Error("Failed to write to pty", "error", err)
938 http.Error(w, "Failed to write to terminal", http.StatusInternalServerError)
939 return
940 }
941
942 // Respond with success
943 w.WriteHeader(http.StatusOK)
944}
945
946// readFromPtyAndBroadcast reads output from the PTY and broadcasts it to all connected clients
947func (s *Server) readFromPtyAndBroadcast(sessionID string, session *terminalSession) {
948 buf := make([]byte, 4096)
949 defer func() {
950 // Clean up when done
951 s.ptyMutex.Lock()
952 delete(s.terminalSessions, sessionID)
953 s.ptyMutex.Unlock()
954
955 // Close the PTY
956 session.pty.Close()
957
958 // Ensure process is terminated
959 if session.cmd.Process != nil {
960 session.cmd.Process.Signal(syscall.SIGTERM)
961 time.Sleep(100 * time.Millisecond)
962 session.cmd.Process.Kill()
963 }
964
965 // Close all client channels
966 session.eventsClientsMutex.Lock()
967 for ch := range session.eventsClients {
968 delete(session.eventsClients, ch)
969 close(ch)
970 }
971 session.eventsClientsMutex.Unlock()
972 }()
973
974 for {
975 n, err := session.pty.Read(buf)
976 if err != nil {
977 if err != io.EOF {
978 slog.Error("Failed to read from pty", "error", err)
979 }
980 break
981 }
982
983 // Make a copy of the data for each client
984 data := make([]byte, n)
985 copy(data, buf[:n])
986
987 // Broadcast to all connected clients
988 session.eventsClientsMutex.Lock()
989 for ch := range session.eventsClients {
990 // Try to send, but don't block if channel is full
991 select {
992 case ch <- data:
993 default:
994 // Channel is full, drop the message for this client
995 }
996 }
997 session.eventsClientsMutex.Unlock()
998 }
999}
1000
1001// getShellPath returns the path to the shell to use
1002func getShellPath() string {
1003 // Try to use the user's preferred shell
1004 shell := os.Getenv("SHELL")
1005 if shell != "" {
1006 return shell
1007 }
1008
1009 // Default to bash on Unix-like systems
1010 if _, err := os.Stat("/bin/bash"); err == nil {
1011 return "/bin/bash"
1012 }
1013
1014 // Fall back to sh
1015 return "/bin/sh"
1016}
1017
1018func initDebugMux() *http.ServeMux {
1019 mux := http.NewServeMux()
Philip Zeyliger8d8b7ac2025-05-21 09:57:23 -07001020 build := "unknown build"
1021 bi, ok := debug.ReadBuildInfo()
1022 if ok {
1023 build = fmt.Sprintf("%s@%v\n", bi.Path, bi.Main.Version)
1024 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001025 mux.HandleFunc("GET /debug/{$}", func(w http.ResponseWriter, r *http.Request) {
1026 w.Header().Set("Content-Type", "text/html; charset=utf-8")
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001027 // TODO: pid is not as useful as "outside pid"
Earl Lee2e463fb2025-04-17 11:22:22 -07001028 fmt.Fprintf(w, `<!doctype html>
1029 <html><head><title>sketch debug</title></head><body>
1030 <h1>sketch debug</h1>
Philip Zeyliger8d8b7ac2025-05-21 09:57:23 -07001031 pid %d<br>
1032 build %s<br>
Earl Lee2e463fb2025-04-17 11:22:22 -07001033 <ul>
1034 <li><a href="/debug/pprof/cmdline">pprof/cmdline</a></li>
1035 <li><a href="/debug/pprof/profile">pprof/profile</a></li>
1036 <li><a href="/debug/pprof/symbol">pprof/symbol</a></li>
1037 <li><a href="/debug/pprof/trace">pprof/trace</a></li>
1038 <li><a href="/debug/pprof/goroutine?debug=1">pprof/goroutine?debug=1</a></li>
1039 <li><a href="/debug/metrics">metrics</a></li>
1040 </ul>
1041 </body>
1042 </html>
Philip Zeyliger8d8b7ac2025-05-21 09:57:23 -07001043 `, os.Getpid(), build)
Earl Lee2e463fb2025-04-17 11:22:22 -07001044 })
1045 mux.HandleFunc("GET /debug/pprof/", pprof.Index)
1046 mux.HandleFunc("GET /debug/pprof/cmdline", pprof.Cmdline)
1047 mux.HandleFunc("GET /debug/pprof/profile", pprof.Profile)
1048 mux.HandleFunc("GET /debug/pprof/symbol", pprof.Symbol)
1049 mux.HandleFunc("GET /debug/pprof/trace", pprof.Trace)
1050 return mux
1051}
1052
1053// isValidGitSHA validates if a string looks like a valid git SHA hash.
1054// Git SHAs are hexadecimal strings of at least 4 characters but typically 7, 8, or 40 characters.
1055func isValidGitSHA(sha string) bool {
1056 // Git SHA must be a hexadecimal string with at least 4 characters
1057 if len(sha) < 4 || len(sha) > 40 {
1058 return false
1059 }
1060
1061 // Check if the string only contains hexadecimal characters
1062 for _, char := range sha {
1063 if !(char >= '0' && char <= '9') && !(char >= 'a' && char <= 'f') && !(char >= 'A' && char <= 'F') {
1064 return false
1065 }
1066 }
1067
1068 return true
1069}
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001070
1071// /stream?from=N endpoint for Server-Sent Events
1072func (s *Server) handleSSEStream(w http.ResponseWriter, r *http.Request) {
1073 w.Header().Set("Content-Type", "text/event-stream")
1074 w.Header().Set("Cache-Control", "no-cache")
1075 w.Header().Set("Connection", "keep-alive")
1076 w.Header().Set("Access-Control-Allow-Origin", "*")
1077
1078 // Extract the 'from' parameter
1079 fromParam := r.URL.Query().Get("from")
1080 var fromIndex int
1081 var err error
1082 if fromParam != "" {
1083 fromIndex, err = strconv.Atoi(fromParam)
1084 if err != nil {
1085 http.Error(w, "Invalid 'from' parameter", http.StatusBadRequest)
1086 return
1087 }
1088 }
1089
1090 // Ensure 'from' is valid
1091 currentCount := s.agent.MessageCount()
1092 if fromIndex < 0 {
1093 fromIndex = 0
1094 } else if fromIndex > currentCount {
1095 fromIndex = currentCount
1096 }
1097
1098 // Send the current state immediately
1099 state := s.getState()
1100
1101 // Create JSON encoder
1102 encoder := json.NewEncoder(w)
1103
1104 // Send state as an event
1105 fmt.Fprintf(w, "event: state\n")
1106 fmt.Fprintf(w, "data: ")
1107 encoder.Encode(state)
1108 fmt.Fprintf(w, "\n\n")
1109
1110 if f, ok := w.(http.Flusher); ok {
1111 f.Flush()
1112 }
1113
1114 // Create a context for the SSE stream
1115 ctx := r.Context()
1116
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001117 // Setup heartbeat timer
1118 heartbeatTicker := time.NewTicker(45 * time.Second)
1119 defer heartbeatTicker.Stop()
1120
1121 // Create a channel for messages
1122 messageChan := make(chan *loop.AgentMessage, 10)
1123
Philip Zeyligereab12de2025-05-14 02:35:53 +00001124 // Create a channel for state transitions
1125 stateChan := make(chan *loop.StateTransition, 10)
1126
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001127 // Start a goroutine to read messages without blocking the heartbeat
1128 go func() {
Pokey Rule9d7f0cc2025-05-20 11:43:26 +01001129 // Create an iterator to receive new messages as they arrive
1130 iterator := s.agent.NewIterator(ctx, fromIndex) // Start from the requested index
1131 defer iterator.Close()
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001132 defer close(messageChan)
1133 for {
1134 // This can block, but it's in its own goroutine
1135 newMessage := iterator.Next()
1136 if newMessage == nil {
1137 // No message available (likely due to context cancellation)
1138 slog.InfoContext(ctx, "No more messages available, ending message stream")
1139 return
1140 }
1141
1142 select {
1143 case messageChan <- newMessage:
1144 // Message sent to channel
1145 case <-ctx.Done():
1146 // Context cancelled
1147 return
1148 }
1149 }
1150 }()
1151
Philip Zeyligereab12de2025-05-14 02:35:53 +00001152 // Start a goroutine to read state transitions
1153 go func() {
Pokey Rule9d7f0cc2025-05-20 11:43:26 +01001154 // Create an iterator to receive state transitions
1155 stateIterator := s.agent.NewStateTransitionIterator(ctx)
1156 defer stateIterator.Close()
Philip Zeyligereab12de2025-05-14 02:35:53 +00001157 defer close(stateChan)
1158 for {
1159 // This can block, but it's in its own goroutine
1160 newTransition := stateIterator.Next()
1161 if newTransition == nil {
1162 // No transition available (likely due to context cancellation)
1163 slog.InfoContext(ctx, "No more state transitions available, ending state stream")
1164 return
1165 }
1166
1167 select {
1168 case stateChan <- newTransition:
1169 // Transition sent to channel
1170 case <-ctx.Done():
1171 // Context cancelled
1172 return
1173 }
1174 }
1175 }()
1176
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001177 // Stay connected and stream real-time updates
1178 for {
1179 select {
1180 case <-heartbeatTicker.C:
1181 // Send heartbeat event
1182 fmt.Fprintf(w, "event: heartbeat\n")
1183 fmt.Fprintf(w, "data: %d\n\n", time.Now().Unix())
1184
1185 // Flush to send the heartbeat immediately
1186 if f, ok := w.(http.Flusher); ok {
1187 f.Flush()
1188 }
1189
1190 case <-ctx.Done():
1191 // Client disconnected
1192 slog.InfoContext(ctx, "Client disconnected from SSE stream")
1193 return
1194
Philip Zeyligereab12de2025-05-14 02:35:53 +00001195 case _, ok := <-stateChan:
1196 if !ok {
1197 // Channel closed
1198 slog.InfoContext(ctx, "State transition channel closed, ending SSE stream")
1199 return
1200 }
1201
1202 // Get updated state
1203 state = s.getState()
1204
1205 // Send updated state after the state transition
1206 fmt.Fprintf(w, "event: state\n")
1207 fmt.Fprintf(w, "data: ")
1208 encoder.Encode(state)
1209 fmt.Fprintf(w, "\n\n")
1210
1211 // Flush to send the state immediately
1212 if f, ok := w.(http.Flusher); ok {
1213 f.Flush()
1214 }
1215
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001216 case newMessage, ok := <-messageChan:
1217 if !ok {
1218 // Channel closed
1219 slog.InfoContext(ctx, "Message channel closed, ending SSE stream")
1220 return
1221 }
1222
1223 // Send the new message as an event
1224 fmt.Fprintf(w, "event: message\n")
1225 fmt.Fprintf(w, "data: ")
1226 encoder.Encode(newMessage)
1227 fmt.Fprintf(w, "\n\n")
1228
1229 // Get updated state
1230 state = s.getState()
1231
1232 // Send updated state after the message
1233 fmt.Fprintf(w, "event: state\n")
1234 fmt.Fprintf(w, "data: ")
1235 encoder.Encode(state)
1236 fmt.Fprintf(w, "\n\n")
1237
1238 // Flush to send the message and state immediately
1239 if f, ok := w.(http.Flusher); ok {
1240 f.Flush()
1241 }
1242 }
1243 }
1244}
1245
1246// Helper function to get the current state
1247func (s *Server) getState() State {
1248 serverMessageCount := s.agent.MessageCount()
1249 totalUsage := s.agent.TotalUsage()
1250
Philip Zeyliger64f60462025-06-16 13:57:10 -07001251 // Get diff stats
1252 diffAdded, diffRemoved := s.agent.DiffStats()
1253
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001254 return State{
Philip Zeyliger49edc922025-05-14 09:45:45 -07001255 StateVersion: 2,
1256 MessageCount: serverMessageCount,
1257 TotalUsage: &totalUsage,
1258 Hostname: s.hostname,
1259 WorkingDir: getWorkingDir(),
1260 // TODO: Rename this field to sketch-base?
1261 InitialCommit: s.agent.SketchGitBase(),
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -07001262 Slug: s.agent.Slug(),
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001263 BranchName: s.agent.BranchName(),
Philip Zeyligerbe7802a2025-06-04 20:15:25 +00001264 BranchPrefix: s.agent.BranchPrefix(),
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001265 OS: s.agent.OS(),
1266 OutsideHostname: s.agent.OutsideHostname(),
1267 InsideHostname: s.hostname,
1268 OutsideOS: s.agent.OutsideOS(),
1269 InsideOS: s.agent.OS(),
1270 OutsideWorkingDir: s.agent.OutsideWorkingDir(),
1271 InsideWorkingDir: getWorkingDir(),
1272 GitOrigin: s.agent.GitOrigin(),
1273 OutstandingLLMCalls: s.agent.OutstandingLLMCallCount(),
1274 OutstandingToolCalls: s.agent.OutstandingToolCalls(),
1275 SessionID: s.agent.SessionID(),
1276 SSHAvailable: s.sshAvailable,
1277 SSHError: s.sshError,
1278 InContainer: s.agent.IsInContainer(),
1279 FirstMessageIndex: s.agent.FirstMessageIndex(),
1280 AgentState: s.agent.CurrentStateName(),
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -07001281 TodoContent: s.agent.CurrentTodoContent(),
Philip Zeyliger0113be52025-06-07 23:53:41 +00001282 SkabandAddr: s.agent.SkabandAddr(),
philip.zeyliger6d3de482025-06-10 19:38:14 -07001283 LinkToGitHub: s.agent.LinkToGitHub(),
philip.zeyliger8773e682025-06-11 21:36:21 -07001284 SSHConnectionString: s.agent.SSHConnectionString(),
Philip Zeyliger64f60462025-06-16 13:57:10 -07001285 DiffLinesAdded: diffAdded,
1286 DiffLinesRemoved: diffRemoved,
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001287 }
1288}
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001289
1290func (s *Server) handleGitRawDiff(w http.ResponseWriter, r *http.Request) {
1291 if r.Method != "GET" {
1292 w.WriteHeader(http.StatusMethodNotAllowed)
1293 return
1294 }
1295
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +00001296 // Get the git repository root directory from agent
1297 repoDir := s.agent.RepoRoot()
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001298
1299 // Parse query parameters
1300 query := r.URL.Query()
1301 commit := query.Get("commit")
1302 from := query.Get("from")
1303 to := query.Get("to")
1304
1305 // If commit is specified, use commit^ and commit as from and to
1306 if commit != "" {
1307 from = commit + "^"
1308 to = commit
1309 }
1310
1311 // Check if we have enough parameters
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001312 if from == "" {
1313 http.Error(w, "Missing required parameter: either 'commit' or at least 'from'", http.StatusBadRequest)
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001314 return
1315 }
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001316 // Note: 'to' can be empty to indicate working directory (unstaged changes)
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001317
1318 // Call the git_tools function
1319 diff, err := git_tools.GitRawDiff(repoDir, from, to)
1320 if err != nil {
1321 http.Error(w, fmt.Sprintf("Error getting git diff: %v", err), http.StatusInternalServerError)
1322 return
1323 }
1324
1325 // Return the result as JSON
1326 w.Header().Set("Content-Type", "application/json")
1327 if err := json.NewEncoder(w).Encode(diff); err != nil {
1328 http.Error(w, fmt.Sprintf("Error encoding response: %v", err), http.StatusInternalServerError)
1329 return
1330 }
1331}
1332
1333func (s *Server) handleGitShow(w http.ResponseWriter, r *http.Request) {
1334 if r.Method != "GET" {
1335 w.WriteHeader(http.StatusMethodNotAllowed)
1336 return
1337 }
1338
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +00001339 // Get the git repository root directory from agent
1340 repoDir := s.agent.RepoRoot()
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001341
1342 // Parse query parameters
1343 hash := r.URL.Query().Get("hash")
1344 if hash == "" {
1345 http.Error(w, "Missing required parameter: 'hash'", http.StatusBadRequest)
1346 return
1347 }
1348
1349 // Call the git_tools function
1350 show, err := git_tools.GitShow(repoDir, hash)
1351 if err != nil {
1352 http.Error(w, fmt.Sprintf("Error running git show: %v", err), http.StatusInternalServerError)
1353 return
1354 }
1355
1356 // Create a JSON response
1357 response := map[string]string{
1358 "hash": hash,
1359 "output": show,
1360 }
1361
1362 // Return the result as JSON
1363 w.Header().Set("Content-Type", "application/json")
1364 if err := json.NewEncoder(w).Encode(response); err != nil {
1365 http.Error(w, fmt.Sprintf("Error encoding response: %v", err), http.StatusInternalServerError)
1366 return
1367 }
1368}
1369
1370func (s *Server) handleGitRecentLog(w http.ResponseWriter, r *http.Request) {
1371 if r.Method != "GET" {
1372 w.WriteHeader(http.StatusMethodNotAllowed)
1373 return
1374 }
1375
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +00001376 // Get the git repository root directory and initial commit from agent
1377 repoDir := s.agent.RepoRoot()
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001378 initialCommit := s.agent.SketchGitBaseRef()
1379
1380 // Call the git_tools function
1381 log, err := git_tools.GitRecentLog(repoDir, initialCommit)
1382 if err != nil {
1383 http.Error(w, fmt.Sprintf("Error getting git log: %v", err), http.StatusInternalServerError)
1384 return
1385 }
1386
1387 // Return the result as JSON
1388 w.Header().Set("Content-Type", "application/json")
1389 if err := json.NewEncoder(w).Encode(log); err != nil {
1390 http.Error(w, fmt.Sprintf("Error encoding response: %v", err), http.StatusInternalServerError)
1391 return
1392 }
1393}
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001394
1395func (s *Server) handleGitCat(w http.ResponseWriter, r *http.Request) {
1396 if r.Method != "GET" {
1397 w.WriteHeader(http.StatusMethodNotAllowed)
1398 return
1399 }
1400
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +00001401 // Get the git repository root directory from agent
1402 repoDir := s.agent.RepoRoot()
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001403
1404 // Parse query parameters
1405 query := r.URL.Query()
1406 path := query.Get("path")
1407
1408 // Check if path is provided
1409 if path == "" {
1410 http.Error(w, "Missing required parameter: path", http.StatusBadRequest)
1411 return
1412 }
1413
1414 // Get file content using GitCat
1415 content, err := git_tools.GitCat(repoDir, path)
1416 if err != nil {
1417 http.Error(w, fmt.Sprintf("Error reading file: %v", err), http.StatusInternalServerError)
1418 return
1419 }
1420
1421 // Return the content as JSON for consistency with other endpoints
1422 w.Header().Set("Content-Type", "application/json")
1423 if err := json.NewEncoder(w).Encode(map[string]string{"output": content}); err != nil {
1424 http.Error(w, fmt.Sprintf("Error encoding response: %v", err), http.StatusInternalServerError)
1425 return
1426 }
1427}
1428
1429func (s *Server) handleGitSave(w http.ResponseWriter, r *http.Request) {
1430 if r.Method != "POST" {
1431 w.WriteHeader(http.StatusMethodNotAllowed)
1432 return
1433 }
1434
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +00001435 // Get the git repository root directory from agent
1436 repoDir := s.agent.RepoRoot()
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001437
1438 // Parse request body
1439 var requestBody struct {
1440 Path string `json:"path"`
1441 Content string `json:"content"`
1442 }
1443
1444 if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {
1445 http.Error(w, fmt.Sprintf("Error parsing request body: %v", err), http.StatusBadRequest)
1446 return
1447 }
1448 defer r.Body.Close()
1449
1450 // Check if path is provided
1451 if requestBody.Path == "" {
1452 http.Error(w, "Missing required parameter: path", http.StatusBadRequest)
1453 return
1454 }
1455
1456 // Save file content using GitSaveFile
1457 err := git_tools.GitSaveFile(repoDir, requestBody.Path, requestBody.Content)
1458 if err != nil {
1459 http.Error(w, fmt.Sprintf("Error saving file: %v", err), http.StatusInternalServerError)
1460 return
1461 }
1462
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001463 // Auto-commit the changes
1464 err = git_tools.AutoCommitDiffViewChanges(r.Context(), repoDir, requestBody.Path)
1465 if err != nil {
1466 http.Error(w, fmt.Sprintf("Error auto-committing changes: %v", err), http.StatusInternalServerError)
1467 return
1468 }
1469
1470 // Detect git changes to push and notify user
Philip Zeyliger9bca61e2025-05-22 12:40:06 -07001471 if err = s.agent.DetectGitChanges(r.Context()); err != nil {
1472 http.Error(w, fmt.Sprintf("Error detecting git changes: %v", err), http.StatusInternalServerError)
1473 return
1474 }
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001475
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001476 // Return simple success response
1477 w.WriteHeader(http.StatusOK)
1478 w.Write([]byte("ok"))
1479}