blob: 8a65b4ca58289f5990bfa227ae1a5d27129a1813 [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"
Josh Bleecher Snyder5c29b3e2025-07-08 18:07:28 +000010 "errors"
Earl Lee2e463fb2025-04-17 11:22:22 -070011 "fmt"
12 "html"
13 "io"
Earl Lee2e463fb2025-04-17 11:22:22 -070014 "log/slog"
15 "net/http"
Philip Zeyligera9710d72025-07-02 02:50:14 +000016 "net/http/httputil"
Earl Lee2e463fb2025-04-17 11:22:22 -070017 "net/http/pprof"
Philip Zeyligera9710d72025-07-02 02:50:14 +000018 "net/url"
Earl Lee2e463fb2025-04-17 11:22:22 -070019 "os"
20 "os/exec"
Philip Zeyligerf84e88c2025-05-14 23:19:01 +000021 "path/filepath"
Philip Zeyliger8d8b7ac2025-05-21 09:57:23 -070022 "runtime/debug"
Earl Lee2e463fb2025-04-17 11:22:22 -070023 "strconv"
24 "strings"
25 "sync"
26 "syscall"
27 "time"
28
29 "github.com/creack/pty"
Philip Zeyliger33d282f2025-05-03 04:01:54 +000030 "sketch.dev/claudetool/browse"
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -070031 "sketch.dev/embedded"
32 "sketch.dev/git_tools"
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070033 "sketch.dev/llm/conversation"
Earl Lee2e463fb2025-04-17 11:22:22 -070034 "sketch.dev/loop"
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -070035 "sketch.dev/loop/server/gzhandler"
Earl Lee2e463fb2025-04-17 11:22:22 -070036)
37
38// terminalSession represents a terminal session with its PTY and the event channel
39type terminalSession struct {
40 pty *os.File
41 eventsClients map[chan []byte]bool
42 lastEventClientID int
43 eventsClientsMutex sync.Mutex
44 cmd *exec.Cmd
45}
46
47// TerminalMessage represents a message sent from the client for terminal resize events
48type TerminalMessage struct {
49 Type string `json:"type"`
50 Cols uint16 `json:"cols"`
51 Rows uint16 `json:"rows"`
52}
53
54// TerminalResponse represents the response for a new terminal creation
55type TerminalResponse struct {
56 SessionID string `json:"sessionId"`
57}
58
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -070059// TodoItem represents a single todo item for task management
60type TodoItem struct {
61 ID string `json:"id"`
62 Task string `json:"task"`
63 Status string `json:"status"` // queued, in-progress, completed
64}
65
66// TodoList represents a collection of todo items
67type TodoList struct {
68 Items []TodoItem `json:"items"`
69}
70
Sean McCulloughd9f13372025-04-21 15:08:49 -070071type State struct {
Philip Zeyligerd03318d2025-05-08 13:09:12 -070072 // null or 1: "old"
73 // 2: supports SSE for message updates
74 StateVersion int `json:"state_version"`
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070075 MessageCount int `json:"message_count"`
76 TotalUsage *conversation.CumulativeUsage `json:"total_usage,omitempty"`
77 InitialCommit string `json:"initial_commit"`
Josh Bleecher Snyder19969a92025-06-05 14:34:02 -070078 Slug string `json:"slug,omitempty"`
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070079 BranchName string `json:"branch_name,omitempty"`
Philip Zeyligerbe7802a2025-06-04 20:15:25 +000080 BranchPrefix string `json:"branch_prefix,omitempty"`
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070081 Hostname string `json:"hostname"` // deprecated
82 WorkingDir string `json:"working_dir"` // deprecated
83 OS string `json:"os"` // deprecated
84 GitOrigin string `json:"git_origin,omitempty"`
bankseancad67b02025-06-27 21:57:05 +000085 GitUsername string `json:"git_username,omitempty"`
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070086 OutstandingLLMCalls int `json:"outstanding_llm_calls"`
87 OutstandingToolCalls []string `json:"outstanding_tool_calls"`
88 SessionID string `json:"session_id"`
89 SSHAvailable bool `json:"ssh_available"`
90 SSHError string `json:"ssh_error,omitempty"`
91 InContainer bool `json:"in_container"`
92 FirstMessageIndex int `json:"first_message_index"`
93 AgentState string `json:"agent_state,omitempty"`
94 OutsideHostname string `json:"outside_hostname,omitempty"`
95 InsideHostname string `json:"inside_hostname,omitempty"`
96 OutsideOS string `json:"outside_os,omitempty"`
97 InsideOS string `json:"inside_os,omitempty"`
98 OutsideWorkingDir string `json:"outside_working_dir,omitempty"`
99 InsideWorkingDir string `json:"inside_working_dir,omitempty"`
philip.zeyliger8773e682025-06-11 21:36:21 -0700100 TodoContent string `json:"todo_content,omitempty"` // Contains todo list JSON data
101 SkabandAddr string `json:"skaband_addr,omitempty"` // URL of the skaband server
102 LinkToGitHub bool `json:"link_to_github,omitempty"` // Enable GitHub branch linking in UI
103 SSHConnectionString string `json:"ssh_connection_string,omitempty"` // SSH connection string for container
Philip Zeyliger64f60462025-06-16 13:57:10 -0700104 DiffLinesAdded int `json:"diff_lines_added"` // Lines added from sketch-base to HEAD
105 DiffLinesRemoved int `json:"diff_lines_removed"` // Lines removed from sketch-base to HEAD
Philip Zeyliger5f26a342025-07-04 01:30:29 +0000106 OpenPorts []Port `json:"open_ports,omitempty"` // Currently open TCP ports
107}
108
109// Port represents an open TCP port
110type Port struct {
111 Proto string `json:"proto"` // "tcp" or "udp"
112 Port uint16 `json:"port"` // port number
113 Process string `json:"process"` // optional process name
114 Pid int `json:"pid"` // process ID
Sean McCulloughd9f13372025-04-21 15:08:49 -0700115}
116
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700117type InitRequest struct {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700118 // Passed to agent so that the URL it prints in the termui prompt is correct (when skaband is not used)
119 HostAddr string `json:"host_addr"`
120
121 // POST /init will start the SSH server with these configs
Sean McCullough7013e9e2025-05-14 02:03:58 +0000122 SSHAuthorizedKeys []byte `json:"ssh_authorized_keys"`
123 SSHServerIdentity []byte `json:"ssh_server_identity"`
124 SSHContainerCAKey []byte `json:"ssh_container_ca_key"`
125 SSHHostCertificate []byte `json:"ssh_host_certificate"`
126 SSHAvailable bool `json:"ssh_available"`
127 SSHError string `json:"ssh_error,omitempty"`
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700128}
129
Earl Lee2e463fb2025-04-17 11:22:22 -0700130// Server serves sketch HTTP. Server implements http.Handler.
131type Server struct {
132 mux *http.ServeMux
133 agent loop.CodingAgent
134 hostname string
135 logFile *os.File
136 // Mutex to protect terminalSessions
137 ptyMutex sync.Mutex
138 terminalSessions map[string]*terminalSession
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000139 sshAvailable bool
140 sshError string
Earl Lee2e463fb2025-04-17 11:22:22 -0700141}
142
143func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
Philip Zeyligera9710d72025-07-02 02:50:14 +0000144 // Check if Host header matches "p<port>.localhost" pattern and proxy to that port
145 if port := s.ParsePortProxyHost(r.Host); port != "" {
146 s.proxyToPort(w, r, port)
147 return
148 }
149
Earl Lee2e463fb2025-04-17 11:22:22 -0700150 s.mux.ServeHTTP(w, r)
151}
152
Philip Zeyligera9710d72025-07-02 02:50:14 +0000153// ParsePortProxyHost checks if host matches "p<port>.localhost" pattern and returns the port
154func (s *Server) ParsePortProxyHost(host string) string {
155 // Remove port suffix if present (e.g., "p8000.localhost:8080" -> "p8000.localhost")
156 hostname := host
157 if idx := strings.LastIndex(host, ":"); idx > 0 {
158 hostname = host[:idx]
159 }
160
161 // Check if hostname matches p<port>.localhost pattern
162 if strings.HasSuffix(hostname, ".localhost") {
163 prefix := strings.TrimSuffix(hostname, ".localhost")
164 if strings.HasPrefix(prefix, "p") && len(prefix) > 1 {
165 port := prefix[1:] // Remove 'p' prefix
166 // Basic validation - port should be numeric and in valid range
167 if portNum, err := strconv.Atoi(port); err == nil && portNum > 0 && portNum <= 65535 {
168 return port
169 }
170 }
171 }
172
173 return ""
174}
175
176// proxyToPort proxies the request to localhost:<port>
177func (s *Server) proxyToPort(w http.ResponseWriter, r *http.Request, port string) {
178 // Create a reverse proxy to localhost:<port>
179 target, err := url.Parse(fmt.Sprintf("http://localhost:%s", port))
180 if err != nil {
181 http.Error(w, "Failed to parse proxy target", http.StatusInternalServerError)
182 return
183 }
184
185 proxy := httputil.NewSingleHostReverseProxy(target)
186
187 // Customize the Director to modify the request
188 originalDirector := proxy.Director
189 proxy.Director = func(req *http.Request) {
190 originalDirector(req)
191 // Set the target host
192 req.URL.Host = target.Host
193 req.URL.Scheme = target.Scheme
194 req.Host = target.Host
195 }
196
197 // Handle proxy errors
198 proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) {
199 slog.Error("Proxy error", "error", err, "target", target.String(), "port", port)
200 http.Error(w, "Proxy error: "+err.Error(), http.StatusBadGateway)
201 }
202
203 proxy.ServeHTTP(w, r)
204}
205
Earl Lee2e463fb2025-04-17 11:22:22 -0700206// New creates a new HTTP server.
207func New(agent loop.CodingAgent, logFile *os.File) (*Server, error) {
208 s := &Server{
209 mux: http.NewServeMux(),
210 agent: agent,
211 hostname: getHostname(),
212 logFile: logFile,
213 terminalSessions: make(map[string]*terminalSession),
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000214 sshAvailable: false,
215 sshError: "",
Earl Lee2e463fb2025-04-17 11:22:22 -0700216 }
217
Philip Zeyliger25f6ff12025-05-02 04:24:10 +0000218 s.mux.HandleFunc("/stream", s.handleSSEStream)
Philip Zeyligerd3ac1122025-05-14 02:54:18 +0000219
220 // Git tool endpoints
221 s.mux.HandleFunc("/git/rawdiff", s.handleGitRawDiff)
222 s.mux.HandleFunc("/git/show", s.handleGitShow)
Philip Zeyliger272a90e2025-05-16 14:49:51 -0700223 s.mux.HandleFunc("/git/cat", s.handleGitCat)
224 s.mux.HandleFunc("/git/save", s.handleGitSave)
Philip Zeyligerd3ac1122025-05-14 02:54:18 +0000225 s.mux.HandleFunc("/git/recentlog", s.handleGitRecentLog)
226
Earl Lee2e463fb2025-04-17 11:22:22 -0700227 s.mux.HandleFunc("/diff", func(w http.ResponseWriter, r *http.Request) {
228 // Check if a specific commit hash was requested
229 commit := r.URL.Query().Get("commit")
230
231 // Get the diff, optionally for a specific commit
232 var diff string
233 var err error
234 if commit != "" {
235 // Validate the commit hash format
236 if !isValidGitSHA(commit) {
237 http.Error(w, fmt.Sprintf("Invalid git commit SHA format: %s", commit), http.StatusBadRequest)
238 return
239 }
240
241 diff, err = agent.Diff(&commit)
242 } else {
243 diff, err = agent.Diff(nil)
244 }
245
246 if err != nil {
247 http.Error(w, fmt.Sprintf("Error generating diff: %v", err), http.StatusInternalServerError)
248 return
249 }
250
251 w.Header().Set("Content-Type", "text/plain")
252 w.Write([]byte(diff))
253 })
254
255 // Handler for initialization called by host sketch binary when inside docker.
256 s.mux.HandleFunc("/init", func(w http.ResponseWriter, r *http.Request) {
257 defer func() {
258 if err := recover(); err != nil {
259 slog.ErrorContext(r.Context(), "/init panic", slog.Any("recovered_err", err))
260
261 // Return an error response to the client
262 http.Error(w, fmt.Sprintf("panic: %v\n", err), http.StatusInternalServerError)
263 }
264 }()
265
266 if r.Method != "POST" {
267 http.Error(w, "POST required", http.StatusBadRequest)
268 return
269 }
270
271 body, err := io.ReadAll(r.Body)
272 r.Body.Close()
273 if err != nil {
274 http.Error(w, "failed to read request body: "+err.Error(), http.StatusBadRequest)
275 return
276 }
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700277
278 m := &InitRequest{}
279 if err := json.Unmarshal(body, m); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700280 http.Error(w, "bad request body: "+err.Error(), http.StatusBadRequest)
281 return
282 }
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700283
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000284 // Store SSH availability info
285 s.sshAvailable = m.SSHAvailable
286 s.sshError = m.SSHError
287
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700288 // Start the SSH server if the init request included ssh keys.
289 if len(m.SSHAuthorizedKeys) > 0 && len(m.SSHServerIdentity) > 0 {
290 go func() {
291 ctx := context.Background()
Sean McCullough7013e9e2025-05-14 02:03:58 +0000292 if err := s.ServeSSH(ctx, m.SSHServerIdentity, m.SSHAuthorizedKeys, m.SSHContainerCAKey, m.SSHHostCertificate); err != nil {
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700293 slog.ErrorContext(r.Context(), "/init ServeSSH", slog.String("err", err.Error()))
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000294 // Update SSH error if server fails to start
295 s.sshAvailable = false
296 s.sshError = err.Error()
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700297 }
298 }()
299 }
300
Earl Lee2e463fb2025-04-17 11:22:22 -0700301 ini := loop.AgentInit{
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700302 InDocker: true,
303 HostAddr: m.HostAddr,
Earl Lee2e463fb2025-04-17 11:22:22 -0700304 }
305 if err := agent.Init(ini); err != nil {
306 http.Error(w, "init failed: "+err.Error(), http.StatusInternalServerError)
307 return
308 }
309 w.Header().Set("Content-Type", "application/json")
310 io.WriteString(w, "{}\n")
311 })
312
313 // Handler for /messages?start=N&end=M (start/end are optional)
314 s.mux.HandleFunc("/messages", func(w http.ResponseWriter, r *http.Request) {
315 w.Header().Set("Content-Type", "application/json")
316
317 // Extract query parameters for range
318 var start, end int
319 var err error
320
321 currentCount := agent.MessageCount()
322
323 startParam := r.URL.Query().Get("start")
324 if startParam != "" {
325 start, err = strconv.Atoi(startParam)
326 if err != nil {
327 http.Error(w, "Invalid 'start' parameter", http.StatusBadRequest)
328 return
329 }
330 }
331
332 endParam := r.URL.Query().Get("end")
333 if endParam != "" {
334 end, err = strconv.Atoi(endParam)
335 if err != nil {
336 http.Error(w, "Invalid 'end' parameter", http.StatusBadRequest)
337 return
338 }
339 } else {
340 end = currentCount
341 }
342
343 if start < 0 || start > end || end > currentCount {
344 http.Error(w, fmt.Sprintf("Invalid range: start %d end %d currentCount %d", start, end, currentCount), http.StatusBadRequest)
345 return
346 }
347
348 start = max(0, start)
349 end = min(agent.MessageCount(), end)
350 messages := agent.Messages(start, end)
351
352 // Create a JSON encoder with indentation for pretty-printing
353 encoder := json.NewEncoder(w)
354 encoder.SetIndent("", " ") // Two spaces for each indentation level
355
356 err = encoder.Encode(messages)
357 if err != nil {
358 http.Error(w, err.Error(), http.StatusInternalServerError)
359 }
360 })
361
362 // Handler for /logs - displays the contents of the log file
363 s.mux.HandleFunc("/logs", func(w http.ResponseWriter, r *http.Request) {
364 if s.logFile == nil {
365 http.Error(w, "log file not set", http.StatusNotFound)
366 return
367 }
368 logContents, err := os.ReadFile(s.logFile.Name())
369 if err != nil {
370 http.Error(w, "error reading log file: "+err.Error(), http.StatusInternalServerError)
371 return
372 }
373 w.Header().Set("Content-Type", "text/html; charset=utf-8")
374 fmt.Fprintf(w, "<!DOCTYPE html>\n<html>\n<head>\n<title>Sketchy Log File</title>\n</head>\n<body>\n")
375 fmt.Fprintf(w, "<pre>%s</pre>\n", html.EscapeString(string(logContents)))
376 fmt.Fprintf(w, "</body>\n</html>")
377 })
378
379 // Handler for /download - downloads both messages and status as a JSON file
380 s.mux.HandleFunc("/download", func(w http.ResponseWriter, r *http.Request) {
381 // Set headers for file download
382 w.Header().Set("Content-Type", "application/octet-stream")
383
384 // Generate filename with format: sketch-YYYYMMDD-HHMMSS.json
385 timestamp := time.Now().Format("20060102-150405")
386 filename := fmt.Sprintf("sketch-%s.json", timestamp)
387
388 w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
389
390 // Get all messages
391 messageCount := agent.MessageCount()
392 messages := agent.Messages(0, messageCount)
393
394 // Get status information (usage and other metadata)
395 totalUsage := agent.TotalUsage()
396 hostname := getHostname()
397 workingDir := getWorkingDir()
398
399 // Create a combined structure with all information
400 downloadData := struct {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700401 Messages []loop.AgentMessage `json:"messages"`
402 MessageCount int `json:"message_count"`
403 TotalUsage conversation.CumulativeUsage `json:"total_usage"`
404 Hostname string `json:"hostname"`
405 WorkingDir string `json:"working_dir"`
406 DownloadTime string `json:"download_time"`
Earl Lee2e463fb2025-04-17 11:22:22 -0700407 }{
408 Messages: messages,
409 MessageCount: messageCount,
410 TotalUsage: totalUsage,
411 Hostname: hostname,
412 WorkingDir: workingDir,
413 DownloadTime: time.Now().Format(time.RFC3339),
414 }
415
416 // Marshal the JSON with indentation for better readability
417 jsonData, err := json.MarshalIndent(downloadData, "", " ")
418 if err != nil {
419 http.Error(w, err.Error(), http.StatusInternalServerError)
420 return
421 }
422 w.Write(jsonData)
423 })
424
425 // The latter doesn't return until the number of messages has changed (from seen
426 // or from when this was called.)
427 s.mux.HandleFunc("/state", func(w http.ResponseWriter, r *http.Request) {
428 pollParam := r.URL.Query().Get("poll")
429 seenParam := r.URL.Query().Get("seen")
430
431 // Get the client's current message count (if provided)
432 clientMessageCount := -1
433 var err error
434 if seenParam != "" {
435 clientMessageCount, err = strconv.Atoi(seenParam)
436 if err != nil {
437 http.Error(w, "Invalid 'seen' parameter", http.StatusBadRequest)
438 return
439 }
440 }
441
442 serverMessageCount := agent.MessageCount()
443
444 // Let lazy clients not have to specify this.
445 if clientMessageCount == -1 {
446 clientMessageCount = serverMessageCount
447 }
448
449 if pollParam == "true" {
450 ch := make(chan string)
451 go func() {
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700452 it := agent.NewIterator(r.Context(), clientMessageCount)
453 it.Next()
Earl Lee2e463fb2025-04-17 11:22:22 -0700454 close(ch)
Philip Zeyligerb7c58752025-05-01 10:10:17 -0700455 it.Close()
Earl Lee2e463fb2025-04-17 11:22:22 -0700456 }()
457 select {
458 case <-r.Context().Done():
459 slog.DebugContext(r.Context(), "abandoned poll request")
460 return
461 case <-time.After(90 * time.Second):
462 // Let the user call /state again to get the latest to limit how long our long polls hang out.
463 slog.DebugContext(r.Context(), "longish poll request")
464 break
465 case <-ch:
466 break
467 }
468 }
469
Earl Lee2e463fb2025-04-17 11:22:22 -0700470 w.Header().Set("Content-Type", "application/json")
471
Philip Zeyliger25f6ff12025-05-02 04:24:10 +0000472 // Use the shared getState function
473 state := s.getState()
Earl Lee2e463fb2025-04-17 11:22:22 -0700474
475 // Create a JSON encoder with indentation for pretty-printing
476 encoder := json.NewEncoder(w)
477 encoder.SetIndent("", " ") // Two spaces for each indentation level
478
479 err = encoder.Encode(state)
480 if err != nil {
481 http.Error(w, err.Error(), http.StatusInternalServerError)
482 }
483 })
484
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -0700485 s.mux.Handle("/static/", http.StripPrefix("/static/", gzhandler.New(embedded.WebUIFS())))
Earl Lee2e463fb2025-04-17 11:22:22 -0700486
487 // Terminal WebSocket handler
488 // Terminal endpoints - predefined terminals 1-9
489 // TODO: The UI doesn't actually know how to use terminals 2-9!
490 s.mux.HandleFunc("/terminal/events/", func(w http.ResponseWriter, r *http.Request) {
491 if r.Method != http.MethodGet {
492 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
493 return
494 }
495 pathParts := strings.Split(r.URL.Path, "/")
496 if len(pathParts) < 4 {
497 http.Error(w, "Invalid terminal ID", http.StatusBadRequest)
498 return
499 }
500
501 sessionID := pathParts[3]
502 // Validate that the terminal ID is between 1-9
503 if len(sessionID) != 1 || sessionID[0] < '1' || sessionID[0] > '9' {
504 http.Error(w, "Terminal ID must be between 1 and 9", http.StatusBadRequest)
505 return
506 }
507
508 s.handleTerminalEvents(w, r, sessionID)
509 })
510
511 s.mux.HandleFunc("/terminal/input/", func(w http.ResponseWriter, r *http.Request) {
512 if r.Method != http.MethodPost {
513 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
514 return
515 }
516 pathParts := strings.Split(r.URL.Path, "/")
517 if len(pathParts) < 4 {
518 http.Error(w, "Invalid terminal ID", http.StatusBadRequest)
519 return
520 }
521 sessionID := pathParts[3]
522 s.handleTerminalInput(w, r, sessionID)
523 })
524
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -0700525 // Handler for interface selection via URL parameters (?m for mobile)
Earl Lee2e463fb2025-04-17 11:22:22 -0700526 s.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -0700527 webuiFS := embedded.WebUIFS()
528 appShell := "sketch-app-shell.html"
529 if r.URL.Query().Has("m") {
530 appShell = "mobile-app-shell.html"
Philip Zeyligere08c7ff2025-06-06 13:22:12 -0700531 }
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -0700532 http.ServeFileFS(w, r, webuiFS, appShell)
Earl Lee2e463fb2025-04-17 11:22:22 -0700533 })
534
Philip Zeyliger2c4db092025-04-28 16:57:50 -0700535 // Handler for /commit-description - returns the description of a git commit
536 s.mux.HandleFunc("/commit-description", func(w http.ResponseWriter, r *http.Request) {
537 if r.Method != http.MethodGet {
538 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
539 return
540 }
541
542 // Get the revision parameter
543 revision := r.URL.Query().Get("revision")
544 if revision == "" {
545 http.Error(w, "Missing revision parameter", http.StatusBadRequest)
546 return
547 }
548
549 // Run git command to get commit description
550 cmd := exec.Command("git", "log", "--oneline", "--decorate", "-n", "1", revision)
551 // Use the working directory from the agent
552 cmd.Dir = s.agent.WorkingDir()
553
554 output, err := cmd.CombinedOutput()
555 if err != nil {
556 http.Error(w, "Failed to get commit description: "+err.Error(), http.StatusInternalServerError)
557 return
558 }
559
560 // Prepare the response
561 resp := map[string]string{
562 "description": strings.TrimSpace(string(output)),
563 }
564
565 w.Header().Set("Content-Type", "application/json")
566 if err := json.NewEncoder(w).Encode(resp); err != nil {
567 slog.ErrorContext(r.Context(), "Error encoding commit description response", slog.Any("err", err))
568 }
569 })
570
Philip Zeyliger33d282f2025-05-03 04:01:54 +0000571 // Handler for /screenshot/{id} - serves screenshot images
572 s.mux.HandleFunc("/screenshot/", func(w http.ResponseWriter, r *http.Request) {
573 if r.Method != http.MethodGet {
574 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
575 return
576 }
577
578 // Extract the screenshot ID from the path
579 pathParts := strings.Split(r.URL.Path, "/")
580 if len(pathParts) < 3 {
581 http.Error(w, "Invalid screenshot ID", http.StatusBadRequest)
582 return
583 }
584
585 screenshotID := pathParts[2]
586
587 // Validate the ID format (prevent directory traversal)
588 if strings.Contains(screenshotID, "/") || strings.Contains(screenshotID, "\\") {
589 http.Error(w, "Invalid screenshot ID format", http.StatusBadRequest)
590 return
591 }
592
593 // Get the screenshot file path
594 filePath := browse.GetScreenshotPath(screenshotID)
595
596 // Check if the file exists
597 if _, err := os.Stat(filePath); os.IsNotExist(err) {
598 http.Error(w, "Screenshot not found", http.StatusNotFound)
599 return
600 }
601
602 // Serve the file
603 w.Header().Set("Content-Type", "image/png")
604 w.Header().Set("Cache-Control", "max-age=3600") // Cache for an hour
605 http.ServeFile(w, r, filePath)
606 })
607
Earl Lee2e463fb2025-04-17 11:22:22 -0700608 // Handler for POST /chat
609 s.mux.HandleFunc("/chat", 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 // Parse the request body
616 var requestBody struct {
617 Message string `json:"message"`
618 }
619
620 decoder := json.NewDecoder(r.Body)
621 if err := decoder.Decode(&requestBody); err != nil {
622 http.Error(w, "Invalid request body: "+err.Error(), http.StatusBadRequest)
623 return
624 }
625 defer r.Body.Close()
626
627 if requestBody.Message == "" {
628 http.Error(w, "Message cannot be empty", http.StatusBadRequest)
629 return
630 }
631
632 agent.UserMessage(r.Context(), requestBody.Message)
633
634 w.WriteHeader(http.StatusOK)
635 })
636
Philip Zeyligerf84e88c2025-05-14 23:19:01 +0000637 // Handler for POST /upload - uploads a file to /tmp
638 s.mux.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
639 if r.Method != http.MethodPost {
640 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
641 return
642 }
643
644 // Limit to 10MB file size
645 r.Body = http.MaxBytesReader(w, r.Body, 10*1024*1024)
646
647 // Parse the multipart form
648 if err := r.ParseMultipartForm(10 * 1024 * 1024); err != nil {
649 http.Error(w, "Failed to parse form: "+err.Error(), http.StatusBadRequest)
650 return
651 }
652
653 // Get the file from the multipart form
654 file, handler, err := r.FormFile("file")
655 if err != nil {
656 http.Error(w, "Failed to get uploaded file: "+err.Error(), http.StatusBadRequest)
657 return
658 }
659 defer file.Close()
660
661 // Generate a unique ID (8 random bytes converted to 16 hex chars)
662 randBytes := make([]byte, 8)
663 if _, err := rand.Read(randBytes); err != nil {
664 http.Error(w, "Failed to generate random filename: "+err.Error(), http.StatusInternalServerError)
665 return
666 }
667
668 // Get file extension from the original filename
669 ext := filepath.Ext(handler.Filename)
670
671 // Create a unique filename in the /tmp directory
672 filename := fmt.Sprintf("/tmp/sketch_file_%s%s", hex.EncodeToString(randBytes), ext)
673
674 // Create the destination file
675 destFile, err := os.Create(filename)
676 if err != nil {
677 http.Error(w, "Failed to create destination file: "+err.Error(), http.StatusInternalServerError)
678 return
679 }
680 defer destFile.Close()
681
682 // Copy the file contents to the destination file
683 if _, err := io.Copy(destFile, file); err != nil {
684 http.Error(w, "Failed to save file: "+err.Error(), http.StatusInternalServerError)
685 return
686 }
687
688 // Return the path to the saved file
689 w.Header().Set("Content-Type", "application/json")
690 json.NewEncoder(w).Encode(map[string]string{"path": filename})
691 })
692
Earl Lee2e463fb2025-04-17 11:22:22 -0700693 // Handler for /cancel - cancels the current inner loop in progress
694 s.mux.HandleFunc("/cancel", func(w http.ResponseWriter, r *http.Request) {
695 if r.Method != http.MethodPost {
696 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
697 return
698 }
699
700 // Parse the request body (optional)
701 var requestBody struct {
702 Reason string `json:"reason"`
703 ToolCallID string `json:"tool_call_id"`
704 }
705
706 decoder := json.NewDecoder(r.Body)
707 if err := decoder.Decode(&requestBody); err != nil && err != io.EOF {
708 http.Error(w, "Invalid request body: "+err.Error(), http.StatusBadRequest)
709 return
710 }
711 defer r.Body.Close()
712
713 cancelReason := "user requested cancellation"
714 if requestBody.Reason != "" {
715 cancelReason = requestBody.Reason
716 }
717
718 if requestBody.ToolCallID != "" {
719 err := agent.CancelToolUse(requestBody.ToolCallID, fmt.Errorf("%s", cancelReason))
720 if err != nil {
721 http.Error(w, err.Error(), http.StatusBadRequest)
722 return
723 }
724 // Return a success response
725 w.Header().Set("Content-Type", "application/json")
726 json.NewEncoder(w).Encode(map[string]string{
727 "status": "cancelled",
728 "too_use_id": requestBody.ToolCallID,
Philip Zeyliger8d50d7b2025-04-23 13:12:40 -0700729 "reason": cancelReason,
730 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700731 return
732 }
Sean McCulloughedc88dc2025-04-30 02:55:01 +0000733 // Call the CancelTurn method
734 agent.CancelTurn(fmt.Errorf("%s", cancelReason))
Earl Lee2e463fb2025-04-17 11:22:22 -0700735 // Return a success response
736 w.Header().Set("Content-Type", "application/json")
737 json.NewEncoder(w).Encode(map[string]string{"status": "cancelled", "reason": cancelReason})
738 })
739
Pokey Rule397871d2025-05-19 15:02:45 +0100740 // Handler for /end - shuts down the inner sketch process
741 s.mux.HandleFunc("/end", func(w http.ResponseWriter, r *http.Request) {
742 if r.Method != http.MethodPost {
743 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
744 return
745 }
746
747 // Parse the request body (optional)
748 var requestBody struct {
Philip Zeyligerb5739402025-06-02 07:04:34 -0700749 Reason string `json:"reason"`
750 Happy *bool `json:"happy,omitempty"`
751 Comment string `json:"comment,omitempty"`
Pokey Rule397871d2025-05-19 15:02:45 +0100752 }
753
754 decoder := json.NewDecoder(r.Body)
755 if err := decoder.Decode(&requestBody); err != nil && err != io.EOF {
756 http.Error(w, "Invalid request body: "+err.Error(), http.StatusBadRequest)
757 return
758 }
759 defer r.Body.Close()
760
761 endReason := "user requested end of session"
762 if requestBody.Reason != "" {
763 endReason = requestBody.Reason
764 }
765
766 // Send success response before exiting
767 w.Header().Set("Content-Type", "application/json")
768 json.NewEncoder(w).Encode(map[string]string{"status": "ending", "reason": endReason})
769 if f, ok := w.(http.Flusher); ok {
770 f.Flush()
771 }
772
773 // Log that we're shutting down
774 slog.Info("Ending session", "reason", endReason)
775
philip.zeyliger28e39ac2025-06-16 22:04:35 +0000776 // Give a brief moment for the response to be sent before exiting
Pokey Rule397871d2025-05-19 15:02:45 +0100777 go func() {
philip.zeyliger28e39ac2025-06-16 22:04:35 +0000778 time.Sleep(100 * time.Millisecond)
Pokey Rule397871d2025-05-19 15:02:45 +0100779 os.Exit(0)
780 }()
781 })
782
Earl Lee2e463fb2025-04-17 11:22:22 -0700783 debugMux := initDebugMux()
784 s.mux.HandleFunc("/debug/", func(w http.ResponseWriter, r *http.Request) {
785 debugMux.ServeHTTP(w, r)
786 })
787
788 return s, nil
789}
790
791// Utility functions
792func getHostname() string {
793 hostname, err := os.Hostname()
794 if err != nil {
795 return "unknown"
796 }
797 return hostname
798}
799
800func getWorkingDir() string {
801 wd, err := os.Getwd()
802 if err != nil {
803 return "unknown"
804 }
805 return wd
806}
807
808// createTerminalSession creates a new terminal session with the given ID
809func (s *Server) createTerminalSession(sessionID string) (*terminalSession, error) {
810 // Start a new shell process
811 shellPath := getShellPath()
812 cmd := exec.Command(shellPath)
813
814 // Get working directory from the agent if possible
815 workDir := getWorkingDir()
816 cmd.Dir = workDir
817
818 // Set up environment
819 cmd.Env = append(os.Environ(), "TERM=xterm-256color")
820
821 // Start the command with a pty
822 ptmx, err := pty.Start(cmd)
823 if err != nil {
824 slog.Error("Failed to start pty", "error", err)
825 return nil, err
826 }
827
828 // Create the terminal session
829 session := &terminalSession{
830 pty: ptmx,
831 eventsClients: make(map[chan []byte]bool),
832 cmd: cmd,
833 }
834
835 // Start goroutine to read from pty and broadcast to all connected SSE clients
836 go s.readFromPtyAndBroadcast(sessionID, session)
837
838 return session, nil
839} // handleTerminalEvents handles SSE connections for terminal output
840func (s *Server) handleTerminalEvents(w http.ResponseWriter, r *http.Request, sessionID string) {
841 // Check if the session exists, if not, create it
842 s.ptyMutex.Lock()
843 session, exists := s.terminalSessions[sessionID]
844
845 if !exists {
846 // Create a new terminal session
847 var err error
848 session, err = s.createTerminalSession(sessionID)
849 if err != nil {
850 s.ptyMutex.Unlock()
851 http.Error(w, fmt.Sprintf("Failed to create terminal: %v", err), http.StatusInternalServerError)
852 return
853 }
854
855 // Store the new session
856 s.terminalSessions[sessionID] = session
857 }
858 s.ptyMutex.Unlock()
859
860 // Set headers for SSE
861 w.Header().Set("Content-Type", "text/event-stream")
862 w.Header().Set("Cache-Control", "no-cache")
863 w.Header().Set("Connection", "keep-alive")
864 w.Header().Set("Access-Control-Allow-Origin", "*")
865
866 // Create a channel for this client
867 events := make(chan []byte, 4096) // Buffer to prevent blocking
868
869 // Register this client's channel
870 session.eventsClientsMutex.Lock()
871 clientID := session.lastEventClientID + 1
872 session.lastEventClientID = clientID
873 session.eventsClients[events] = true
874 session.eventsClientsMutex.Unlock()
875
876 // When the client disconnects, remove their channel
877 defer func() {
878 session.eventsClientsMutex.Lock()
879 delete(session.eventsClients, events)
880 close(events)
881 session.eventsClientsMutex.Unlock()
882 }()
883
884 // Flush to send headers to client immediately
885 if f, ok := w.(http.Flusher); ok {
886 f.Flush()
887 }
888
889 // Send events to the client as they arrive
890 for {
891 select {
892 case <-r.Context().Done():
893 return
894 case data := <-events:
895 // Format as SSE with base64 encoding
896 fmt.Fprintf(w, "data: %s\n\n", base64.StdEncoding.EncodeToString(data))
897
898 // Flush the data immediately
899 if f, ok := w.(http.Flusher); ok {
900 f.Flush()
901 }
902 }
903 }
904}
905
906// handleTerminalInput processes input to the terminal
907func (s *Server) handleTerminalInput(w http.ResponseWriter, r *http.Request, sessionID string) {
908 // Check if the session exists
909 s.ptyMutex.Lock()
910 session, exists := s.terminalSessions[sessionID]
911 s.ptyMutex.Unlock()
912
913 if !exists {
914 http.Error(w, "Terminal session not found", http.StatusNotFound)
915 return
916 }
917
918 // Read the request body (terminal input or resize command)
919 body, err := io.ReadAll(r.Body)
920 if err != nil {
921 http.Error(w, "Failed to read request body", http.StatusBadRequest)
922 return
923 }
924
925 // Check if it's a resize message
926 if len(body) > 0 && body[0] == '{' {
927 var msg TerminalMessage
928 if err := json.Unmarshal(body, &msg); err == nil && msg.Type == "resize" {
929 if msg.Cols > 0 && msg.Rows > 0 {
930 pty.Setsize(session.pty, &pty.Winsize{
931 Cols: msg.Cols,
932 Rows: msg.Rows,
933 })
934
935 // Respond with success
936 w.WriteHeader(http.StatusOK)
937 return
938 }
939 }
940 }
941
942 // Regular terminal input
943 _, err = session.pty.Write(body)
944 if err != nil {
945 slog.Error("Failed to write to pty", "error", err)
946 http.Error(w, "Failed to write to terminal", http.StatusInternalServerError)
947 return
948 }
949
950 // Respond with success
951 w.WriteHeader(http.StatusOK)
952}
953
954// readFromPtyAndBroadcast reads output from the PTY and broadcasts it to all connected clients
955func (s *Server) readFromPtyAndBroadcast(sessionID string, session *terminalSession) {
956 buf := make([]byte, 4096)
957 defer func() {
958 // Clean up when done
959 s.ptyMutex.Lock()
960 delete(s.terminalSessions, sessionID)
961 s.ptyMutex.Unlock()
962
963 // Close the PTY
964 session.pty.Close()
965
966 // Ensure process is terminated
967 if session.cmd.Process != nil {
968 session.cmd.Process.Signal(syscall.SIGTERM)
969 time.Sleep(100 * time.Millisecond)
970 session.cmd.Process.Kill()
971 }
972
973 // Close all client channels
974 session.eventsClientsMutex.Lock()
975 for ch := range session.eventsClients {
976 delete(session.eventsClients, ch)
977 close(ch)
978 }
979 session.eventsClientsMutex.Unlock()
980 }()
981
982 for {
983 n, err := session.pty.Read(buf)
984 if err != nil {
985 if err != io.EOF {
986 slog.Error("Failed to read from pty", "error", err)
987 }
988 break
989 }
990
991 // Make a copy of the data for each client
992 data := make([]byte, n)
993 copy(data, buf[:n])
994
995 // Broadcast to all connected clients
996 session.eventsClientsMutex.Lock()
997 for ch := range session.eventsClients {
998 // Try to send, but don't block if channel is full
999 select {
1000 case ch <- data:
1001 default:
1002 // Channel is full, drop the message for this client
1003 }
1004 }
1005 session.eventsClientsMutex.Unlock()
1006 }
1007}
1008
1009// getShellPath returns the path to the shell to use
1010func getShellPath() string {
1011 // Try to use the user's preferred shell
1012 shell := os.Getenv("SHELL")
1013 if shell != "" {
1014 return shell
1015 }
1016
1017 // Default to bash on Unix-like systems
1018 if _, err := os.Stat("/bin/bash"); err == nil {
1019 return "/bin/bash"
1020 }
1021
1022 // Fall back to sh
1023 return "/bin/sh"
1024}
1025
1026func initDebugMux() *http.ServeMux {
1027 mux := http.NewServeMux()
Philip Zeyliger8d8b7ac2025-05-21 09:57:23 -07001028 build := "unknown build"
1029 bi, ok := debug.ReadBuildInfo()
1030 if ok {
1031 build = fmt.Sprintf("%s@%v\n", bi.Path, bi.Main.Version)
1032 }
Earl Lee2e463fb2025-04-17 11:22:22 -07001033 mux.HandleFunc("GET /debug/{$}", func(w http.ResponseWriter, r *http.Request) {
1034 w.Header().Set("Content-Type", "text/html; charset=utf-8")
Philip Zeyliger2c4db092025-04-28 16:57:50 -07001035 // TODO: pid is not as useful as "outside pid"
Earl Lee2e463fb2025-04-17 11:22:22 -07001036 fmt.Fprintf(w, `<!doctype html>
1037 <html><head><title>sketch debug</title></head><body>
1038 <h1>sketch debug</h1>
Philip Zeyliger8d8b7ac2025-05-21 09:57:23 -07001039 pid %d<br>
1040 build %s<br>
Earl Lee2e463fb2025-04-17 11:22:22 -07001041 <ul>
Philip Zeyligera14b0182025-06-30 14:31:18 -07001042 <li><a href="pprof/cmdline">pprof/cmdline</a></li>
1043 <li><a href="pprof/profile">pprof/profile</a></li>
1044 <li><a href="pprof/symbol">pprof/symbol</a></li>
1045 <li><a href="pprof/trace">pprof/trace</a></li>
1046 <li><a href="pprof/goroutine?debug=1">pprof/goroutine?debug=1</a></li>
Earl Lee2e463fb2025-04-17 11:22:22 -07001047 </ul>
1048 </body>
1049 </html>
Philip Zeyliger8d8b7ac2025-05-21 09:57:23 -07001050 `, os.Getpid(), build)
Earl Lee2e463fb2025-04-17 11:22:22 -07001051 })
1052 mux.HandleFunc("GET /debug/pprof/", pprof.Index)
1053 mux.HandleFunc("GET /debug/pprof/cmdline", pprof.Cmdline)
1054 mux.HandleFunc("GET /debug/pprof/profile", pprof.Profile)
1055 mux.HandleFunc("GET /debug/pprof/symbol", pprof.Symbol)
1056 mux.HandleFunc("GET /debug/pprof/trace", pprof.Trace)
1057 return mux
1058}
1059
1060// isValidGitSHA validates if a string looks like a valid git SHA hash.
1061// Git SHAs are hexadecimal strings of at least 4 characters but typically 7, 8, or 40 characters.
1062func isValidGitSHA(sha string) bool {
1063 // Git SHA must be a hexadecimal string with at least 4 characters
1064 if len(sha) < 4 || len(sha) > 40 {
1065 return false
1066 }
1067
1068 // Check if the string only contains hexadecimal characters
1069 for _, char := range sha {
1070 if !(char >= '0' && char <= '9') && !(char >= 'a' && char <= 'f') && !(char >= 'A' && char <= 'F') {
1071 return false
1072 }
1073 }
1074
1075 return true
1076}
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001077
1078// /stream?from=N endpoint for Server-Sent Events
1079func (s *Server) handleSSEStream(w http.ResponseWriter, r *http.Request) {
1080 w.Header().Set("Content-Type", "text/event-stream")
1081 w.Header().Set("Cache-Control", "no-cache")
1082 w.Header().Set("Connection", "keep-alive")
1083 w.Header().Set("Access-Control-Allow-Origin", "*")
1084
1085 // Extract the 'from' parameter
1086 fromParam := r.URL.Query().Get("from")
1087 var fromIndex int
1088 var err error
1089 if fromParam != "" {
1090 fromIndex, err = strconv.Atoi(fromParam)
1091 if err != nil {
1092 http.Error(w, "Invalid 'from' parameter", http.StatusBadRequest)
1093 return
1094 }
1095 }
1096
1097 // Ensure 'from' is valid
1098 currentCount := s.agent.MessageCount()
1099 if fromIndex < 0 {
1100 fromIndex = 0
1101 } else if fromIndex > currentCount {
1102 fromIndex = currentCount
1103 }
1104
1105 // Send the current state immediately
1106 state := s.getState()
1107
1108 // Create JSON encoder
1109 encoder := json.NewEncoder(w)
1110
1111 // Send state as an event
1112 fmt.Fprintf(w, "event: state\n")
1113 fmt.Fprintf(w, "data: ")
1114 encoder.Encode(state)
1115 fmt.Fprintf(w, "\n\n")
1116
1117 if f, ok := w.(http.Flusher); ok {
1118 f.Flush()
1119 }
1120
1121 // Create a context for the SSE stream
1122 ctx := r.Context()
1123
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001124 // Setup heartbeat timer
1125 heartbeatTicker := time.NewTicker(45 * time.Second)
1126 defer heartbeatTicker.Stop()
1127
1128 // Create a channel for messages
1129 messageChan := make(chan *loop.AgentMessage, 10)
1130
Philip Zeyligereab12de2025-05-14 02:35:53 +00001131 // Create a channel for state transitions
1132 stateChan := make(chan *loop.StateTransition, 10)
1133
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001134 // Start a goroutine to read messages without blocking the heartbeat
1135 go func() {
Pokey Rule9d7f0cc2025-05-20 11:43:26 +01001136 // Create an iterator to receive new messages as they arrive
1137 iterator := s.agent.NewIterator(ctx, fromIndex) // Start from the requested index
1138 defer iterator.Close()
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001139 defer close(messageChan)
1140 for {
1141 // This can block, but it's in its own goroutine
1142 newMessage := iterator.Next()
1143 if newMessage == nil {
1144 // No message available (likely due to context cancellation)
1145 slog.InfoContext(ctx, "No more messages available, ending message stream")
1146 return
1147 }
1148
1149 select {
1150 case messageChan <- newMessage:
1151 // Message sent to channel
1152 case <-ctx.Done():
1153 // Context cancelled
1154 return
1155 }
1156 }
1157 }()
1158
Philip Zeyligereab12de2025-05-14 02:35:53 +00001159 // Start a goroutine to read state transitions
1160 go func() {
Pokey Rule9d7f0cc2025-05-20 11:43:26 +01001161 // Create an iterator to receive state transitions
1162 stateIterator := s.agent.NewStateTransitionIterator(ctx)
1163 defer stateIterator.Close()
Philip Zeyligereab12de2025-05-14 02:35:53 +00001164 defer close(stateChan)
1165 for {
1166 // This can block, but it's in its own goroutine
1167 newTransition := stateIterator.Next()
1168 if newTransition == nil {
1169 // No transition available (likely due to context cancellation)
1170 slog.InfoContext(ctx, "No more state transitions available, ending state stream")
1171 return
1172 }
1173
1174 select {
1175 case stateChan <- newTransition:
1176 // Transition sent to channel
1177 case <-ctx.Done():
1178 // Context cancelled
1179 return
1180 }
1181 }
1182 }()
1183
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001184 // Stay connected and stream real-time updates
1185 for {
1186 select {
1187 case <-heartbeatTicker.C:
1188 // Send heartbeat event
1189 fmt.Fprintf(w, "event: heartbeat\n")
1190 fmt.Fprintf(w, "data: %d\n\n", time.Now().Unix())
1191
1192 // Flush to send the heartbeat immediately
1193 if f, ok := w.(http.Flusher); ok {
1194 f.Flush()
1195 }
1196
1197 case <-ctx.Done():
1198 // Client disconnected
1199 slog.InfoContext(ctx, "Client disconnected from SSE stream")
1200 return
1201
Philip Zeyligereab12de2025-05-14 02:35:53 +00001202 case _, ok := <-stateChan:
1203 if !ok {
1204 // Channel closed
1205 slog.InfoContext(ctx, "State transition channel closed, ending SSE stream")
1206 return
1207 }
1208
1209 // Get updated state
1210 state = s.getState()
1211
1212 // Send updated state after the state transition
1213 fmt.Fprintf(w, "event: state\n")
1214 fmt.Fprintf(w, "data: ")
1215 encoder.Encode(state)
1216 fmt.Fprintf(w, "\n\n")
1217
1218 // Flush to send the state immediately
1219 if f, ok := w.(http.Flusher); ok {
1220 f.Flush()
1221 }
1222
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001223 case newMessage, ok := <-messageChan:
1224 if !ok {
1225 // Channel closed
1226 slog.InfoContext(ctx, "Message channel closed, ending SSE stream")
1227 return
1228 }
1229
1230 // Send the new message as an event
1231 fmt.Fprintf(w, "event: message\n")
1232 fmt.Fprintf(w, "data: ")
1233 encoder.Encode(newMessage)
1234 fmt.Fprintf(w, "\n\n")
1235
1236 // Get updated state
1237 state = s.getState()
1238
1239 // Send updated state after the message
1240 fmt.Fprintf(w, "event: state\n")
1241 fmt.Fprintf(w, "data: ")
1242 encoder.Encode(state)
1243 fmt.Fprintf(w, "\n\n")
1244
1245 // Flush to send the message and state immediately
1246 if f, ok := w.(http.Flusher); ok {
1247 f.Flush()
1248 }
1249 }
1250 }
1251}
1252
1253// Helper function to get the current state
1254func (s *Server) getState() State {
1255 serverMessageCount := s.agent.MessageCount()
1256 totalUsage := s.agent.TotalUsage()
1257
Philip Zeyliger64f60462025-06-16 13:57:10 -07001258 // Get diff stats
1259 diffAdded, diffRemoved := s.agent.DiffStats()
1260
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001261 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(),
bankseancad67b02025-06-27 21:57:05 +00001280 GitUsername: s.agent.GitUsername(),
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001281 OutstandingLLMCalls: s.agent.OutstandingLLMCallCount(),
1282 OutstandingToolCalls: s.agent.OutstandingToolCalls(),
1283 SessionID: s.agent.SessionID(),
1284 SSHAvailable: s.sshAvailable,
1285 SSHError: s.sshError,
1286 InContainer: s.agent.IsInContainer(),
1287 FirstMessageIndex: s.agent.FirstMessageIndex(),
1288 AgentState: s.agent.CurrentStateName(),
Josh Bleecher Snyder112b9232025-05-23 11:26:33 -07001289 TodoContent: s.agent.CurrentTodoContent(),
Philip Zeyliger0113be52025-06-07 23:53:41 +00001290 SkabandAddr: s.agent.SkabandAddr(),
philip.zeyliger6d3de482025-06-10 19:38:14 -07001291 LinkToGitHub: s.agent.LinkToGitHub(),
philip.zeyliger8773e682025-06-11 21:36:21 -07001292 SSHConnectionString: s.agent.SSHConnectionString(),
Philip Zeyliger64f60462025-06-16 13:57:10 -07001293 DiffLinesAdded: diffAdded,
1294 DiffLinesRemoved: diffRemoved,
Philip Zeyliger5f26a342025-07-04 01:30:29 +00001295 OpenPorts: s.getOpenPorts(),
Philip Zeyliger25f6ff12025-05-02 04:24:10 +00001296 }
1297}
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001298
Philip Zeyliger5f26a342025-07-04 01:30:29 +00001299// getOpenPorts retrieves the current open ports from the agent
1300func (s *Server) getOpenPorts() []Port {
1301 ports := s.agent.GetPorts()
1302 if ports == nil {
1303 return nil
1304 }
1305
1306 result := make([]Port, len(ports))
1307 for i, port := range ports {
1308 result[i] = Port{
1309 Proto: port.Proto,
1310 Port: port.Port,
1311 Process: port.Process,
1312 Pid: port.Pid,
1313 }
1314 }
1315 return result
1316}
1317
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001318func (s *Server) handleGitRawDiff(w http.ResponseWriter, r *http.Request) {
1319 if r.Method != "GET" {
1320 w.WriteHeader(http.StatusMethodNotAllowed)
1321 return
1322 }
1323
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +00001324 // Get the git repository root directory from agent
1325 repoDir := s.agent.RepoRoot()
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001326
1327 // Parse query parameters
1328 query := r.URL.Query()
1329 commit := query.Get("commit")
1330 from := query.Get("from")
1331 to := query.Get("to")
1332
1333 // If commit is specified, use commit^ and commit as from and to
1334 if commit != "" {
1335 from = commit + "^"
1336 to = commit
1337 }
1338
1339 // Check if we have enough parameters
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001340 if from == "" {
1341 http.Error(w, "Missing required parameter: either 'commit' or at least 'from'", http.StatusBadRequest)
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001342 return
1343 }
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001344 // Note: 'to' can be empty to indicate working directory (unstaged changes)
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001345
1346 // Call the git_tools function
1347 diff, err := git_tools.GitRawDiff(repoDir, from, to)
1348 if err != nil {
1349 http.Error(w, fmt.Sprintf("Error getting git diff: %v", err), http.StatusInternalServerError)
1350 return
1351 }
1352
1353 // Return the result as JSON
1354 w.Header().Set("Content-Type", "application/json")
1355 if err := json.NewEncoder(w).Encode(diff); err != nil {
1356 http.Error(w, fmt.Sprintf("Error encoding response: %v", err), http.StatusInternalServerError)
1357 return
1358 }
1359}
1360
1361func (s *Server) handleGitShow(w http.ResponseWriter, r *http.Request) {
1362 if r.Method != "GET" {
1363 w.WriteHeader(http.StatusMethodNotAllowed)
1364 return
1365 }
1366
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +00001367 // Get the git repository root directory from agent
1368 repoDir := s.agent.RepoRoot()
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001369
1370 // Parse query parameters
1371 hash := r.URL.Query().Get("hash")
1372 if hash == "" {
1373 http.Error(w, "Missing required parameter: 'hash'", http.StatusBadRequest)
1374 return
1375 }
1376
1377 // Call the git_tools function
1378 show, err := git_tools.GitShow(repoDir, hash)
1379 if err != nil {
1380 http.Error(w, fmt.Sprintf("Error running git show: %v", err), http.StatusInternalServerError)
1381 return
1382 }
1383
1384 // Create a JSON response
1385 response := map[string]string{
1386 "hash": hash,
1387 "output": show,
1388 }
1389
1390 // Return the result as JSON
1391 w.Header().Set("Content-Type", "application/json")
1392 if err := json.NewEncoder(w).Encode(response); err != nil {
1393 http.Error(w, fmt.Sprintf("Error encoding response: %v", err), http.StatusInternalServerError)
1394 return
1395 }
1396}
1397
1398func (s *Server) handleGitRecentLog(w http.ResponseWriter, r *http.Request) {
1399 if r.Method != "GET" {
1400 w.WriteHeader(http.StatusMethodNotAllowed)
1401 return
1402 }
1403
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +00001404 // Get the git repository root directory and initial commit from agent
1405 repoDir := s.agent.RepoRoot()
Philip Zeyligerd3ac1122025-05-14 02:54:18 +00001406 initialCommit := s.agent.SketchGitBaseRef()
1407
1408 // Call the git_tools function
1409 log, err := git_tools.GitRecentLog(repoDir, initialCommit)
1410 if err != nil {
1411 http.Error(w, fmt.Sprintf("Error getting git log: %v", err), http.StatusInternalServerError)
1412 return
1413 }
1414
1415 // Return the result as JSON
1416 w.Header().Set("Content-Type", "application/json")
1417 if err := json.NewEncoder(w).Encode(log); err != nil {
1418 http.Error(w, fmt.Sprintf("Error encoding response: %v", err), http.StatusInternalServerError)
1419 return
1420 }
1421}
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001422
1423func (s *Server) handleGitCat(w http.ResponseWriter, r *http.Request) {
1424 if r.Method != "GET" {
1425 w.WriteHeader(http.StatusMethodNotAllowed)
1426 return
1427 }
1428
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +00001429 // Get the git repository root directory from agent
1430 repoDir := s.agent.RepoRoot()
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001431
1432 // Parse query parameters
1433 query := r.URL.Query()
1434 path := query.Get("path")
1435
1436 // Check if path is provided
1437 if path == "" {
1438 http.Error(w, "Missing required parameter: path", http.StatusBadRequest)
1439 return
1440 }
1441
1442 // Get file content using GitCat
1443 content, err := git_tools.GitCat(repoDir, path)
Josh Bleecher Snyder5c29b3e2025-07-08 18:07:28 +00001444 if errors.Is(err, os.ErrNotExist) {
1445 w.WriteHeader(http.StatusNoContent)
1446 return
1447 }
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001448 if err != nil {
1449 http.Error(w, fmt.Sprintf("Error reading file: %v", err), http.StatusInternalServerError)
1450 return
1451 }
1452
1453 // Return the content as JSON for consistency with other endpoints
1454 w.Header().Set("Content-Type", "application/json")
1455 if err := json.NewEncoder(w).Encode(map[string]string{"output": content}); err != nil {
1456 http.Error(w, fmt.Sprintf("Error encoding response: %v", err), http.StatusInternalServerError)
1457 return
1458 }
1459}
1460
1461func (s *Server) handleGitSave(w http.ResponseWriter, r *http.Request) {
1462 if r.Method != "POST" {
1463 w.WriteHeader(http.StatusMethodNotAllowed)
1464 return
1465 }
1466
Josh Bleecher Snyderc5848f32025-05-28 18:50:58 +00001467 // Get the git repository root directory from agent
1468 repoDir := s.agent.RepoRoot()
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001469
1470 // Parse request body
1471 var requestBody struct {
1472 Path string `json:"path"`
1473 Content string `json:"content"`
1474 }
1475
1476 if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {
1477 http.Error(w, fmt.Sprintf("Error parsing request body: %v", err), http.StatusBadRequest)
1478 return
1479 }
1480 defer r.Body.Close()
1481
1482 // Check if path is provided
1483 if requestBody.Path == "" {
1484 http.Error(w, "Missing required parameter: path", http.StatusBadRequest)
1485 return
1486 }
1487
1488 // Save file content using GitSaveFile
1489 err := git_tools.GitSaveFile(repoDir, requestBody.Path, requestBody.Content)
1490 if err != nil {
1491 http.Error(w, fmt.Sprintf("Error saving file: %v", err), http.StatusInternalServerError)
1492 return
1493 }
1494
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001495 // Auto-commit the changes
1496 err = git_tools.AutoCommitDiffViewChanges(r.Context(), repoDir, requestBody.Path)
1497 if err != nil {
1498 http.Error(w, fmt.Sprintf("Error auto-committing changes: %v", err), http.StatusInternalServerError)
1499 return
1500 }
1501
1502 // Detect git changes to push and notify user
Philip Zeyliger9bca61e2025-05-22 12:40:06 -07001503 if err = s.agent.DetectGitChanges(r.Context()); err != nil {
1504 http.Error(w, fmt.Sprintf("Error detecting git changes: %v", err), http.StatusInternalServerError)
1505 return
1506 }
Philip Zeyliger75bd37d2025-05-22 18:49:14 +00001507
Philip Zeyliger272a90e2025-05-16 14:49:51 -07001508 // Return simple success response
1509 w.WriteHeader(http.StatusOK)
1510 w.Write([]byte("ok"))
1511}