blob: d83d8cfb4ee589c8b34067f5d001ebd22e4fb34b [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"
Earl Lee2e463fb2025-04-17 11:22:22 -07006 "encoding/base64"
7 "encoding/json"
8 "fmt"
9 "html"
10 "io"
11 "io/fs"
12 "log/slog"
13 "net/http"
14 "net/http/pprof"
15 "os"
16 "os/exec"
17 "strconv"
18 "strings"
19 "sync"
20 "syscall"
21 "time"
22
Philip Zeyliger176de792025-04-21 12:25:18 -070023 "sketch.dev/loop/server/gzhandler"
24
Earl Lee2e463fb2025-04-17 11:22:22 -070025 "github.com/creack/pty"
26 "sketch.dev/ant"
27 "sketch.dev/loop"
28 "sketch.dev/loop/webui"
29)
30
31// terminalSession represents a terminal session with its PTY and the event channel
32type terminalSession struct {
33 pty *os.File
34 eventsClients map[chan []byte]bool
35 lastEventClientID int
36 eventsClientsMutex sync.Mutex
37 cmd *exec.Cmd
38}
39
40// TerminalMessage represents a message sent from the client for terminal resize events
41type TerminalMessage struct {
42 Type string `json:"type"`
43 Cols uint16 `json:"cols"`
44 Rows uint16 `json:"rows"`
45}
46
47// TerminalResponse represents the response for a new terminal creation
48type TerminalResponse struct {
49 SessionID string `json:"sessionId"`
50}
51
Sean McCulloughd9f13372025-04-21 15:08:49 -070052type State struct {
53 MessageCount int `json:"message_count"`
54 TotalUsage *ant.CumulativeUsage `json:"total_usage,omitempty"`
Sean McCulloughd9f13372025-04-21 15:08:49 -070055 InitialCommit string `json:"initial_commit"`
56 Title string `json:"title"`
Philip Zeyligerd1402952025-04-23 03:54:37 +000057 Hostname string `json:"hostname"` // deprecated
58 WorkingDir string `json:"working_dir"` // deprecated
59 OS string `json:"os"` // deprecated
60 GitOrigin string `json:"git_origin,omitempty"`
61
62 HostHostname string `json:"host_hostname,omitempty"`
63 RuntimeHostname string `json:"runtime_hostname,omitempty"`
64 HostOS string `json:"host_os,omitempty"`
65 RuntimeOS string `json:"runtime_os,omitempty"`
66 HostWorkingDir string `json:"host_working_dir,omitempty"`
67 RuntimeWorkingDir string `json:"runtime_working_dir,omitempty"`
Sean McCulloughd9f13372025-04-21 15:08:49 -070068}
69
Sean McCulloughbaa2b592025-04-23 10:40:08 -070070type InitRequest struct {
71 HostAddr string `json:"host_addr"`
72 GitRemoteAddr string `json:"git_remote_addr"`
73 Commit string `json:"commit"`
74 SSHAuthorizedKeys []byte `json:"ssh_authorized_keys"`
75 SSHServerIdentity []byte `json:"ssh_server_identity"`
76}
77
Earl Lee2e463fb2025-04-17 11:22:22 -070078// Server serves sketch HTTP. Server implements http.Handler.
79type Server struct {
80 mux *http.ServeMux
81 agent loop.CodingAgent
82 hostname string
83 logFile *os.File
84 // Mutex to protect terminalSessions
85 ptyMutex sync.Mutex
86 terminalSessions map[string]*terminalSession
87}
88
89func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
90 s.mux.ServeHTTP(w, r)
91}
92
93// New creates a new HTTP server.
94func New(agent loop.CodingAgent, logFile *os.File) (*Server, error) {
95 s := &Server{
96 mux: http.NewServeMux(),
97 agent: agent,
98 hostname: getHostname(),
99 logFile: logFile,
100 terminalSessions: make(map[string]*terminalSession),
101 }
102
103 webBundle, err := webui.Build()
104 if err != nil {
105 return nil, fmt.Errorf("failed to build web bundle, did you run 'go generate sketch.dev/loop/...'?: %w", err)
106 }
107
108 s.mux.HandleFunc("/diff", func(w http.ResponseWriter, r *http.Request) {
109 // Check if a specific commit hash was requested
110 commit := r.URL.Query().Get("commit")
111
112 // Get the diff, optionally for a specific commit
113 var diff string
114 var err error
115 if commit != "" {
116 // Validate the commit hash format
117 if !isValidGitSHA(commit) {
118 http.Error(w, fmt.Sprintf("Invalid git commit SHA format: %s", commit), http.StatusBadRequest)
119 return
120 }
121
122 diff, err = agent.Diff(&commit)
123 } else {
124 diff, err = agent.Diff(nil)
125 }
126
127 if err != nil {
128 http.Error(w, fmt.Sprintf("Error generating diff: %v", err), http.StatusInternalServerError)
129 return
130 }
131
132 w.Header().Set("Content-Type", "text/plain")
133 w.Write([]byte(diff))
134 })
135
136 // Handler for initialization called by host sketch binary when inside docker.
137 s.mux.HandleFunc("/init", func(w http.ResponseWriter, r *http.Request) {
138 defer func() {
139 if err := recover(); err != nil {
140 slog.ErrorContext(r.Context(), "/init panic", slog.Any("recovered_err", err))
141
142 // Return an error response to the client
143 http.Error(w, fmt.Sprintf("panic: %v\n", err), http.StatusInternalServerError)
144 }
145 }()
146
147 if r.Method != "POST" {
148 http.Error(w, "POST required", http.StatusBadRequest)
149 return
150 }
151
152 body, err := io.ReadAll(r.Body)
153 r.Body.Close()
154 if err != nil {
155 http.Error(w, "failed to read request body: "+err.Error(), http.StatusBadRequest)
156 return
157 }
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700158
159 m := &InitRequest{}
160 if err := json.Unmarshal(body, m); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700161 http.Error(w, "bad request body: "+err.Error(), http.StatusBadRequest)
162 return
163 }
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700164
165 // Start the SSH server if the init request included ssh keys.
166 if len(m.SSHAuthorizedKeys) > 0 && len(m.SSHServerIdentity) > 0 {
167 go func() {
168 ctx := context.Background()
169 if err := s.ServeSSH(ctx, m.SSHServerIdentity, m.SSHAuthorizedKeys); err != nil {
170 slog.ErrorContext(r.Context(), "/init ServeSSH", slog.String("err", err.Error()))
171 }
172 }()
173 }
174
Earl Lee2e463fb2025-04-17 11:22:22 -0700175 ini := loop.AgentInit{
176 WorkingDir: "/app",
177 InDocker: true,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700178 Commit: m.Commit,
179 GitRemoteAddr: m.GitRemoteAddr,
180 HostAddr: m.HostAddr,
Earl Lee2e463fb2025-04-17 11:22:22 -0700181 }
182 if err := agent.Init(ini); err != nil {
183 http.Error(w, "init failed: "+err.Error(), http.StatusInternalServerError)
184 return
185 }
186 w.Header().Set("Content-Type", "application/json")
187 io.WriteString(w, "{}\n")
188 })
189
190 // Handler for /messages?start=N&end=M (start/end are optional)
191 s.mux.HandleFunc("/messages", func(w http.ResponseWriter, r *http.Request) {
192 w.Header().Set("Content-Type", "application/json")
193
194 // Extract query parameters for range
195 var start, end int
196 var err error
197
198 currentCount := agent.MessageCount()
199
200 startParam := r.URL.Query().Get("start")
201 if startParam != "" {
202 start, err = strconv.Atoi(startParam)
203 if err != nil {
204 http.Error(w, "Invalid 'start' parameter", http.StatusBadRequest)
205 return
206 }
207 }
208
209 endParam := r.URL.Query().Get("end")
210 if endParam != "" {
211 end, err = strconv.Atoi(endParam)
212 if err != nil {
213 http.Error(w, "Invalid 'end' parameter", http.StatusBadRequest)
214 return
215 }
216 } else {
217 end = currentCount
218 }
219
220 if start < 0 || start > end || end > currentCount {
221 http.Error(w, fmt.Sprintf("Invalid range: start %d end %d currentCount %d", start, end, currentCount), http.StatusBadRequest)
222 return
223 }
224
225 start = max(0, start)
226 end = min(agent.MessageCount(), end)
227 messages := agent.Messages(start, end)
228
229 // Create a JSON encoder with indentation for pretty-printing
230 encoder := json.NewEncoder(w)
231 encoder.SetIndent("", " ") // Two spaces for each indentation level
232
233 err = encoder.Encode(messages)
234 if err != nil {
235 http.Error(w, err.Error(), http.StatusInternalServerError)
236 }
237 })
238
239 // Handler for /logs - displays the contents of the log file
240 s.mux.HandleFunc("/logs", func(w http.ResponseWriter, r *http.Request) {
241 if s.logFile == nil {
242 http.Error(w, "log file not set", http.StatusNotFound)
243 return
244 }
245 logContents, err := os.ReadFile(s.logFile.Name())
246 if err != nil {
247 http.Error(w, "error reading log file: "+err.Error(), http.StatusInternalServerError)
248 return
249 }
250 w.Header().Set("Content-Type", "text/html; charset=utf-8")
251 fmt.Fprintf(w, "<!DOCTYPE html>\n<html>\n<head>\n<title>Sketchy Log File</title>\n</head>\n<body>\n")
252 fmt.Fprintf(w, "<pre>%s</pre>\n", html.EscapeString(string(logContents)))
253 fmt.Fprintf(w, "</body>\n</html>")
254 })
255
256 // Handler for /download - downloads both messages and status as a JSON file
257 s.mux.HandleFunc("/download", func(w http.ResponseWriter, r *http.Request) {
258 // Set headers for file download
259 w.Header().Set("Content-Type", "application/octet-stream")
260
261 // Generate filename with format: sketch-YYYYMMDD-HHMMSS.json
262 timestamp := time.Now().Format("20060102-150405")
263 filename := fmt.Sprintf("sketch-%s.json", timestamp)
264
265 w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename))
266
267 // Get all messages
268 messageCount := agent.MessageCount()
269 messages := agent.Messages(0, messageCount)
270
271 // Get status information (usage and other metadata)
272 totalUsage := agent.TotalUsage()
273 hostname := getHostname()
274 workingDir := getWorkingDir()
275
276 // Create a combined structure with all information
277 downloadData := struct {
278 Messages []loop.AgentMessage `json:"messages"`
279 MessageCount int `json:"message_count"`
280 TotalUsage ant.CumulativeUsage `json:"total_usage"`
281 Hostname string `json:"hostname"`
282 WorkingDir string `json:"working_dir"`
283 DownloadTime string `json:"download_time"`
284 }{
285 Messages: messages,
286 MessageCount: messageCount,
287 TotalUsage: totalUsage,
288 Hostname: hostname,
289 WorkingDir: workingDir,
290 DownloadTime: time.Now().Format(time.RFC3339),
291 }
292
293 // Marshal the JSON with indentation for better readability
294 jsonData, err := json.MarshalIndent(downloadData, "", " ")
295 if err != nil {
296 http.Error(w, err.Error(), http.StatusInternalServerError)
297 return
298 }
299 w.Write(jsonData)
300 })
301
302 // The latter doesn't return until the number of messages has changed (from seen
303 // or from when this was called.)
304 s.mux.HandleFunc("/state", func(w http.ResponseWriter, r *http.Request) {
305 pollParam := r.URL.Query().Get("poll")
306 seenParam := r.URL.Query().Get("seen")
307
308 // Get the client's current message count (if provided)
309 clientMessageCount := -1
310 var err error
311 if seenParam != "" {
312 clientMessageCount, err = strconv.Atoi(seenParam)
313 if err != nil {
314 http.Error(w, "Invalid 'seen' parameter", http.StatusBadRequest)
315 return
316 }
317 }
318
319 serverMessageCount := agent.MessageCount()
320
321 // Let lazy clients not have to specify this.
322 if clientMessageCount == -1 {
323 clientMessageCount = serverMessageCount
324 }
325
326 if pollParam == "true" {
327 ch := make(chan string)
328 go func() {
329 // This is your blocking operation
330 agent.WaitForMessageCount(r.Context(), clientMessageCount)
331 close(ch)
332 }()
333 select {
334 case <-r.Context().Done():
335 slog.DebugContext(r.Context(), "abandoned poll request")
336 return
337 case <-time.After(90 * time.Second):
338 // Let the user call /state again to get the latest to limit how long our long polls hang out.
339 slog.DebugContext(r.Context(), "longish poll request")
340 break
341 case <-ch:
342 break
343 }
344 }
345
346 serverMessageCount = agent.MessageCount()
347 totalUsage := agent.TotalUsage()
348
349 w.Header().Set("Content-Type", "application/json")
350
Sean McCulloughd9f13372025-04-21 15:08:49 -0700351 state := State{
Philip Zeyligerd1402952025-04-23 03:54:37 +0000352 MessageCount: serverMessageCount,
353 TotalUsage: &totalUsage,
354 Hostname: s.hostname,
355 WorkingDir: getWorkingDir(),
356 InitialCommit: agent.InitialCommit(),
357 Title: agent.Title(),
358 OS: agent.OS(),
359 HostHostname: agent.HostHostname(),
360 RuntimeHostname: s.hostname,
361 HostOS: agent.HostOS(),
362 RuntimeOS: agent.OS(),
363 HostWorkingDir: agent.HostWorkingDir(),
364 RuntimeWorkingDir: getWorkingDir(),
365 GitOrigin: agent.GitOrigin(),
Earl Lee2e463fb2025-04-17 11:22:22 -0700366 }
367
368 // Create a JSON encoder with indentation for pretty-printing
369 encoder := json.NewEncoder(w)
370 encoder.SetIndent("", " ") // Two spaces for each indentation level
371
372 err = encoder.Encode(state)
373 if err != nil {
374 http.Error(w, err.Error(), http.StatusInternalServerError)
375 }
376 })
377
Philip Zeyliger176de792025-04-21 12:25:18 -0700378 s.mux.Handle("/static/", http.StripPrefix("/static/", gzhandler.New(webBundle)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700379
380 // Terminal WebSocket handler
381 // Terminal endpoints - predefined terminals 1-9
382 // TODO: The UI doesn't actually know how to use terminals 2-9!
383 s.mux.HandleFunc("/terminal/events/", func(w http.ResponseWriter, r *http.Request) {
384 if r.Method != http.MethodGet {
385 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
386 return
387 }
388 pathParts := strings.Split(r.URL.Path, "/")
389 if len(pathParts) < 4 {
390 http.Error(w, "Invalid terminal ID", http.StatusBadRequest)
391 return
392 }
393
394 sessionID := pathParts[3]
395 // Validate that the terminal ID is between 1-9
396 if len(sessionID) != 1 || sessionID[0] < '1' || sessionID[0] > '9' {
397 http.Error(w, "Terminal ID must be between 1 and 9", http.StatusBadRequest)
398 return
399 }
400
401 s.handleTerminalEvents(w, r, sessionID)
402 })
403
404 s.mux.HandleFunc("/terminal/input/", func(w http.ResponseWriter, r *http.Request) {
405 if r.Method != http.MethodPost {
406 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
407 return
408 }
409 pathParts := strings.Split(r.URL.Path, "/")
410 if len(pathParts) < 4 {
411 http.Error(w, "Invalid terminal ID", http.StatusBadRequest)
412 return
413 }
414 sessionID := pathParts[3]
415 s.handleTerminalInput(w, r, sessionID)
416 })
417
418 s.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
Sean McCullough86b56862025-04-18 13:04:03 -0700419 // Serve the sketch-app-shell.html file directly from the embedded filesystem
420 data, err := fs.ReadFile(webBundle, "sketch-app-shell.html")
Earl Lee2e463fb2025-04-17 11:22:22 -0700421 if err != nil {
422 http.Error(w, "File not found", http.StatusNotFound)
423 return
424 }
425 w.Header().Set("Content-Type", "text/html")
426 w.Write(data)
427 })
428
429 // Handler for POST /chat
430 s.mux.HandleFunc("/chat", func(w http.ResponseWriter, r *http.Request) {
431 if r.Method != http.MethodPost {
432 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
433 return
434 }
435
436 // Parse the request body
437 var requestBody struct {
438 Message string `json:"message"`
439 }
440
441 decoder := json.NewDecoder(r.Body)
442 if err := decoder.Decode(&requestBody); err != nil {
443 http.Error(w, "Invalid request body: "+err.Error(), http.StatusBadRequest)
444 return
445 }
446 defer r.Body.Close()
447
448 if requestBody.Message == "" {
449 http.Error(w, "Message cannot be empty", http.StatusBadRequest)
450 return
451 }
452
453 agent.UserMessage(r.Context(), requestBody.Message)
454
455 w.WriteHeader(http.StatusOK)
456 })
457
458 // Handler for /cancel - cancels the current inner loop in progress
459 s.mux.HandleFunc("/cancel", func(w http.ResponseWriter, r *http.Request) {
460 if r.Method != http.MethodPost {
461 http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
462 return
463 }
464
465 // Parse the request body (optional)
466 var requestBody struct {
467 Reason string `json:"reason"`
468 ToolCallID string `json:"tool_call_id"`
469 }
470
471 decoder := json.NewDecoder(r.Body)
472 if err := decoder.Decode(&requestBody); err != nil && err != io.EOF {
473 http.Error(w, "Invalid request body: "+err.Error(), http.StatusBadRequest)
474 return
475 }
476 defer r.Body.Close()
477
478 cancelReason := "user requested cancellation"
479 if requestBody.Reason != "" {
480 cancelReason = requestBody.Reason
481 }
482
483 if requestBody.ToolCallID != "" {
484 err := agent.CancelToolUse(requestBody.ToolCallID, fmt.Errorf("%s", cancelReason))
485 if err != nil {
486 http.Error(w, err.Error(), http.StatusBadRequest)
487 return
488 }
489 // Return a success response
490 w.Header().Set("Content-Type", "application/json")
491 json.NewEncoder(w).Encode(map[string]string{
492 "status": "cancelled",
493 "too_use_id": requestBody.ToolCallID,
494 "reason": cancelReason})
495 return
496 }
497 // Call the CancelInnerLoop method
498 agent.CancelInnerLoop(fmt.Errorf("%s", cancelReason))
499 // Return a success response
500 w.Header().Set("Content-Type", "application/json")
501 json.NewEncoder(w).Encode(map[string]string{"status": "cancelled", "reason": cancelReason})
502 })
503
504 debugMux := initDebugMux()
505 s.mux.HandleFunc("/debug/", func(w http.ResponseWriter, r *http.Request) {
506 debugMux.ServeHTTP(w, r)
507 })
508
509 return s, nil
510}
511
512// Utility functions
513func getHostname() string {
514 hostname, err := os.Hostname()
515 if err != nil {
516 return "unknown"
517 }
518 return hostname
519}
520
521func getWorkingDir() string {
522 wd, err := os.Getwd()
523 if err != nil {
524 return "unknown"
525 }
526 return wd
527}
528
529// createTerminalSession creates a new terminal session with the given ID
530func (s *Server) createTerminalSession(sessionID string) (*terminalSession, error) {
531 // Start a new shell process
532 shellPath := getShellPath()
533 cmd := exec.Command(shellPath)
534
535 // Get working directory from the agent if possible
536 workDir := getWorkingDir()
537 cmd.Dir = workDir
538
539 // Set up environment
540 cmd.Env = append(os.Environ(), "TERM=xterm-256color")
541
542 // Start the command with a pty
543 ptmx, err := pty.Start(cmd)
544 if err != nil {
545 slog.Error("Failed to start pty", "error", err)
546 return nil, err
547 }
548
549 // Create the terminal session
550 session := &terminalSession{
551 pty: ptmx,
552 eventsClients: make(map[chan []byte]bool),
553 cmd: cmd,
554 }
555
556 // Start goroutine to read from pty and broadcast to all connected SSE clients
557 go s.readFromPtyAndBroadcast(sessionID, session)
558
559 return session, nil
560} // handleTerminalEvents handles SSE connections for terminal output
561func (s *Server) handleTerminalEvents(w http.ResponseWriter, r *http.Request, sessionID string) {
562 // Check if the session exists, if not, create it
563 s.ptyMutex.Lock()
564 session, exists := s.terminalSessions[sessionID]
565
566 if !exists {
567 // Create a new terminal session
568 var err error
569 session, err = s.createTerminalSession(sessionID)
570 if err != nil {
571 s.ptyMutex.Unlock()
572 http.Error(w, fmt.Sprintf("Failed to create terminal: %v", err), http.StatusInternalServerError)
573 return
574 }
575
576 // Store the new session
577 s.terminalSessions[sessionID] = session
578 }
579 s.ptyMutex.Unlock()
580
581 // Set headers for SSE
582 w.Header().Set("Content-Type", "text/event-stream")
583 w.Header().Set("Cache-Control", "no-cache")
584 w.Header().Set("Connection", "keep-alive")
585 w.Header().Set("Access-Control-Allow-Origin", "*")
586
587 // Create a channel for this client
588 events := make(chan []byte, 4096) // Buffer to prevent blocking
589
590 // Register this client's channel
591 session.eventsClientsMutex.Lock()
592 clientID := session.lastEventClientID + 1
593 session.lastEventClientID = clientID
594 session.eventsClients[events] = true
595 session.eventsClientsMutex.Unlock()
596
597 // When the client disconnects, remove their channel
598 defer func() {
599 session.eventsClientsMutex.Lock()
600 delete(session.eventsClients, events)
601 close(events)
602 session.eventsClientsMutex.Unlock()
603 }()
604
605 // Flush to send headers to client immediately
606 if f, ok := w.(http.Flusher); ok {
607 f.Flush()
608 }
609
610 // Send events to the client as they arrive
611 for {
612 select {
613 case <-r.Context().Done():
614 return
615 case data := <-events:
616 // Format as SSE with base64 encoding
617 fmt.Fprintf(w, "data: %s\n\n", base64.StdEncoding.EncodeToString(data))
618
619 // Flush the data immediately
620 if f, ok := w.(http.Flusher); ok {
621 f.Flush()
622 }
623 }
624 }
625}
626
627// handleTerminalInput processes input to the terminal
628func (s *Server) handleTerminalInput(w http.ResponseWriter, r *http.Request, sessionID string) {
629 // Check if the session exists
630 s.ptyMutex.Lock()
631 session, exists := s.terminalSessions[sessionID]
632 s.ptyMutex.Unlock()
633
634 if !exists {
635 http.Error(w, "Terminal session not found", http.StatusNotFound)
636 return
637 }
638
639 // Read the request body (terminal input or resize command)
640 body, err := io.ReadAll(r.Body)
641 if err != nil {
642 http.Error(w, "Failed to read request body", http.StatusBadRequest)
643 return
644 }
645
646 // Check if it's a resize message
647 if len(body) > 0 && body[0] == '{' {
648 var msg TerminalMessage
649 if err := json.Unmarshal(body, &msg); err == nil && msg.Type == "resize" {
650 if msg.Cols > 0 && msg.Rows > 0 {
651 pty.Setsize(session.pty, &pty.Winsize{
652 Cols: msg.Cols,
653 Rows: msg.Rows,
654 })
655
656 // Respond with success
657 w.WriteHeader(http.StatusOK)
658 return
659 }
660 }
661 }
662
663 // Regular terminal input
664 _, err = session.pty.Write(body)
665 if err != nil {
666 slog.Error("Failed to write to pty", "error", err)
667 http.Error(w, "Failed to write to terminal", http.StatusInternalServerError)
668 return
669 }
670
671 // Respond with success
672 w.WriteHeader(http.StatusOK)
673}
674
675// readFromPtyAndBroadcast reads output from the PTY and broadcasts it to all connected clients
676func (s *Server) readFromPtyAndBroadcast(sessionID string, session *terminalSession) {
677 buf := make([]byte, 4096)
678 defer func() {
679 // Clean up when done
680 s.ptyMutex.Lock()
681 delete(s.terminalSessions, sessionID)
682 s.ptyMutex.Unlock()
683
684 // Close the PTY
685 session.pty.Close()
686
687 // Ensure process is terminated
688 if session.cmd.Process != nil {
689 session.cmd.Process.Signal(syscall.SIGTERM)
690 time.Sleep(100 * time.Millisecond)
691 session.cmd.Process.Kill()
692 }
693
694 // Close all client channels
695 session.eventsClientsMutex.Lock()
696 for ch := range session.eventsClients {
697 delete(session.eventsClients, ch)
698 close(ch)
699 }
700 session.eventsClientsMutex.Unlock()
701 }()
702
703 for {
704 n, err := session.pty.Read(buf)
705 if err != nil {
706 if err != io.EOF {
707 slog.Error("Failed to read from pty", "error", err)
708 }
709 break
710 }
711
712 // Make a copy of the data for each client
713 data := make([]byte, n)
714 copy(data, buf[:n])
715
716 // Broadcast to all connected clients
717 session.eventsClientsMutex.Lock()
718 for ch := range session.eventsClients {
719 // Try to send, but don't block if channel is full
720 select {
721 case ch <- data:
722 default:
723 // Channel is full, drop the message for this client
724 }
725 }
726 session.eventsClientsMutex.Unlock()
727 }
728}
729
730// getShellPath returns the path to the shell to use
731func getShellPath() string {
732 // Try to use the user's preferred shell
733 shell := os.Getenv("SHELL")
734 if shell != "" {
735 return shell
736 }
737
738 // Default to bash on Unix-like systems
739 if _, err := os.Stat("/bin/bash"); err == nil {
740 return "/bin/bash"
741 }
742
743 // Fall back to sh
744 return "/bin/sh"
745}
746
747func initDebugMux() *http.ServeMux {
748 mux := http.NewServeMux()
749 mux.HandleFunc("GET /debug/{$}", func(w http.ResponseWriter, r *http.Request) {
750 w.Header().Set("Content-Type", "text/html; charset=utf-8")
751 fmt.Fprintf(w, `<!doctype html>
752 <html><head><title>sketch debug</title></head><body>
753 <h1>sketch debug</h1>
754 <ul>
755 <li><a href="/debug/pprof/cmdline">pprof/cmdline</a></li>
756 <li><a href="/debug/pprof/profile">pprof/profile</a></li>
757 <li><a href="/debug/pprof/symbol">pprof/symbol</a></li>
758 <li><a href="/debug/pprof/trace">pprof/trace</a></li>
759 <li><a href="/debug/pprof/goroutine?debug=1">pprof/goroutine?debug=1</a></li>
760 <li><a href="/debug/metrics">metrics</a></li>
761 </ul>
762 </body>
763 </html>
764 `)
765 })
766 mux.HandleFunc("GET /debug/pprof/", pprof.Index)
767 mux.HandleFunc("GET /debug/pprof/cmdline", pprof.Cmdline)
768 mux.HandleFunc("GET /debug/pprof/profile", pprof.Profile)
769 mux.HandleFunc("GET /debug/pprof/symbol", pprof.Symbol)
770 mux.HandleFunc("GET /debug/pprof/trace", pprof.Trace)
771 return mux
772}
773
774// isValidGitSHA validates if a string looks like a valid git SHA hash.
775// Git SHAs are hexadecimal strings of at least 4 characters but typically 7, 8, or 40 characters.
776func isValidGitSHA(sha string) bool {
777 // Git SHA must be a hexadecimal string with at least 4 characters
778 if len(sha) < 4 || len(sha) > 40 {
779 return false
780 }
781
782 // Check if the string only contains hexadecimal characters
783 for _, char := range sha {
784 if !(char >= '0' && char <= '9') && !(char >= 'a' && char <= 'f') && !(char >= 'A' && char <= 'F') {
785 return false
786 }
787 }
788
789 return true
790}