blob: c17093ad1d8331d3d430b7fd02515d51eb7513ec [file] [log] [blame]
Earl Lee2e463fb2025-04-17 11:22:22 -07001// Package dockerimg
2package dockerimg
3
4import (
5 "bytes"
6 "context"
Philip Zeyliger5e227dd2025-04-21 15:55:29 -07007 "crypto/rand"
Earl Lee2e463fb2025-04-17 11:22:22 -07008 "crypto/sha256"
9 "encoding/hex"
10 "encoding/json"
11 "fmt"
12 "io"
13 "log/slog"
14 "net"
15 "net/http"
16 "os"
17 "os/exec"
18 "path/filepath"
19 "runtime"
20 "strings"
Josh Bleecher Snyder99570462025-05-05 10:26:14 -070021 "sync/atomic"
Earl Lee2e463fb2025-04-17 11:22:22 -070022 "time"
23
Sean McCullough7013e9e2025-05-14 02:03:58 +000024 "golang.org/x/crypto/ssh"
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +000025 "sketch.dev/browser"
Kilian Lackhove23772f42025-06-18 20:28:58 +020026 "sketch.dev/llm"
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070027 "sketch.dev/llm/ant"
Kilian Lackhove23772f42025-06-18 20:28:58 +020028 "sketch.dev/llm/gem"
Sean McCulloughbaa2b592025-04-23 10:40:08 -070029 "sketch.dev/loop/server"
Earl Lee2e463fb2025-04-17 11:22:22 -070030 "sketch.dev/skribe"
Philip Zeyliger5d6af872025-04-23 19:48:34 -070031 "sketch.dev/webui"
Earl Lee2e463fb2025-04-17 11:22:22 -070032)
33
34// ContainerConfig holds all configuration for launching a container
35type ContainerConfig struct {
36 // SessionID is the unique identifier for this session
37 SessionID string
38
39 // LocalAddr is the initial address to use (though it may be overwritten later)
40 LocalAddr string
41
42 // SkabandAddr is the address of the skaband service if available
43 SkabandAddr string
44
David Crawshaw5a7b3692025-05-05 16:49:15 -070045 // Model is the name of the LLM model to use.
46 Model string
Earl Lee2e463fb2025-04-17 11:22:22 -070047
David Crawshaw5a7b3692025-05-05 16:49:15 -070048 // ModelURL is the URL of the LLM service.
49 ModelURL string
50
51 // ModelAPIKey is the API key for LLM service.
52 ModelAPIKey string
Earl Lee2e463fb2025-04-17 11:22:22 -070053
54 // Path is the local filesystem path to use
55 Path string
56
57 // GitUsername is the username to use for git operations
58 GitUsername string
59
60 // GitEmail is the email to use for git operations
61 GitEmail string
62
63 // OpenBrowser determines whether to open a browser automatically
64 OpenBrowser bool
65
66 // NoCleanup prevents container cleanup when set to true
67 NoCleanup bool
68
69 // ForceRebuild forces rebuilding of the Docker image even if it exists
70 ForceRebuild bool
71
72 // Host directory to copy container logs into, if not set to ""
73 ContainerLogDest string
74
75 // Path to pre-built linux sketch binary, or build a new one if set to ""
76 SketchBinaryLinux string
77
78 // Sketch client public key.
79 SketchPubKey string
Philip Zeyligerd1402952025-04-23 03:54:37 +000080
Sean McCulloughbaa2b592025-04-23 10:40:08 -070081 // Host port for the container's ssh server
82 SSHPort int
83
Philip Zeyliger18532b22025-04-23 21:11:46 +000084 // Outside information to pass to the container
85 OutsideHostname string
86 OutsideOS string
87 OutsideWorkingDir string
Philip Zeyligerb74c4f62025-04-25 19:18:49 -070088
Pokey Rule0dcebe12025-04-28 14:51:04 +010089 // If true, exit after the first turn
90 OneShot bool
91
92 // Initial prompt
93 Prompt string
Philip Zeyliger1b47aa22025-04-28 19:25:38 +000094
David Crawshawb5f6a002025-05-05 08:27:16 -070095 // Verbose enables verbose output
96 Verbose bool
Philip Zeyliger1dc21372025-05-05 19:54:44 +000097
98 // DockerArgs are additional arguments to pass to the docker create command
99 DockerArgs string
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000100
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000101 // Mounts specifies volumes to mount in the container in format /path/on/host:/path/in/container
102 Mounts []string
103
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000104 // ExperimentFlag contains the experimental features to enable
105 ExperimentFlag string
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700106
107 // TermUI enables terminal UI
108 TermUI bool
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700109
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000110 // Budget configuration
Philip Zeyligere6c294d2025-06-04 16:55:21 +0000111 MaxDollars float64
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000112
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700113 GitRemoteUrl string
114
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000115 // Upstream branch for git work
116 Upstream string
117
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700118 // Commit hash to checkout from GetRemoteUrl
119 Commit string
120
121 // Outtie's HTTP server
122 OutsideHTTP string
Philip Zeyligerbe7802a2025-06-04 20:15:25 +0000123
124 // Prefix for git branches created by sketch
125 BranchPrefix string
philip.zeyliger6d3de482025-06-10 19:38:14 -0700126
127 // LinkToGitHub enables GitHub branch linking in UI
128 LinkToGitHub bool
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700129
130 // SubtraceToken enables running sketch under subtrace.dev (development only)
131 SubtraceToken string
Philip Zeyliger194bfa82025-06-24 06:03:06 -0700132
133 // MCPServers contains MCP server configurations
134 MCPServers []string
Earl Lee2e463fb2025-04-17 11:22:22 -0700135}
136
137// LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it.
138// It writes status to stdout.
David Crawshawb5f6a002025-05-05 08:27:16 -0700139func LaunchContainer(ctx context.Context, config ContainerConfig) error {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700140 slog.Debug("Container Config", slog.String("config", fmt.Sprintf("%+v", config)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700141 if _, err := exec.LookPath("docker"); err != nil {
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700142 if runtime.GOOS == "darwin" {
143 return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start")
144 } else {
145 return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)")
146 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700147 }
148
149 if out, err := combinedOutput(ctx, "docker", "ps"); err != nil {
150 // `docker ps` provides a good error message here that can be
151 // easily chatgpt'ed by users, so send it to the user as-is:
152 // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
153 return fmt.Errorf("docker ps: %s (%w)", out, err)
154 }
155
156 _, hostPort, err := net.SplitHostPort(config.LocalAddr)
157 if err != nil {
158 return err
159 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700160 gitRoot, err := findGitRoot(ctx, config.Path)
161 if err != nil {
162 return err
163 }
Philip Zeyligerd6d12d12025-05-19 19:19:21 -0700164 err = checkForEmptyGitRepo(ctx, config.Path)
165 if err != nil {
166 return err
167 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700168
David Crawshaw5a7b3692025-05-05 16:49:15 -0700169 imgName, err := findOrBuildDockerImage(ctx, config.Path, gitRoot, config.Model, config.ModelURL, config.ModelAPIKey, config.ForceRebuild, config.Verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700170 if err != nil {
171 return err
172 }
173
174 linuxSketchBin := config.SketchBinaryLinux
175 if linuxSketchBin == "" {
David Crawshawb5f6a002025-05-05 08:27:16 -0700176 linuxSketchBin, err = buildLinuxSketchBin(ctx)
Earl Lee2e463fb2025-04-17 11:22:22 -0700177 if err != nil {
178 return err
179 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700180 }
181
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000182 cntrName := "sketch-" + config.SessionID
Earl Lee2e463fb2025-04-17 11:22:22 -0700183 defer func() {
184 if config.NoCleanup {
185 return
186 }
187 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
188 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
189 _ = out
190 }
191 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
192 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
193 _ = out
194 }
195 }()
196
197 // errCh receives errors from operations that this function calls in separate goroutines.
198 errCh := make(chan error)
199
200 // Start the git server
201 gitSrv, err := newGitServer(gitRoot)
202 if err != nil {
203 return fmt.Errorf("failed to start git server: %w", err)
204 }
205 defer gitSrv.shutdown(ctx)
206
207 go func() {
208 errCh <- gitSrv.serve(ctx)
209 }()
210
211 // Get the current host git commit
212 var commit string
Philip Zeyligera347b172025-06-04 16:18:57 +0000213 if out, err := combinedOutput(ctx, "git", "rev-parse", "HEAD"); err != nil {
214 return fmt.Errorf("git rev-parse HEAD: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700215 } else {
216 commit = strings.TrimSpace(string(out))
217 }
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000218
219 var upstream string
220 if out, err := combinedOutput(ctx, "git", "branch", "--show-current"); err != nil {
221 slog.DebugContext(ctx, "git branch --show-current failed (continuing)", "error", err)
222 } else {
223 upstream = strings.TrimSpace(string(out))
224 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700225 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
226 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
227 }
228
229 relPath, err := filepath.Rel(gitRoot, config.Path)
230 if err != nil {
231 return err
232 }
233
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700234 config.OutsideHTTP = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitSrv.pass, gitSrv.gitPort)
235 config.GitRemoteUrl = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitSrv.pass, gitSrv.gitPort)
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000236 config.Upstream = upstream
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700237 config.Commit = commit
238
Earl Lee2e463fb2025-04-17 11:22:22 -0700239 // Create the sketch container
240 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000241 return fmt.Errorf("failed to create docker container: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700242 }
243
244 // Copy the sketch linux binary into the container
245 if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil {
246 return fmt.Errorf("docker cp: %s, %w", out, err)
247 }
Sean McCulloughf5bb3d32025-04-18 10:47:59 -0700248
249 // Make sure that the webui is built so we can copy the results to the container.
250 _, err = webui.Build()
251 if err != nil {
252 return fmt.Errorf("failed to build webui: %w", err)
253 }
254
David Crawshaw8bff16a2025-04-18 01:16:49 -0700255 webuiZipPath, err := webui.ZipPath()
256 if err != nil {
257 return err
258 }
259 if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil {
260 return fmt.Errorf("docker cp: %s, %w", out, err)
261 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700262
David Crawshaw53786ef2025-04-24 12:52:51 -0700263 fmt.Printf("📦 running in container %s\n", cntrName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700264
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700265 // Setup subtrace if token is provided (development only) - after container creation, before start
266 if config.SubtraceToken != "" {
267 fmt.Println("🔍 Setting up subtrace (development only)")
268 if err := setupSubtraceBeforeStart(ctx, cntrName, config.SubtraceToken); err != nil {
269 return fmt.Errorf("failed to setup subtrace: %w", err)
270 }
271 }
272
Earl Lee2e463fb2025-04-17 11:22:22 -0700273 // Start the sketch container
274 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
275 return fmt.Errorf("docker start: %s, %w", out, err)
276 }
277
278 // Copies structured logs from the container to the host.
279 copyLogs := func() {
280 if config.ContainerLogDest == "" {
281 return
282 }
283 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
284 if err != nil {
285 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
286 return
287 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700288 prefix := []byte("structured logs:")
289 for line := range bytes.Lines(out) {
290 rest, ok := bytes.CutPrefix(line, prefix)
291 if !ok {
Earl Lee2e463fb2025-04-17 11:22:22 -0700292 continue
293 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700294 logFile := string(bytes.TrimSpace(rest))
Earl Lee2e463fb2025-04-17 11:22:22 -0700295 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
296 logFileName := filepath.Base(logFile)
297 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
298 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
299 if err != nil {
300 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
301 }
302 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
303 }
304 }
305
306 // NOTE: we want to see what the internal sketch binary prints
307 // regardless of the setting of the verbosity flag on the external
308 // binary, so reading "docker logs", which is the stdout/stderr of
309 // the internal binary is not conditional on the verbose flag.
310 appendInternalErr := func(err error) error {
311 if err == nil {
312 return nil
313 }
314 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000315 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700316 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
317 }
318 out = bytes.TrimSpace(out)
319 if len(out) > 0 {
320 return fmt.Errorf("docker logs: %s;\n%w", out, err)
321 }
322 return err
323 }
324
325 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700326 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700327 if err != nil {
328 return appendInternalErr(err)
329 }
330
Philip Zeyliger00442412025-05-14 11:03:23 -0700331 if config.Verbose {
332 fmt.Fprintf(os.Stderr, "Host web server: http://%s/\n", localAddr)
333 }
334
Sean McCulloughae3480f2025-04-23 15:28:20 -0700335 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
336 if err != nil {
337 return appendInternalErr(err)
338 }
339 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
340 if err != nil {
David Crawshawb5f6a002025-05-05 08:27:16 -0700341 return appendInternalErr(fmt.Errorf("failed to split ssh host and port: %w", err))
Sean McCulloughae3480f2025-04-23 15:28:20 -0700342 }
Sean McCullough4854c652025-04-24 18:37:02 -0700343
Sean McCullough7013e9e2025-05-14 02:03:58 +0000344 var sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate []byte
Sean McCullough4854c652025-04-24 18:37:02 -0700345
banksean29d689f2025-06-23 15:41:26 +0000346 cst, err := NewLocalSSHimmer(cntrName, sshHost, sshPort)
Sean McCullough078e85a2025-05-08 17:28:34 -0700347 if err != nil {
348 return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err))
349 }
350
351 sshErr := CheckSSHReachability(cntrName)
Sean McCullough15c95282025-05-08 16:48:38 -0700352 sshAvailable := false
353 sshErrMsg := ""
354 if sshErr != nil {
355 fmt.Println(sshErr.Error())
356 sshErrMsg = sshErr.Error()
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700357 // continue - ssh config is not required for the rest of sketch to function locally.
358 } else {
Sean McCullough15c95282025-05-08 16:48:38 -0700359 sshAvailable = true
Sean McCulloughea3fc202025-04-28 12:53:37 -0700360 // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find:
361 // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700362 fmt.Printf(`Connect to this container via any of these methods:
Sean McCullough4854c652025-04-24 18:37:02 -0700363🖥️ ssh %s
364🖥️ code --remote ssh-remote+root@%s /app -n
Sean McCulloughea3fc202025-04-28 12:53:37 -0700365🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank
Sean McCullough4854c652025-04-24 18:37:02 -0700366`, cntrName, cntrName, cntrName)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700367 sshUserIdentity = cst.userIdentity
368 sshServerIdentity = cst.serverIdentity
Sean McCullough7013e9e2025-05-14 02:03:58 +0000369
370 // Get the Container CA public key for mutual auth
371 if cst.containerCAPublicKey != nil {
372 containerCAPublicKey = ssh.MarshalAuthorizedKey(cst.containerCAPublicKey)
373 fmt.Println("🔒 SSH Mutual Authentication enabled (container will verify host)")
374 }
375
376 // Get the host certificate for mutual auth
377 hostCertificate = cst.hostCertificate
378
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700379 defer func() {
380 if err := cst.Cleanup(); err != nil {
381 appendInternalErr(err)
382 }
383 }()
384 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700385
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700386 // Tell the sketch container to Init(), which starts the SSH server
387 // and checks out the right commit.
388 // TODO: I'm trying to move as much configuration as possible into the command-line
389 // arguments to avoid splitting them up. "localAddr" is the only difficult one:
390 // we run (effectively) "docker run -p 0:80 image sketch -flags" and you can't
391 // get the port Docker chose until after the process starts. The SSH config is
392 // mostly available ahead of time, but whether it works ("sshAvailable"/"sshErrMsg")
393 // may also empirically need to be done after the SSH server is up and running.
Earl Lee2e463fb2025-04-17 11:22:22 -0700394 go func() {
395 // TODO: Why is this called in a goroutine? I have found that when I pull this out
396 // of the goroutine and call it inline, then the terminal UI clears itself and all
397 // the scrollback (which is not good, but also not fatal). I can't see why it does this
398 // though, since none of the calls in postContainerInitConfig obviously write to stdout
399 // or stderr.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700400 if err := postContainerInitConfig(ctx, localAddr, sshAvailable, sshErrMsg, sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700401 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
402 errCh <- appendInternalErr(err)
403 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700404
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700405 // We open the browser after the init config because the above waits for the web server to be serving.
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700406 ps1URL := "http://" + localAddr
407 if config.SkabandAddr != "" {
408 ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700409 }
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700410 if config.OpenBrowser {
411 browser.Open(ps1URL)
412 }
413 gitSrv.ps1URL.Store(&ps1URL)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700414 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700415
Sean McCullough138ec242025-06-02 22:42:06 +0000416 // Start automatic port tunneling if SSH is available
417 if sshAvailable {
418 go func() {
419 containerURL := "http://" + localAddr
420 tunnelManager := NewTunnelManager(containerURL, cntrName, 10) // Allow up to 10 concurrent tunnels
421 tunnelManager.Start(ctx)
422 slog.InfoContext(ctx, "Started automatic port tunnel manager", "container", cntrName)
423 }()
424 }
425
Earl Lee2e463fb2025-04-17 11:22:22 -0700426 go func() {
427 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
428 cmd.Stdin = os.Stdin
429 cmd.Stdout = os.Stdout
430 cmd.Stderr = os.Stderr
431 errCh <- run(ctx, "docker attach", cmd)
432 }()
433
434 defer copyLogs()
435
436 for {
437 select {
438 case <-ctx.Done():
439 return ctx.Err()
440 case err := <-errCh:
441 if err != nil {
442 return appendInternalErr(fmt.Errorf("container process: %w", err))
443 }
444 return nil
445 }
446 }
447}
448
449func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
450 cmd := exec.CommandContext(ctx, cmdName, args...)
Earl Lee2e463fb2025-04-17 11:22:22 -0700451 start := time.Now()
452
453 out, err := cmd.CombinedOutput()
454 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700455 slog.ErrorContext(ctx, cmdName, slog.Duration("elapsed", time.Since(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
Earl Lee2e463fb2025-04-17 11:22:22 -0700456 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700457 slog.DebugContext(ctx, cmdName, slog.Duration("elapsed", time.Since(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
Earl Lee2e463fb2025-04-17 11:22:22 -0700458 }
459 return out, err
460}
461
462func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
463 start := time.Now()
464 err := cmd.Run()
465 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700466 slog.ErrorContext(ctx, cmdName, slog.Duration("elapsed", time.Since(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
Earl Lee2e463fb2025-04-17 11:22:22 -0700467 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700468 slog.DebugContext(ctx, cmdName, slog.Duration("elapsed", time.Since(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
Earl Lee2e463fb2025-04-17 11:22:22 -0700469 }
470 return err
471}
472
473type gitServer struct {
474 gitLn net.Listener
475 gitPort string
476 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700477 pass string
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700478 ps1URL atomic.Pointer[string]
Earl Lee2e463fb2025-04-17 11:22:22 -0700479}
480
481func (gs *gitServer) shutdown(ctx context.Context) {
482 gs.srv.Shutdown(ctx)
483 gs.gitLn.Close()
484}
485
486// Serve a git remote from the host for the container to fetch from and push to.
487func (gs *gitServer) serve(ctx context.Context) error {
488 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
489 return gs.srv.Serve(gs.gitLn)
490}
491
492func newGitServer(gitRoot string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700493 ret := &gitServer{
494 pass: rand.Text(),
495 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700496
Earl Lee2e463fb2025-04-17 11:22:22 -0700497 gitLn, err := net.Listen("tcp4", ":0")
498 if err != nil {
499 return nil, fmt.Errorf("git listen: %w", err)
500 }
501 ret.gitLn = gitLn
502
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700503 browserC := make(chan bool, 1) // channel of browser open requests
504
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000505 go func() {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700506 for range browserC {
507 browser.Open(*ret.ps1URL.Load())
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000508 }
509 }()
510
511 srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass), browserC: browserC}}
Earl Lee2e463fb2025-04-17 11:22:22 -0700512 ret.srv = &srv
513
514 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
515 if err != nil {
516 return nil, fmt.Errorf("git port: %w", err)
517 }
518 ret.gitPort = gitPort
519 return ret, nil
520}
521
522func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
David Crawshaw69c67312025-04-17 13:42:00 -0700523 cmdArgs := []string{
524 "create",
David Crawshaw66cf74e2025-05-05 08:48:39 -0700525 "-i",
Earl Lee2e463fb2025-04-17 11:22:22 -0700526 "--name", cntrName,
527 "-p", hostPort + ":80", // forward container port 80 to a host port
David Crawshaw3659d872025-05-05 17:52:23 -0700528 "-e", "SKETCH_MODEL_API_KEY=" + config.ModelAPIKey,
Earl Lee2e463fb2025-04-17 11:22:22 -0700529 }
Philip Zeyliger3d2eff02025-05-27 09:30:31 -0700530 if !(config.OneShot || !config.TermUI) {
David Crawshaw66cf74e2025-05-05 08:48:39 -0700531 cmdArgs = append(cmdArgs, "-t")
532 }
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000533
534 for _, envVar := range getEnvForwardingFromGitConfig(ctx) {
535 cmdArgs = append(cmdArgs, "-e", envVar)
536 }
David Crawshaw5a7b3692025-05-05 16:49:15 -0700537 if config.ModelURL != "" {
David Crawshaw3659d872025-05-05 17:52:23 -0700538 cmdArgs = append(cmdArgs, "-e", "SKETCH_MODEL_URL="+config.ModelURL)
Earl Lee2e463fb2025-04-17 11:22:22 -0700539 }
540 if config.SketchPubKey != "" {
541 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
542 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700543 if config.SSHPort > 0 {
544 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
545 } else {
Philip Zeyliger87d29ef2025-05-16 20:25:28 -0700546 cmdArgs = append(cmdArgs, "-p", "0:22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700547 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700548 if relPath != "." {
549 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
550 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700551 // colima does this by default, but Linux docker seems to need this set explicitly
552 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000553
David Crawshaw1bd636c2025-06-13 19:56:27 +0000554 // Add seccomp profile to prevent killing PID 1 (the sketch process itself)
555 // Write the seccomp profile to cache directory if it doesn't exist
556 seccompPath, err := ensureSeccompProfile(ctx)
557 if err != nil {
558 return fmt.Errorf("failed to create seccomp profile: %w", err)
559 }
560 cmdArgs = append(cmdArgs, "--security-opt", "seccomp="+seccompPath)
561
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700562 // Add subtrace environment variable if token is provided
563 if config.SubtraceToken != "" {
564 cmdArgs = append(cmdArgs, "-e", "SUBTRACE_TOKEN="+config.SubtraceToken)
565 cmdArgs = append(cmdArgs, "-e", "SUBTRACE_HTTP2=1")
566 }
567
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000568 // Add volume mounts if specified
569 for _, mount := range config.Mounts {
570 if mount != "" {
571 cmdArgs = append(cmdArgs, "-v", mount)
572 }
573 }
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700574 cmdArgs = append(cmdArgs, imgName)
575
576 // Add command: either [sketch] or [subtrace run -- sketch]
577 if config.SubtraceToken != "" {
578 cmdArgs = append(cmdArgs, "/usr/local/bin/subtrace", "run", "--", "/bin/sketch")
579 } else {
580 cmdArgs = append(cmdArgs, "/bin/sketch")
581 }
582
583 // Add all sketch arguments
584 cmdArgs = append(cmdArgs,
Earl Lee2e463fb2025-04-17 11:22:22 -0700585 "-unsafe",
586 "-addr=:80",
587 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000588 "-git-username="+config.GitUsername,
589 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000590 "-outside-hostname="+config.OutsideHostname,
591 "-outside-os="+config.OutsideOS,
592 "-outside-working-dir="+config.OutsideWorkingDir,
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000593 fmt.Sprintf("-max-dollars=%f", config.MaxDollars),
Josh Bleecher Snyder3cae7d92025-04-30 09:54:29 -0700594 "-open=false",
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700595 "-termui="+fmt.Sprintf("%t", config.TermUI),
Philip Zeyligercabfa552025-05-19 16:14:28 -0700596 "-verbose="+fmt.Sprintf("%t", config.Verbose),
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000597 "-x="+config.ExperimentFlag,
Philip Zeyligerbe7802a2025-06-04 20:15:25 +0000598 "-branch-prefix="+config.BranchPrefix,
philip.zeyliger6d3de482025-06-10 19:38:14 -0700599 "-link-to-github="+fmt.Sprintf("%t", config.LinkToGitHub),
Earl Lee2e463fb2025-04-17 11:22:22 -0700600 )
philip.zeyliger8773e682025-06-11 21:36:21 -0700601 // Set SSH connection string based on session ID for SSH Theater
602 cmdArgs = append(cmdArgs, "-ssh-connection-string=sketch-"+config.SessionID)
David Crawshaw5a7b3692025-05-05 16:49:15 -0700603 if config.Model != "" {
604 cmdArgs = append(cmdArgs, "-model="+config.Model)
605 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700606 if config.GitRemoteUrl != "" {
607 cmdArgs = append(cmdArgs, "-git-remote-url="+config.GitRemoteUrl)
608 if config.Commit == "" {
609 panic("Commit should have been set when GitRemoteUrl was set")
610 }
611 cmdArgs = append(cmdArgs, "-commit="+config.Commit)
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000612 cmdArgs = append(cmdArgs, "-upstream="+config.Upstream)
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700613 }
614 if config.OutsideHTTP != "" {
615 cmdArgs = append(cmdArgs, "-outside-http="+config.OutsideHTTP)
616 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000617 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
Pokey Rule0dcebe12025-04-28 14:51:04 +0100618 if config.Prompt != "" {
619 cmdArgs = append(cmdArgs, "-prompt", config.Prompt)
620 }
621 if config.OneShot {
622 cmdArgs = append(cmdArgs, "-one-shot")
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700623 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000624 if config.ModelURL == "" {
625 // Forward ANTHROPIC_API_KEY for direct use.
626 // TODO: have outtie run an http proxy?
627 // TODO: select and forward the relevant API key based on the model
628 cmdArgs = append(cmdArgs, "-llm-api-key="+os.Getenv("ANTHROPIC_API_KEY"))
629 }
Philip Zeyliger194bfa82025-06-24 06:03:06 -0700630 // Add MCP server configurations
631 for _, mcpServer := range config.MCPServers {
632 cmdArgs = append(cmdArgs, "-mcp", mcpServer)
633 }
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000634
635 // Add additional docker arguments if provided
636 if config.DockerArgs != "" {
637 // Parse space-separated docker arguments with support for quotes and escaping
638 args := parseDockerArgs(config.DockerArgs)
639 // Insert arguments after "create" but before other arguments
640 for i := len(args) - 1; i >= 0; i-- {
641 cmdArgs = append(cmdArgs[:1], append([]string{args[i]}, cmdArgs[1:]...)...)
642 }
643 }
644
Earl Lee2e463fb2025-04-17 11:22:22 -0700645 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
646 return fmt.Errorf("docker create: %s, %w", out, err)
647 }
648 return nil
649}
650
David Crawshawb5f6a002025-05-05 08:27:16 -0700651func buildLinuxSketchBin(ctx context.Context) (string, error) {
Philip Zeyliger4acf0062025-05-22 13:53:46 -0700652 // Detect if race detector is enabled and use a different cache path
653 raceEnabled := RaceEnabled()
654 cacheSuffix := ""
655 if raceEnabled {
656 cacheSuffix = "-race"
657 }
658
659 homeDir, err := os.UserHomeDir()
660 if err != nil {
661 return "", err
662 }
663
664 linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo"+cacheSuffix)
665 if err := os.MkdirAll(linuxGopath, 0o777); err != nil {
666 return "", err
667 }
668
669 // When race detector is enabled, use Docker to build the Linux binary
670 if raceEnabled {
671 return buildLinuxSketchBinWithDocker(ctx, linuxGopath)
672 }
673
674 // Standard non-race build using cross-compilation
Pokey Rulea9a786b2025-05-12 10:52:34 +0100675 // Change to directory containing dockerimg.go for module detection
676 _, codeFile, _, _ := runtime.Caller(0)
677 codeDir := filepath.Dir(codeFile)
678 if currentDir, err := os.Getwd(); err != nil {
679 slog.WarnContext(ctx, "could not get current directory", "err", err)
680 } else {
681 if err := os.Chdir(codeDir); err != nil {
682 slog.WarnContext(ctx, "could not change to code directory for module check", "err", err)
683 } else {
684 defer func() {
685 _ = os.Chdir(currentDir)
686 }()
687 }
688 }
689
David Crawshaw8a617cb2025-04-18 01:28:43 -0700690 verToInstall := "@latest"
691 if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil {
692 return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err)
693 } else {
694 if strings.TrimSpace(string(out)) == "sketch.dev" {
David Crawshaw094e4d22025-04-24 11:35:14 -0700695 slog.DebugContext(ctx, "built linux agent from currently checked out module")
David Crawshaw8a617cb2025-04-18 01:28:43 -0700696 verToInstall = ""
697 }
698 }
David Crawshaw69c67312025-04-17 13:42:00 -0700699
Earl Lee2e463fb2025-04-17 11:22:22 -0700700 start := time.Now()
Philip Zeyliger4acf0062025-05-22 13:53:46 -0700701 args := []string{"install"}
702 args = append(args, "sketch.dev/cmd/sketch"+verToInstall)
703
704 cmd := exec.CommandContext(ctx, "go", args...)
David Crawshawb9eaef52025-04-17 15:23:18 -0700705 cmd.Env = append(
706 os.Environ(),
707 "GOOS=linux",
708 "CGO_ENABLED=0",
709 "GOTOOLCHAIN=auto",
David Crawshaw8a617cb2025-04-18 01:28:43 -0700710 "GOPATH="+linuxGopath,
Josh Bleecher Snyderfae17572025-04-21 11:48:05 -0700711 "GOBIN=",
David Crawshawb9eaef52025-04-17 15:23:18 -0700712 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700713
Earl Lee2e463fb2025-04-17 11:22:22 -0700714 out, err := cmd.CombinedOutput()
715 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700716 slog.ErrorContext(ctx, "go", slog.Duration("elapsed", time.Since(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
Earl Lee2e463fb2025-04-17 11:22:22 -0700717 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
718 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700719 slog.DebugContext(ctx, "go", slog.Duration("elapsed", time.Since(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
Earl Lee2e463fb2025-04-17 11:22:22 -0700720 }
721
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700722 if runtime.GOOS != "linux" {
David Crawshawc7e77962025-05-03 13:20:18 -0700723 return filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch"), nil
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700724 }
David Crawshawc7e77962025-05-03 13:20:18 -0700725 // If we are already on Linux, there's no extra platform name in the path
726 return filepath.Join(linuxGopath, "bin", "sketch"), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700727}
728
Sean McCulloughae3480f2025-04-23 15:28:20 -0700729func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700730 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700731 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700732 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
733 } else {
734 v4, _, found := strings.Cut(string(out), "\n")
735 if !found {
736 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
737 }
738 localAddr = v4
739 if strings.HasPrefix(localAddr, "0.0.0.0") {
740 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
741 }
742 }
743 return localAddr, nil
744}
745
746// Contact the container and configure it.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700747func postContainerInitConfig(ctx context.Context, localAddr string, sshAvailable bool, sshError string, sshServerIdentity, sshAuthorizedKeys, sshContainerCAKey, sshHostCertificate []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700748 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700749
750 initMsg, err := json.Marshal(
751 server.InitRequest{
Sean McCullough7013e9e2025-05-14 02:03:58 +0000752 HostAddr: localAddr,
753 SSHAuthorizedKeys: sshAuthorizedKeys,
754 SSHServerIdentity: sshServerIdentity,
755 SSHContainerCAKey: sshContainerCAKey,
756 SSHHostCertificate: sshHostCertificate,
757 SSHAvailable: sshAvailable,
758 SSHError: sshError,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700759 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700760 if err != nil {
761 return fmt.Errorf("init msg: %w", err)
762 }
763
Earl Lee2e463fb2025-04-17 11:22:22 -0700764 // Note: this /init POST is handled in loop/server/loophttp.go:
765 initMsgByteReader := bytes.NewReader(initMsg)
766 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
767 if err != nil {
768 return err
769 }
770
771 var res *http.Response
772 for i := 0; ; i++ {
773 time.Sleep(100 * time.Millisecond)
774 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
775 initMsgByteReader.Reset(initMsg)
776 res, err = http.DefaultClient.Do(req)
777 if err != nil {
David Crawshaw99231ba2025-05-03 10:48:26 -0700778 if i < 100 {
779 if i%10 == 0 {
780 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
781 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700782 continue
783 }
784 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
785 }
786 break
787 }
788 resBytes, _ := io.ReadAll(res.Body)
789 if res.StatusCode != http.StatusOK {
790 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
791 }
792 return nil
793}
794
David Crawshaw5a7b3692025-05-05 16:49:15 -0700795func findOrBuildDockerImage(ctx context.Context, cwd, gitRoot, model, modelURL, modelAPIKey string, forceRebuild, verbose bool) (imgName string, err error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700796 h := sha256.Sum256([]byte(gitRoot))
797 imgName = "sketch-" + hex.EncodeToString(h[:6])
798
799 var curImgInitFilesHash string
800 if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil {
Kilian Lackhovedd6352a2025-06-17 22:01:05 +0200801 if strings.Contains(strings.ToLower(string(out)), "no such object") {
Earl Lee2e463fb2025-04-17 11:22:22 -0700802 // Image does not exist, continue and build it.
803 curImgInitFilesHash = ""
804 } else {
805 return "", fmt.Errorf("docker inspect failed: %s, %v", out, err)
806 }
807 } else {
808 m := map[string]string{}
809 if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil {
810 return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err)
811 }
812 curImgInitFilesHash = m["sketch_context"]
813 }
814
815 candidates, err := findRepoDockerfiles(cwd, gitRoot)
816 if err != nil {
817 return "", fmt.Errorf("find dockerfile: %w", err)
818 }
819
820 var initFiles map[string]string
821 var dockerfilePath string
David Crawshawff2df6a2025-05-12 14:45:29 -0700822 var generatedDockerfile string
Earl Lee2e463fb2025-04-17 11:22:22 -0700823
Jon Friesend27921f2025-06-05 13:15:56 +0000824 // Prioritize Dockerfile.sketch over Dockerfile, then fall back to generated dockerfile
825 if len(candidates) > 0 {
826 dockerfilePath = prioritizeDockerfiles(candidates)
Earl Lee2e463fb2025-04-17 11:22:22 -0700827 contents, err := os.ReadFile(dockerfilePath)
828 if err != nil {
829 return "", err
830 }
Jon Friesend27921f2025-06-05 13:15:56 +0000831 fmt.Printf("using %s as dev env\n", dockerfilePath)
Earl Lee2e463fb2025-04-17 11:22:22 -0700832 if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700833 return imgName, nil
834 }
835 } else {
836 initFiles, err = readInitFiles(os.DirFS(gitRoot))
837 if err != nil {
838 return "", err
839 }
840 subPathWorkingDir, err := filepath.Rel(gitRoot, cwd)
841 if err != nil {
842 return "", err
843 }
844 initFileHash := hashInitFiles(initFiles)
845 if curImgInitFilesHash == initFileHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700846 return imgName, nil
847 }
848
Kilian Lackhove23772f42025-06-18 20:28:58 +0200849 start := time.Now()
850
851 var service llm.Service
David Crawshaw5a7b3692025-05-05 16:49:15 -0700852 if model == "gemini" {
Kilian Lackhove23772f42025-06-18 20:28:58 +0200853 service = &gem.Service{
854 URL: modelURL,
855 APIKey: modelAPIKey,
856 HTTPC: http.DefaultClient,
857 }
858 } else {
859 service = &ant.Service{
860 URL: modelURL,
861 APIKey: modelAPIKey,
862 HTTPC: http.DefaultClient,
David Crawshaw5a7b3692025-05-05 16:49:15 -0700863 }
864 }
865
Kilian Lackhove23772f42025-06-18 20:28:58 +0200866 generatedDockerfile, err = createDockerfile(ctx, service, initFiles, subPathWorkingDir, verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700867 if err != nil {
868 return "", fmt.Errorf("create dockerfile: %w", err)
869 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000870 // Create a unique temporary directory for the Dockerfile
871 tmpDir, err := os.MkdirTemp("", "sketch-docker-*")
872 if err != nil {
873 return "", fmt.Errorf("failed to create temporary directory: %w", err)
874 }
875 dockerfilePath = filepath.Join(tmpDir, tmpSketchDockerfile)
David Crawshawff2df6a2025-05-12 14:45:29 -0700876 if err := os.WriteFile(dockerfilePath, []byte(generatedDockerfile), 0o666); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700877 return "", err
878 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000879 // Remove the temporary directory and all contents when done
880 defer os.RemoveAll(tmpDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700881
David Crawshawb5f6a002025-05-05 08:27:16 -0700882 if verbose {
David Crawshawff2df6a2025-05-12 14:45:29 -0700883 fmt.Fprintf(os.Stderr, "generated Dockerfile in %s:\n\t%s\n\n", time.Since(start).Round(time.Millisecond), strings.Replace(generatedDockerfile, "\n", "\n\t", -1))
David Crawshawb5f6a002025-05-05 08:27:16 -0700884 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700885 }
886
887 var gitUserEmail, gitUserName string
888 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
Sean McCullough8ad17ba2025-06-09 00:43:57 +0000889 return "", fmt.Errorf("git user.email is not set. Please run 'git config --global user.email \"your.email@example.com\"' to set your email address")
Earl Lee2e463fb2025-04-17 11:22:22 -0700890 } else {
891 gitUserEmail = strings.TrimSpace(string(out))
892 }
893 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
Sean McCullough8ad17ba2025-06-09 00:43:57 +0000894 return "", fmt.Errorf("git user.name is not set. Please run 'git config --global user.name \"Your Name\"' to set your name")
Earl Lee2e463fb2025-04-17 11:22:22 -0700895 } else {
896 gitUserName = strings.TrimSpace(string(out))
897 }
898
899 start := time.Now()
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700900 cmdArgs := []string{
901 "build",
Earl Lee2e463fb2025-04-17 11:22:22 -0700902 "-t", imgName,
903 "-f", dockerfilePath,
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700904 "--build-arg", "GIT_USER_EMAIL=" + gitUserEmail,
905 "--build-arg", "GIT_USER_NAME=" + gitUserName,
906 }
907
908 // Add the sketch_context label for image reuse detection
909 var contextHash string
910 if len(candidates) > 0 {
911 // Building from Dockerfile.sketch or similar static file
912 contents, err := os.ReadFile(dockerfilePath)
913 if err != nil {
914 return "", err
915 }
916 contextHash = hashInitFiles(map[string]string{dockerfilePath: string(contents)})
917 } else {
918 // Building from generated dockerfile
919 contextHash = hashInitFiles(initFiles)
920 }
921 cmdArgs = append(cmdArgs, "--label", "sketch_context="+contextHash)
922 cmdArgs = append(cmdArgs, ".")
923
924 cmd := exec.CommandContext(ctx, "docker", cmdArgs...)
David Crawshawb5f6a002025-05-05 08:27:16 -0700925 cmd.Dir = gitRoot
David Crawshaw31f15242025-05-06 16:03:49 -0700926 // We print the docker build output whether or not the user
927 // has selected --verbose. Building an image takes a while
928 // and this gives good context.
David Crawshawb5f6a002025-05-05 08:27:16 -0700929 cmd.Stdout = os.Stdout
930 cmd.Stderr = os.Stderr
931 fmt.Printf("🏗️ building docker image %s... (use -verbose to see build output)\n", imgName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700932
933 err = run(ctx, "docker build", cmd)
934 if err != nil {
David Crawshawff2df6a2025-05-12 14:45:29 -0700935 var msg string
936 if generatedDockerfile != "" {
937 if !verbose {
938 fmt.Fprintf(os.Stderr, "Generated Dockerfile:\n\t%s\n\n", strings.Replace(generatedDockerfile, "\n", "\n\t", -1))
939 }
940 msg = fmt.Sprintf("\n\nThe generated Dockerfile failed to build.\nYou can override it by committing a Dockerfile to your project.")
941 }
942 return "", fmt.Errorf("docker build failed: %v%s", err, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -0700943 }
944 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
945 return imgName, nil
946}
947
948func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) {
949 files, err := findDirDockerfiles(cwd)
950 if err != nil {
951 return nil, err
952 }
953 if len(files) > 0 {
954 return files, nil
955 }
956
957 path := cwd
958 for path != gitRoot {
959 path = filepath.Dir(path)
960 files, err := findDirDockerfiles(path)
961 if err != nil {
962 return nil, err
963 }
964 if len(files) > 0 {
965 return files, nil
966 }
967 }
968 return files, nil
969}
970
Jon Friesend27921f2025-06-05 13:15:56 +0000971// prioritizeDockerfiles returns the highest priority dockerfile from a list of candidates.
972// Priority order: Dockerfile.sketch > Dockerfile > other Dockerfile.*
973func prioritizeDockerfiles(candidates []string) string {
974 if len(candidates) == 0 {
975 return ""
976 }
977 if len(candidates) == 1 {
978 return candidates[0]
979 }
980
981 // Look for Dockerfile.sketch first (case insensitive)
982 for _, candidate := range candidates {
983 basename := strings.ToLower(filepath.Base(candidate))
984 if basename == "dockerfile.sketch" {
985 return candidate
986 }
987 }
988
989 // Look for Dockerfile second (case insensitive)
990 for _, candidate := range candidates {
991 basename := strings.ToLower(filepath.Base(candidate))
992 if basename == "dockerfile" {
993 return candidate
994 }
995 }
996
997 // Return first remaining candidate
998 return candidates[0]
999}
1000
Earl Lee2e463fb2025-04-17 11:22:22 -07001001// findDirDockerfiles finds all "Dockerfile*" files in a directory.
1002func findDirDockerfiles(root string) (res []string, err error) {
1003 err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
1004 if err != nil {
1005 return err
1006 }
1007 if info.IsDir() && root != path {
1008 return filepath.SkipDir
1009 }
1010 name := strings.ToLower(info.Name())
Josh Bleecher Snydera9fd88f2025-06-05 10:43:22 -07001011 if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") || strings.HasSuffix(name, ".dockerfile") {
Earl Lee2e463fb2025-04-17 11:22:22 -07001012 res = append(res, path)
1013 }
1014 return nil
1015 })
1016 if err != nil {
1017 return nil, err
1018 }
1019 return res, nil
1020}
1021
Philip Zeyligerd6d12d12025-05-19 19:19:21 -07001022func checkForEmptyGitRepo(ctx context.Context, path string) error {
1023 cmd := exec.CommandContext(ctx, "git", "rev-parse", "-q", "--verify", "HEAD")
1024 cmd.Dir = path
1025 _, err := cmd.CombinedOutput()
1026 if err != nil {
1027 return fmt.Errorf("sketch needs to run from within a git repo with at least one commit.\nRun: %s",
1028 "git commit --allow-empty -m 'initial commit'")
1029 }
1030 return nil
1031}
1032
Earl Lee2e463fb2025-04-17 11:22:22 -07001033func findGitRoot(ctx context.Context, path string) (string, error) {
1034 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
1035 cmd.Dir = path
1036 out, err := cmd.CombinedOutput()
1037 if err != nil {
1038 if strings.Contains(string(out), "not a git repository") {
1039 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
1040Consider one of the following options:
1041 - cd to a different dir that is already part of a git repo first, or
1042 - to create a new git repo from this directory (%s), run this command:
1043
1044 git init . && git commit --allow-empty -m "initial commit"
1045
1046and try running sketch again.
1047`, path, path)
1048 }
1049 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
1050 }
1051 gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path
1052 absGitDir := filepath.Join(path, gitDir)
1053 return filepath.Dir(absGitDir), err
1054}
1055
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +00001056// getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker
1057// from git config using the sketch.envfwd multi-valued key.
1058func getEnvForwardingFromGitConfig(ctx context.Context) []string {
1059 outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput()
1060 out := string(outb)
1061 if err != nil {
1062 if strings.Contains(out, "key does not exist") {
1063 return nil
1064 }
1065 slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out)
1066 return nil
1067 }
1068
1069 var envVars []string
1070 for envVar := range strings.Lines(out) {
1071 envVar = strings.TrimSpace(envVar)
1072 if envVar == "" {
1073 continue
1074 }
1075 envVars = append(envVars, envVar+"="+os.Getenv(envVar))
1076 }
1077 return envVars
1078}
Philip Zeyliger1dc21372025-05-05 19:54:44 +00001079
1080// parseDockerArgs parses a string containing space-separated Docker arguments into an array of strings.
1081// It handles quoted arguments and escaped characters.
1082//
1083// Examples:
1084//
1085// --memory=2g --cpus=2 -> ["--memory=2g", "--cpus=2"]
1086// --label="my label" --env=FOO=bar -> ["--label=my label", "--env=FOO=bar"]
1087// --env="KEY=\"quoted value\"" -> ["--env=KEY=\"quoted value\""]
1088func parseDockerArgs(args string) []string {
1089 if args = strings.TrimSpace(args); args == "" {
1090 return []string{}
1091 }
1092
1093 var result []string
1094 var current strings.Builder
1095 inQuotes := false
1096 escapeNext := false
1097 quoteChar := rune(0)
1098
1099 for _, char := range args {
1100 if escapeNext {
1101 current.WriteRune(char)
1102 escapeNext = false
1103 continue
1104 }
1105
1106 if char == '\\' {
1107 escapeNext = true
1108 continue
1109 }
1110
1111 if char == '"' || char == '\'' {
1112 if !inQuotes {
1113 inQuotes = true
1114 quoteChar = char
1115 continue
1116 } else if char == quoteChar {
1117 inQuotes = false
1118 quoteChar = rune(0)
1119 continue
1120 }
1121 // Non-matching quote character inside quotes
1122 current.WriteRune(char)
1123 continue
1124 }
1125
1126 // Space outside of quotes is an argument separator
1127 if char == ' ' && !inQuotes {
1128 if current.Len() > 0 {
1129 result = append(result, current.String())
1130 current.Reset()
1131 }
1132 continue
1133 }
1134
1135 current.WriteRune(char)
1136 }
1137
1138 // Add the last argument if there is one
1139 if current.Len() > 0 {
1140 result = append(result, current.String())
1141 }
1142
1143 return result
1144}
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001145
1146// buildLinuxSketchBinWithDocker builds the Linux sketch binary using Docker when race detector is enabled.
1147// This avoids cross-compilation issues with CGO which is required for the race detector.
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001148// Mounts host Go module cache and build cache for faster subsequent builds.
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001149func buildLinuxSketchBinWithDocker(ctx context.Context, linuxGopath string) (string, error) {
1150 // Find the git repo root
1151 currentDir, err := os.Getwd()
1152 if err != nil {
1153 return "", fmt.Errorf("could not get current directory: %w", err)
1154 }
1155
1156 gitRoot, err := findGitRoot(ctx, currentDir)
1157 if err != nil {
1158 return "", fmt.Errorf("could not find git root, cannot build with race detector outside a git repo: %w", err)
1159 }
1160
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001161 // Get host Go cache directories to mount for faster builds
1162 goCacheDir, err := getHostGoCacheDir(ctx)
1163 if err != nil {
1164 return "", fmt.Errorf("failed to get host GOCACHE: %w", err)
1165 }
1166 goModCacheDir, err := getHostGoModCacheDir(ctx)
1167 if err != nil {
1168 return "", fmt.Errorf("failed to get host GOMODCACHE: %w", err)
1169 }
1170
1171 slog.DebugContext(ctx, "building Linux sketch binary with race detector using Docker", "git_root", gitRoot, "gocache", goCacheDir, "gomodcache", goModCacheDir)
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001172
1173 // Use the published Docker image tag
1174 imageTag := dockerfileBaseHash()
1175 imgName := fmt.Sprintf("%s:%s", dockerImgName, imageTag)
1176
1177 // Create destination directory for the binary
1178 destPath := filepath.Join(linuxGopath, "bin")
1179 if err := os.MkdirAll(destPath, 0o777); err != nil {
1180 return "", fmt.Errorf("failed to create destination directory: %w", err)
1181 }
1182 destFile := filepath.Join(destPath, "sketch")
1183
1184 // Create a unique container name
1185 containerID := fmt.Sprintf("sketch-race-build-%d", time.Now().UnixNano())
1186
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001187 // Run a container with the repo mounted and Go caches for faster builds
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001188 start := time.Now()
1189 slog.DebugContext(ctx, "running Docker container to build sketch with race detector")
1190
1191 // Use explicit output path for clarity
1192 runArgs := []string{
1193 "run",
1194 "--name", containerID,
1195 "-v", gitRoot + ":/app",
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001196 "-v", goCacheDir + ":/root/.cache/go-build",
1197 "-v", goModCacheDir + ":/go/pkg/mod",
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001198 "-w", "/app",
1199 imgName,
Josh Bleecher Snyderf4f929a2025-05-23 17:19:26 +00001200 "sh", "-c", "cd /app && mkdir -p /tmp/sketch-out && go build -buildvcs=false -race -o /tmp/sketch-out/sketch sketch.dev/cmd/sketch",
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001201 }
1202
1203 out, err := combinedOutput(ctx, "docker", runArgs...)
1204 if err != nil {
1205 // Print the output to help with debugging
1206 slog.ErrorContext(ctx, "docker run for race build failed",
1207 slog.String("output", string(out)),
1208 slog.String("error", err.Error()))
1209 return "", fmt.Errorf("docker run failed: %s: %w", out, err)
1210 }
1211
1212 slog.DebugContext(ctx, "built sketch with race detector in Docker", "elapsed", time.Since(start))
1213
1214 // Copy the binary from the container using the explicit path
1215 out, err = combinedOutput(ctx, "docker", "cp", containerID+":/tmp/sketch-out/sketch", destFile)
1216 if err != nil {
1217 return "", fmt.Errorf("docker cp failed: %s: %w", out, err)
1218 }
1219
1220 // Clean up the container
1221 if out, err := combinedOutput(ctx, "docker", "rm", containerID); err != nil {
1222 slog.WarnContext(ctx, "failed to remove container", "container", containerID, "error", err, "output", string(out))
1223 }
1224
1225 // Make the binary executable
1226 if err := os.Chmod(destFile, 0o755); err != nil {
1227 return "", fmt.Errorf("failed to make binary executable: %w", err)
1228 }
1229
1230 return destFile, nil
1231}
Josh Bleecher Snyder3e6a4c42025-05-23 17:29:57 +00001232
1233// getHostGoCacheDir returns the host's GOCACHE directory
1234func getHostGoCacheDir(ctx context.Context) (string, error) {
1235 out, err := exec.CommandContext(ctx, "go", "env", "GOCACHE").CombinedOutput()
1236 if err != nil {
1237 return "", fmt.Errorf("failed to get GOCACHE: %s: %w", out, err)
1238 }
1239 return strings.TrimSpace(string(out)), nil
1240}
1241
1242// getHostGoModCacheDir returns the host's GOMODCACHE directory
1243func getHostGoModCacheDir(ctx context.Context) (string, error) {
1244 out, err := exec.CommandContext(ctx, "go", "env", "GOMODCACHE").CombinedOutput()
1245 if err != nil {
1246 return "", fmt.Errorf("failed to get GOMODCACHE: %s: %w", out, err)
1247 }
1248 return strings.TrimSpace(string(out)), nil
1249}
David Crawshaw1bd636c2025-06-13 19:56:27 +00001250
1251const seccompProfile = `{
1252 "defaultAction": "SCMP_ACT_ALLOW",
1253 "syscalls": [
1254 {
1255 "names": ["kill", "tkill", "tgkill", "pidfd_send_signal"],
1256 "action": "SCMP_ACT_ERRNO",
1257 "args": [
1258 {
1259 "index": 0,
1260 "value": 1,
1261 "op": "SCMP_CMP_EQ"
1262 }
1263 ]
1264 }
1265 ]
1266}`
1267
1268// ensureSeccompProfile creates the seccomp profile file in the sketch cache directory if it doesn't exist.
1269func ensureSeccompProfile(ctx context.Context) (seccompPath string, err error) {
1270 homeDir, err := os.UserHomeDir()
1271 if err != nil {
1272 return "", fmt.Errorf("failed to get home directory: %w", err)
1273 }
1274 cacheDir := filepath.Join(homeDir, ".cache", "sketch")
1275 if err := os.MkdirAll(cacheDir, 0o755); err != nil {
1276 return "", fmt.Errorf("failed to create cache directory: %w", err)
1277 }
1278 seccompPath = filepath.Join(cacheDir, "seccomp-no-kill-1.json")
1279
1280 curBytes, err := os.ReadFile(seccompPath)
1281 if err != nil && !os.IsNotExist(err) {
1282 return "", fmt.Errorf("failed to read seccomp profile file %s: %w", seccompPath, err)
1283 }
1284 if string(curBytes) == seccompProfile {
1285 return seccompPath, nil // File already exists and matches the expected profile
1286 }
1287
1288 if err := os.WriteFile(seccompPath, []byte(seccompProfile), 0o644); err != nil {
1289 return "", fmt.Errorf("failed to write seccomp profile to %s: %w", seccompPath, err)
1290 }
1291 slog.DebugContext(ctx, "created seccomp profile", "path", seccompPath)
1292 return seccompPath, nil
1293}