blob: 19d90cfec5ede8a6915c4d22123e33781327d33a [file] [log] [blame]
Earl Lee2e463fb2025-04-17 11:22:22 -07001// Package dockerimg
2package dockerimg
3
4import (
Josh Bleecher Snyderc9898fd2025-07-08 21:09:18 +00005 "archive/tar"
Earl Lee2e463fb2025-04-17 11:22:22 -07006 "bytes"
7 "context"
Philip Zeyliger5e227dd2025-04-21 15:55:29 -07008 "crypto/rand"
Earl Lee2e463fb2025-04-17 11:22:22 -07009 "crypto/sha256"
10 "encoding/hex"
11 "encoding/json"
12 "fmt"
13 "io"
14 "log/slog"
15 "net"
16 "net/http"
17 "os"
18 "os/exec"
19 "path/filepath"
20 "runtime"
21 "strings"
Josh Bleecher Snyder99570462025-05-05 10:26:14 -070022 "sync/atomic"
Earl Lee2e463fb2025-04-17 11:22:22 -070023 "time"
24
Sean McCullough7013e9e2025-05-14 02:03:58 +000025 "golang.org/x/crypto/ssh"
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +000026 "sketch.dev/browser"
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -070027 "sketch.dev/embedded"
Sean McCulloughbaa2b592025-04-23 10:40:08 -070028 "sketch.dev/loop/server"
Earl Lee2e463fb2025-04-17 11:22:22 -070029 "sketch.dev/skribe"
30)
31
32// ContainerConfig holds all configuration for launching a container
33type ContainerConfig struct {
34 // SessionID is the unique identifier for this session
35 SessionID string
36
37 // LocalAddr is the initial address to use (though it may be overwritten later)
38 LocalAddr string
39
40 // SkabandAddr is the address of the skaband service if available
41 SkabandAddr string
42
David Crawshaw5a7b3692025-05-05 16:49:15 -070043 // Model is the name of the LLM model to use.
44 Model string
Earl Lee2e463fb2025-04-17 11:22:22 -070045
David Crawshaw5a7b3692025-05-05 16:49:15 -070046 // ModelURL is the URL of the LLM service.
47 ModelURL string
48
49 // ModelAPIKey is the API key for LLM service.
50 ModelAPIKey string
Earl Lee2e463fb2025-04-17 11:22:22 -070051
52 // Path is the local filesystem path to use
53 Path string
54
55 // GitUsername is the username to use for git operations
56 GitUsername string
57
58 // GitEmail is the email to use for git operations
59 GitEmail string
60
61 // OpenBrowser determines whether to open a browser automatically
62 OpenBrowser bool
63
64 // NoCleanup prevents container cleanup when set to true
65 NoCleanup bool
66
67 // ForceRebuild forces rebuilding of the Docker image even if it exists
68 ForceRebuild bool
69
Philip Zeyliger983b58a2025-07-02 19:42:08 -070070 // BaseImage is the base Docker image to use for layering the repo
71 BaseImage string
72
Earl Lee2e463fb2025-04-17 11:22:22 -070073 // Host directory to copy container logs into, if not set to ""
74 ContainerLogDest string
75
76 // Path to pre-built linux sketch binary, or build a new one if set to ""
77 SketchBinaryLinux string
78
79 // Sketch client public key.
80 SketchPubKey string
Philip Zeyligerd1402952025-04-23 03:54:37 +000081
Sean McCulloughbaa2b592025-04-23 10:40:08 -070082 // Host port for the container's ssh server
83 SSHPort int
84
Philip Zeyliger18532b22025-04-23 21:11:46 +000085 // Outside information to pass to the container
86 OutsideHostname string
87 OutsideOS string
88 OutsideWorkingDir string
Philip Zeyligerb74c4f62025-04-25 19:18:49 -070089
Pokey Rule0dcebe12025-04-28 14:51:04 +010090 // If true, exit after the first turn
91 OneShot bool
92
93 // Initial prompt
94 Prompt string
Philip Zeyliger1b47aa22025-04-28 19:25:38 +000095
David Crawshawb5f6a002025-05-05 08:27:16 -070096 // Verbose enables verbose output
97 Verbose bool
Philip Zeyliger1dc21372025-05-05 19:54:44 +000098
99 // DockerArgs are additional arguments to pass to the docker create command
100 DockerArgs string
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000101
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000102 // Mounts specifies volumes to mount in the container in format /path/on/host:/path/in/container
103 Mounts []string
104
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000105 // ExperimentFlag contains the experimental features to enable
106 ExperimentFlag string
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700107
108 // TermUI enables terminal UI
109 TermUI bool
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700110
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000111 // Budget configuration
Philip Zeyligere6c294d2025-06-04 16:55:21 +0000112 MaxDollars float64
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000113
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700114 GitRemoteUrl string
115
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000116 // Original git origin URL from the host repository
117 OriginalGitOrigin string
118
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000119 // Upstream branch for git work
120 Upstream string
121
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700122 // Commit hash to checkout from GetRemoteUrl
123 Commit string
124
125 // Outtie's HTTP server
126 OutsideHTTP string
Philip Zeyligerbe7802a2025-06-04 20:15:25 +0000127
128 // Prefix for git branches created by sketch
129 BranchPrefix string
philip.zeyliger6d3de482025-06-10 19:38:14 -0700130
131 // LinkToGitHub enables GitHub branch linking in UI
132 LinkToGitHub bool
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700133
134 // SubtraceToken enables running sketch under subtrace.dev (development only)
135 SubtraceToken string
Philip Zeyliger194bfa82025-06-24 06:03:06 -0700136
137 // MCPServers contains MCP server configurations
138 MCPServers []string
Philip Zeyliger254c49f2025-07-17 17:26:24 -0700139
140 // PassthroughUpstream configures upstream remote for passthrough to innie
141 PassthroughUpstream bool
Earl Lee2e463fb2025-04-17 11:22:22 -0700142}
143
144// LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it.
145// It writes status to stdout.
David Crawshawb5f6a002025-05-05 08:27:16 -0700146func LaunchContainer(ctx context.Context, config ContainerConfig) error {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700147 slog.Debug("Container Config", slog.String("config", fmt.Sprintf("%+v", config)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700148 if _, err := exec.LookPath("docker"); err != nil {
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700149 if runtime.GOOS == "darwin" {
150 return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start")
151 } else {
152 return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)")
153 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700154 }
155
156 if out, err := combinedOutput(ctx, "docker", "ps"); err != nil {
157 // `docker ps` provides a good error message here that can be
158 // easily chatgpt'ed by users, so send it to the user as-is:
159 // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
160 return fmt.Errorf("docker ps: %s (%w)", out, err)
161 }
162
163 _, hostPort, err := net.SplitHostPort(config.LocalAddr)
164 if err != nil {
165 return err
166 }
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000167 // Bail early if sketch was started from a path that isn't in a git repo.
168 err = requireGitRepo(ctx, config.Path)
Earl Lee2e463fb2025-04-17 11:22:22 -0700169 if err != nil {
170 return err
171 }
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000172
173 // Best effort attempt to get repo root; fall back to current directory.
174 gitRoot := config.Path
175 if root, err := gitRepoRoot(ctx, config.Path); err == nil {
176 gitRoot = root
177 }
178
179 // Capture the original git origin URL before we set up the temporary git server
180 config.OriginalGitOrigin = getOriginalGitOrigin(ctx, gitRoot)
181
Philip Zeyliger254c49f2025-07-17 17:26:24 -0700182 // If we've got an upstream, let's configure
183 if config.OriginalGitOrigin != "" {
184 config.PassthroughUpstream = true
185 }
186
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700187 imgName, err := findOrBuildDockerImage(ctx, gitRoot, config.BaseImage, config.ForceRebuild, config.Verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700188 if err != nil {
189 return err
190 }
191
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000192 cntrName := "sketch-" + config.SessionID
Earl Lee2e463fb2025-04-17 11:22:22 -0700193 defer func() {
194 if config.NoCleanup {
195 return
196 }
197 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
198 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
199 _ = out
200 }
201 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
202 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
203 _ = out
204 }
205 }()
206
207 // errCh receives errors from operations that this function calls in separate goroutines.
208 errCh := make(chan error)
209
210 // Start the git server
Philip Zeyliger254c49f2025-07-17 17:26:24 -0700211 gitSrv, err := newGitServer(gitRoot, config.PassthroughUpstream)
Earl Lee2e463fb2025-04-17 11:22:22 -0700212 if err != nil {
213 return fmt.Errorf("failed to start git server: %w", err)
214 }
215 defer gitSrv.shutdown(ctx)
216
217 go func() {
218 errCh <- gitSrv.serve(ctx)
219 }()
220
philz24613202025-07-15 20:56:21 -0700221 // Check if we have any commits, and if not, create an empty initial commit
222 cmd := exec.CommandContext(ctx, "git", "rev-list", "--all", "--count")
223 countOut, err := cmd.CombinedOutput()
224 if err != nil {
225 return fmt.Errorf("git rev-list --all --count: %s: %w", countOut, err)
226 }
227 commitCount := strings.TrimSpace(string(countOut))
228 if commitCount == "0" {
229 slog.Info("No commits found, creating empty initial commit")
230 cmd = exec.CommandContext(ctx, "git", "commit", "--allow-empty", "-m", "Initial empty commit")
231 if commitOut, err := cmd.CombinedOutput(); err != nil {
232 return fmt.Errorf("git commit --allow-empty: %s: %w", commitOut, err)
233 }
234 }
235
Earl Lee2e463fb2025-04-17 11:22:22 -0700236 // Get the current host git commit
237 var commit string
Philip Zeyligera347b172025-06-04 16:18:57 +0000238 if out, err := combinedOutput(ctx, "git", "rev-parse", "HEAD"); err != nil {
239 return fmt.Errorf("git rev-parse HEAD: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700240 } else {
241 commit = strings.TrimSpace(string(out))
242 }
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000243
244 var upstream string
245 if out, err := combinedOutput(ctx, "git", "branch", "--show-current"); err != nil {
246 slog.DebugContext(ctx, "git branch --show-current failed (continuing)", "error", err)
247 } else {
248 upstream = strings.TrimSpace(string(out))
249 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700250 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
251 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
252 }
253
254 relPath, err := filepath.Rel(gitRoot, config.Path)
255 if err != nil {
256 return err
257 }
258
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700259 config.OutsideHTTP = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitSrv.pass, gitSrv.gitPort)
260 config.GitRemoteUrl = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitSrv.pass, gitSrv.gitPort)
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000261 config.Upstream = upstream
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700262 config.Commit = commit
263
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -0700264 // Create the sketch container, copy over linux sketch
Earl Lee2e463fb2025-04-17 11:22:22 -0700265 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000266 return fmt.Errorf("failed to create docker container: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700267 }
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -0700268 if err := copyEmbeddedLinuxBinaryToContainer(ctx, cntrName); err != nil {
269 return fmt.Errorf("failed to copy linux binary to container: %w", err)
David Crawshaw8bff16a2025-04-18 01:16:49 -0700270 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700271
David Crawshaw53786ef2025-04-24 12:52:51 -0700272 fmt.Printf("📦 running in container %s\n", cntrName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700273
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700274 // Setup subtrace if token is provided (development only) - after container creation, before start
275 if config.SubtraceToken != "" {
276 fmt.Println("🔍 Setting up subtrace (development only)")
277 if err := setupSubtraceBeforeStart(ctx, cntrName, config.SubtraceToken); err != nil {
278 return fmt.Errorf("failed to setup subtrace: %w", err)
279 }
280 }
281
Earl Lee2e463fb2025-04-17 11:22:22 -0700282 // Start the sketch container
283 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
284 return fmt.Errorf("docker start: %s, %w", out, err)
285 }
286
287 // Copies structured logs from the container to the host.
288 copyLogs := func() {
289 if config.ContainerLogDest == "" {
290 return
291 }
292 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
293 if err != nil {
294 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
295 return
296 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700297 prefix := []byte("structured logs:")
298 for line := range bytes.Lines(out) {
299 rest, ok := bytes.CutPrefix(line, prefix)
300 if !ok {
Earl Lee2e463fb2025-04-17 11:22:22 -0700301 continue
302 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700303 logFile := string(bytes.TrimSpace(rest))
Earl Lee2e463fb2025-04-17 11:22:22 -0700304 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
305 logFileName := filepath.Base(logFile)
306 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
307 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
308 if err != nil {
309 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
310 }
311 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
312 }
313 }
314
315 // NOTE: we want to see what the internal sketch binary prints
316 // regardless of the setting of the verbosity flag on the external
317 // binary, so reading "docker logs", which is the stdout/stderr of
318 // the internal binary is not conditional on the verbose flag.
319 appendInternalErr := func(err error) error {
320 if err == nil {
321 return nil
322 }
323 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000324 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700325 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
326 }
327 out = bytes.TrimSpace(out)
328 if len(out) > 0 {
329 return fmt.Errorf("docker logs: %s;\n%w", out, err)
330 }
331 return err
332 }
333
334 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700335 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700336 if err != nil {
337 return appendInternalErr(err)
338 }
339
Philip Zeyliger00442412025-05-14 11:03:23 -0700340 if config.Verbose {
341 fmt.Fprintf(os.Stderr, "Host web server: http://%s/\n", localAddr)
342 }
343
Sean McCulloughae3480f2025-04-23 15:28:20 -0700344 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
345 if err != nil {
346 return appendInternalErr(err)
347 }
348 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
349 if err != nil {
David Crawshawb5f6a002025-05-05 08:27:16 -0700350 return appendInternalErr(fmt.Errorf("failed to split ssh host and port: %w", err))
Sean McCulloughae3480f2025-04-23 15:28:20 -0700351 }
Sean McCullough4854c652025-04-24 18:37:02 -0700352
Sean McCullough7013e9e2025-05-14 02:03:58 +0000353 var sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate []byte
Sean McCullough4854c652025-04-24 18:37:02 -0700354
banksean29d689f2025-06-23 15:41:26 +0000355 cst, err := NewLocalSSHimmer(cntrName, sshHost, sshPort)
Sean McCullough078e85a2025-05-08 17:28:34 -0700356 if err != nil {
357 return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err))
358 }
359
360 sshErr := CheckSSHReachability(cntrName)
Sean McCullough15c95282025-05-08 16:48:38 -0700361 sshAvailable := false
362 sshErrMsg := ""
363 if sshErr != nil {
364 fmt.Println(sshErr.Error())
365 sshErrMsg = sshErr.Error()
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700366 // continue - ssh config is not required for the rest of sketch to function locally.
367 } else {
Sean McCullough15c95282025-05-08 16:48:38 -0700368 sshAvailable = true
Sean McCulloughea3fc202025-04-28 12:53:37 -0700369 // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find:
370 // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700371 fmt.Printf(`Connect to this container via any of these methods:
Sean McCullough4854c652025-04-24 18:37:02 -0700372🖥️ ssh %s
373🖥️ code --remote ssh-remote+root@%s /app -n
Sean McCulloughea3fc202025-04-28 12:53:37 -0700374🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank
Sean McCullough4854c652025-04-24 18:37:02 -0700375`, cntrName, cntrName, cntrName)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700376 sshUserIdentity = cst.userIdentity
377 sshServerIdentity = cst.serverIdentity
Sean McCullough7013e9e2025-05-14 02:03:58 +0000378
379 // Get the Container CA public key for mutual auth
380 if cst.containerCAPublicKey != nil {
381 containerCAPublicKey = ssh.MarshalAuthorizedKey(cst.containerCAPublicKey)
382 fmt.Println("🔒 SSH Mutual Authentication enabled (container will verify host)")
383 }
384
385 // Get the host certificate for mutual auth
386 hostCertificate = cst.hostCertificate
387
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700388 defer func() {
389 if err := cst.Cleanup(); err != nil {
390 appendInternalErr(err)
391 }
392 }()
393 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700394
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700395 // Tell the sketch container to Init(), which starts the SSH server
396 // and checks out the right commit.
397 // TODO: I'm trying to move as much configuration as possible into the command-line
398 // arguments to avoid splitting them up. "localAddr" is the only difficult one:
399 // we run (effectively) "docker run -p 0:80 image sketch -flags" and you can't
400 // get the port Docker chose until after the process starts. The SSH config is
401 // mostly available ahead of time, but whether it works ("sshAvailable"/"sshErrMsg")
402 // may also empirically need to be done after the SSH server is up and running.
Earl Lee2e463fb2025-04-17 11:22:22 -0700403 go func() {
404 // TODO: Why is this called in a goroutine? I have found that when I pull this out
405 // of the goroutine and call it inline, then the terminal UI clears itself and all
406 // the scrollback (which is not good, but also not fatal). I can't see why it does this
407 // though, since none of the calls in postContainerInitConfig obviously write to stdout
408 // or stderr.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700409 if err := postContainerInitConfig(ctx, localAddr, sshAvailable, sshErrMsg, sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700410 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
411 errCh <- appendInternalErr(err)
412 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700413
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700414 // 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 -0700415 ps1URL := "http://" + localAddr
416 if config.SkabandAddr != "" {
417 ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700418 }
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700419 if config.OpenBrowser {
420 browser.Open(ps1URL)
421 }
422 gitSrv.ps1URL.Store(&ps1URL)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700423 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700424
425 go func() {
426 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
427 cmd.Stdin = os.Stdin
428 cmd.Stdout = os.Stdout
429 cmd.Stderr = os.Stderr
430 errCh <- run(ctx, "docker attach", cmd)
431 }()
432
433 defer copyLogs()
434
435 for {
436 select {
437 case <-ctx.Done():
438 return ctx.Err()
439 case err := <-errCh:
440 if err != nil {
441 return appendInternalErr(fmt.Errorf("container process: %w", err))
442 }
443 return nil
444 }
445 }
446}
447
448func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
449 cmd := exec.CommandContext(ctx, cmdName, args...)
Earl Lee2e463fb2025-04-17 11:22:22 -0700450 start := time.Now()
451
452 out, err := cmd.CombinedOutput()
453 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700454 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 -0700455 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700456 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 -0700457 }
458 return out, err
459}
460
461func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
462 start := time.Now()
463 err := cmd.Run()
464 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700465 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 -0700466 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700467 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 -0700468 }
469 return err
470}
471
472type gitServer struct {
473 gitLn net.Listener
474 gitPort string
475 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700476 pass string
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700477 ps1URL atomic.Pointer[string]
Earl Lee2e463fb2025-04-17 11:22:22 -0700478}
479
480func (gs *gitServer) shutdown(ctx context.Context) {
481 gs.srv.Shutdown(ctx)
482 gs.gitLn.Close()
483}
484
485// Serve a git remote from the host for the container to fetch from and push to.
486func (gs *gitServer) serve(ctx context.Context) error {
487 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
488 return gs.srv.Serve(gs.gitLn)
489}
490
Philip Zeyliger254c49f2025-07-17 17:26:24 -0700491func newGitServer(gitRoot string, configureUpstreamPassthrough bool) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700492 ret := &gitServer{
493 pass: rand.Text(),
494 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700495
Earl Lee2e463fb2025-04-17 11:22:22 -0700496 gitLn, err := net.Listen("tcp4", ":0")
497 if err != nil {
498 return nil, fmt.Errorf("git listen: %w", err)
499 }
500 ret.gitLn = gitLn
501
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700502 browserC := make(chan bool, 1) // channel of browser open requests
503
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000504 go func() {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700505 for range browserC {
506 browser.Open(*ret.ps1URL.Load())
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000507 }
508 }()
509
Philip Zeyliger254c49f2025-07-17 17:26:24 -0700510 var hooksDir string
511 if configureUpstreamPassthrough {
512 hooksDir, err = setupHooksDir(gitRoot)
513 if err != nil {
514 return nil, fmt.Errorf("failed to setup hooks directory: %w", err)
515 }
516 }
517
518 srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, hooksDir: hooksDir, pass: []byte(ret.pass), browserC: browserC}}
Earl Lee2e463fb2025-04-17 11:22:22 -0700519 ret.srv = &srv
520
521 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
522 if err != nil {
523 return nil, fmt.Errorf("git port: %w", err)
524 }
525 ret.gitPort = gitPort
526 return ret, nil
527}
528
529func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
David Crawshaw69c67312025-04-17 13:42:00 -0700530 cmdArgs := []string{
531 "create",
David Crawshaw66cf74e2025-05-05 08:48:39 -0700532 "-i",
Earl Lee2e463fb2025-04-17 11:22:22 -0700533 "--name", cntrName,
534 "-p", hostPort + ":80", // forward container port 80 to a host port
David Crawshaw3659d872025-05-05 17:52:23 -0700535 "-e", "SKETCH_MODEL_API_KEY=" + config.ModelAPIKey,
Earl Lee2e463fb2025-04-17 11:22:22 -0700536 }
Philip Zeyliger3d2eff02025-05-27 09:30:31 -0700537 if !(config.OneShot || !config.TermUI) {
David Crawshaw66cf74e2025-05-05 08:48:39 -0700538 cmdArgs = append(cmdArgs, "-t")
539 }
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000540
541 for _, envVar := range getEnvForwardingFromGitConfig(ctx) {
542 cmdArgs = append(cmdArgs, "-e", envVar)
543 }
David Crawshaw5a7b3692025-05-05 16:49:15 -0700544 if config.ModelURL != "" {
David Crawshaw3659d872025-05-05 17:52:23 -0700545 cmdArgs = append(cmdArgs, "-e", "SKETCH_MODEL_URL="+config.ModelURL)
Earl Lee2e463fb2025-04-17 11:22:22 -0700546 }
547 if config.SketchPubKey != "" {
548 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
549 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700550 if config.SSHPort > 0 {
551 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
552 } else {
Philip Zeyliger87d29ef2025-05-16 20:25:28 -0700553 cmdArgs = append(cmdArgs, "-p", "0:22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700554 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700555 // colima does this by default, but Linux docker seems to need this set explicitly
556 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000557
David Crawshaw1bd636c2025-06-13 19:56:27 +0000558 // Add seccomp profile to prevent killing PID 1 (the sketch process itself)
559 // Write the seccomp profile to cache directory if it doesn't exist
560 seccompPath, err := ensureSeccompProfile(ctx)
561 if err != nil {
562 return fmt.Errorf("failed to create seccomp profile: %w", err)
563 }
564 cmdArgs = append(cmdArgs, "--security-opt", "seccomp="+seccompPath)
565
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700566 // Add subtrace environment variable if token is provided
567 if config.SubtraceToken != "" {
568 cmdArgs = append(cmdArgs, "-e", "SUBTRACE_TOKEN="+config.SubtraceToken)
569 cmdArgs = append(cmdArgs, "-e", "SUBTRACE_HTTP2=1")
570 }
571
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000572 // Add volume mounts if specified
573 for _, mount := range config.Mounts {
574 if mount != "" {
575 cmdArgs = append(cmdArgs, "-v", mount)
576 }
577 }
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700578 cmdArgs = append(cmdArgs, imgName)
579
580 // Add command: either [sketch] or [subtrace run -- sketch]
581 if config.SubtraceToken != "" {
582 cmdArgs = append(cmdArgs, "/usr/local/bin/subtrace", "run", "--", "/bin/sketch")
583 } else {
584 cmdArgs = append(cmdArgs, "/bin/sketch")
585 }
586
587 // Add all sketch arguments
588 cmdArgs = append(cmdArgs,
Earl Lee2e463fb2025-04-17 11:22:22 -0700589 "-unsafe",
590 "-addr=:80",
591 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000592 "-git-username="+config.GitUsername,
593 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000594 "-outside-hostname="+config.OutsideHostname,
595 "-outside-os="+config.OutsideOS,
596 "-outside-working-dir="+config.OutsideWorkingDir,
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000597 fmt.Sprintf("-max-dollars=%f", config.MaxDollars),
Josh Bleecher Snyder3cae7d92025-04-30 09:54:29 -0700598 "-open=false",
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700599 "-termui="+fmt.Sprintf("%t", config.TermUI),
Philip Zeyligercabfa552025-05-19 16:14:28 -0700600 "-verbose="+fmt.Sprintf("%t", config.Verbose),
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000601 "-x="+config.ExperimentFlag,
Philip Zeyligerbe7802a2025-06-04 20:15:25 +0000602 "-branch-prefix="+config.BranchPrefix,
philip.zeyliger6d3de482025-06-10 19:38:14 -0700603 "-link-to-github="+fmt.Sprintf("%t", config.LinkToGitHub),
Earl Lee2e463fb2025-04-17 11:22:22 -0700604 )
philip.zeyliger8773e682025-06-11 21:36:21 -0700605 // Set SSH connection string based on session ID for SSH Theater
606 cmdArgs = append(cmdArgs, "-ssh-connection-string=sketch-"+config.SessionID)
Josh Bleecher Snydera96f9d22025-07-11 02:47:33 +0000607 if relPath != "." {
608 cmdArgs = append(cmdArgs, "-C", relPath)
609 }
David Crawshaw5a7b3692025-05-05 16:49:15 -0700610 if config.Model != "" {
611 cmdArgs = append(cmdArgs, "-model="+config.Model)
612 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700613 if config.GitRemoteUrl != "" {
614 cmdArgs = append(cmdArgs, "-git-remote-url="+config.GitRemoteUrl)
615 if config.Commit == "" {
616 panic("Commit should have been set when GitRemoteUrl was set")
617 }
618 cmdArgs = append(cmdArgs, "-commit="+config.Commit)
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000619 cmdArgs = append(cmdArgs, "-upstream="+config.Upstream)
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700620 }
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000621 if config.OriginalGitOrigin != "" {
622 cmdArgs = append(cmdArgs, "-original-git-origin="+config.OriginalGitOrigin)
623 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700624 if config.OutsideHTTP != "" {
625 cmdArgs = append(cmdArgs, "-outside-http="+config.OutsideHTTP)
626 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000627 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
Pokey Rule0dcebe12025-04-28 14:51:04 +0100628 if config.Prompt != "" {
629 cmdArgs = append(cmdArgs, "-prompt", config.Prompt)
630 }
631 if config.OneShot {
632 cmdArgs = append(cmdArgs, "-one-shot")
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700633 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000634 if config.ModelURL == "" {
635 // Forward ANTHROPIC_API_KEY for direct use.
636 // TODO: have outtie run an http proxy?
637 // TODO: select and forward the relevant API key based on the model
638 cmdArgs = append(cmdArgs, "-llm-api-key="+os.Getenv("ANTHROPIC_API_KEY"))
639 }
Philip Zeyliger194bfa82025-06-24 06:03:06 -0700640 // Add MCP server configurations
641 for _, mcpServer := range config.MCPServers {
642 cmdArgs = append(cmdArgs, "-mcp", mcpServer)
643 }
Philip Zeyliger254c49f2025-07-17 17:26:24 -0700644 if config.PassthroughUpstream {
645 cmdArgs = append(cmdArgs, "-passthrough-upstream")
646 }
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000647
648 // Add additional docker arguments if provided
649 if config.DockerArgs != "" {
650 // Parse space-separated docker arguments with support for quotes and escaping
651 args := parseDockerArgs(config.DockerArgs)
652 // Insert arguments after "create" but before other arguments
653 for i := len(args) - 1; i >= 0; i-- {
654 cmdArgs = append(cmdArgs[:1], append([]string{args[i]}, cmdArgs[1:]...)...)
655 }
656 }
657
Earl Lee2e463fb2025-04-17 11:22:22 -0700658 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
659 return fmt.Errorf("docker create: %s, %w", out, err)
660 }
661 return nil
662}
663
Sean McCulloughae3480f2025-04-23 15:28:20 -0700664func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700665 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700666 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700667 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
668 } else {
669 v4, _, found := strings.Cut(string(out), "\n")
670 if !found {
671 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
672 }
673 localAddr = v4
674 if strings.HasPrefix(localAddr, "0.0.0.0") {
675 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
676 }
677 }
678 return localAddr, nil
679}
680
681// Contact the container and configure it.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700682func postContainerInitConfig(ctx context.Context, localAddr string, sshAvailable bool, sshError string, sshServerIdentity, sshAuthorizedKeys, sshContainerCAKey, sshHostCertificate []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700683 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700684
685 initMsg, err := json.Marshal(
686 server.InitRequest{
Sean McCullough7013e9e2025-05-14 02:03:58 +0000687 HostAddr: localAddr,
688 SSHAuthorizedKeys: sshAuthorizedKeys,
689 SSHServerIdentity: sshServerIdentity,
690 SSHContainerCAKey: sshContainerCAKey,
691 SSHHostCertificate: sshHostCertificate,
692 SSHAvailable: sshAvailable,
693 SSHError: sshError,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700694 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700695 if err != nil {
696 return fmt.Errorf("init msg: %w", err)
697 }
698
Earl Lee2e463fb2025-04-17 11:22:22 -0700699 // Note: this /init POST is handled in loop/server/loophttp.go:
700 initMsgByteReader := bytes.NewReader(initMsg)
701 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
702 if err != nil {
703 return err
704 }
705
706 var res *http.Response
707 for i := 0; ; i++ {
708 time.Sleep(100 * time.Millisecond)
709 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
710 initMsgByteReader.Reset(initMsg)
711 res, err = http.DefaultClient.Do(req)
712 if err != nil {
David Crawshaw99231ba2025-05-03 10:48:26 -0700713 if i < 100 {
714 if i%10 == 0 {
715 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
716 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700717 continue
718 }
719 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
720 }
721 break
722 }
723 resBytes, _ := io.ReadAll(res.Body)
724 if res.StatusCode != http.StatusOK {
725 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
726 }
727 return nil
728}
729
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700730func findOrBuildDockerImage(ctx context.Context, gitRoot, baseImage string, forceRebuild, verbose bool) (imgName string, err error) {
731 // Default to the published sketch image if no base image is specified
732 if baseImage == "" {
733 imageTag := dockerfileBaseHash()
734 baseImage = fmt.Sprintf("%s:%s", dockerImgName, imageTag)
Earl Lee2e463fb2025-04-17 11:22:22 -0700735 }
736
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700737 // Ensure the base image exists locally, pull if necessary
738 if err := ensureBaseImageExists(ctx, baseImage); err != nil {
739 return "", fmt.Errorf("failed to ensure base image %s exists: %w", baseImage, err)
740 }
741
742 // Get the base image container ID for caching
743 baseImageID, err := getDockerImageID(ctx, baseImage)
Earl Lee2e463fb2025-04-17 11:22:22 -0700744 if err != nil {
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700745 return "", fmt.Errorf("failed to get base image ID for %s: %w", baseImage, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700746 }
747
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700748 // Create a cache key based on base image ID and working directory
749 // Docker naming conventions restrict you to 20 characters per path component
750 // and only allow lowercase letters, digits, underscores, and dashes, so encoding
751 // the hash and the repo directory is sadly a bit of a non-starter.
752 cacheKey := createCacheKey(baseImageID, gitRoot)
753 imgName = "sketch-" + cacheKey
Earl Lee2e463fb2025-04-17 11:22:22 -0700754
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700755 // Check if the cached image exists and is up to date
756 if !forceRebuild {
757 if exists, err := dockerImageExists(ctx, imgName); err != nil {
758 return "", fmt.Errorf("failed to check if image exists: %w", err)
759 } else if exists {
760 if verbose {
761 fmt.Printf("using cached image %s\n", imgName)
Kilian Lackhove23772f42025-06-18 20:28:58 +0200762 }
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700763 return imgName, nil
David Crawshawb5f6a002025-05-05 08:27:16 -0700764 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700765 }
766
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700767 // Build the layered image
768 if err := buildLayeredImage(ctx, imgName, baseImage, gitRoot, verbose); err != nil {
769 return "", fmt.Errorf("failed to build layered image: %w", err)
770 }
771
772 return imgName, nil
773}
774
775// ensureBaseImageExists checks if the base image exists locally and pulls it if not
776func ensureBaseImageExists(ctx context.Context, imageName string) error {
777 exists, err := dockerImageExists(ctx, imageName)
778 if err != nil {
779 return fmt.Errorf("failed to check if image exists: %w", err)
780 }
781
782 if !exists {
783 fmt.Printf("🐋 pulling base image %s...\n", imageName)
784 if out, err := combinedOutput(ctx, "docker", "pull", imageName); err != nil {
785 return fmt.Errorf("docker pull %s failed: %s: %w", imageName, out, err)
786 }
787 fmt.Printf("✅ successfully pulled %s\n", imageName)
788 }
789
790 return nil
791}
792
793// getDockerImageID gets the container ID for a Docker image
794func getDockerImageID(ctx context.Context, imageName string) (string, error) {
795 out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{.Id}}", imageName)
796 if err != nil {
797 return "", err
798 }
799 return strings.TrimSpace(string(out)), nil
800}
801
802// createCacheKey creates a cache key from base image ID and working directory
803func createCacheKey(baseImageID, gitRoot string) string {
804 h := sha256.New()
805 h.Write([]byte(baseImageID))
806 h.Write([]byte(gitRoot))
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000807 // one-time cache-busting for the transition from copying git repos to only copying git objects
808 h.Write([]byte("git-objects"))
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700809 return hex.EncodeToString(h.Sum(nil))[:12] // Use first 12 chars for shorter name
810}
811
812// dockerImageExists checks if a Docker image exists locally
813func dockerImageExists(ctx context.Context, imageName string) (bool, error) {
814 out, err := combinedOutput(ctx, "docker", "inspect", imageName)
815 if err != nil {
816 if strings.Contains(strings.ToLower(string(out)), "no such object") ||
817 strings.Contains(strings.ToLower(string(out)), "no such image") {
818 return false, nil
819 }
820 return false, err
821 }
822 return true, nil
823}
824
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000825// buildLayeredImage builds a new Docker image by layering the repo on top of the base image.
826//
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700827// TODO: git config stuff could be environment variables at runtime for email and username.
828// The git docs seem to say that http.postBuffer is a bug in our git proxy more than a thing
829// that's needed, but we haven't found the bug yet!
Philip Zeyliger882b1d12025-07-02 20:04:08 -0700830//
831// TODO: There is a caching tension. A base image is great for tools (like, some version
832// of Go). Then you want a git repo, which is much faster to incrementally fetch rather
833// than cloning every time. Then you want some build artifacts, like perhaps the
834// "go mod download" cache, or the "go build" cache or the "npm install" cache.
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000835// The implementation here copies the git objects into the base image.
836// That enables fast clones into the container, because most of the git objects are already there.
837// It also avoids copying uncommitted changes, configs/hooks, etc.
Josh Bleecher Snyderfa424f52025-07-11 18:43:55 +0000838// We also set up fake temporary Go module(s) so we can run "go mod download".
839// TODO: maybe 'go list ./...' and then do a build as well to populate the build cache.
840// TODO: 'npm install', etc? We have the rails for it.
Josh Bleecher Snyder369f2622025-07-15 00:02:59 +0000841// If /app/.git already exists, we fetch from the existing repo instead of cloning.
842// This lets advanced users arrange their git repo exactly as they desire.
Philip Zeyliger882b1d12025-07-02 20:04:08 -0700843// Note that buildx has some support for conditional COPY, but without buildx, which
844// we can't reliably depend on, we have to run the base image to inspect its file system,
845// and then we can decide what to do.
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000846//
847// We may in the future want to enable people to bring along uncommitted changes to tracked files.
848// To do that, we would run `git stash create` in outie at launch time, treat HEAD as the base commit,
849// and add in the stash commit as a new commit atop it.
850// That would accurately model the base commit as well as the uncommitted changes.
851// (This wouldn't happen here, but at agent/container initialization time.)
852//
853// repoPath is the current working directory where sketch is being run from.
854func buildLayeredImage(ctx context.Context, imgName, baseImage, gitRoot string, verbose bool) error {
Josh Bleecher Snyderfa424f52025-07-11 18:43:55 +0000855 goModules, err := collectGoModules(ctx, gitRoot)
856 if err != nil {
857 return fmt.Errorf("failed to collect go modules: %w", err)
858 }
859
860 buf := new(strings.Builder)
861 line := func(msg string, args ...any) {
862 fmt.Fprintf(buf, msg+"\n", args...)
863 }
864
865 line("FROM %s", baseImage)
866 line("COPY . /git-ref")
867
868 for _, module := range goModules {
869 line("RUN mkdir -p /go-module")
870 line("RUN git --git-dir=/git-ref --work-tree=/go-module cat-file blob %s > /go-module/go.mod", module.modSHA)
871 if module.sumSHA != "" {
872 line("RUN git --git-dir=/git-ref --work-tree=/go-module cat-file blob %s > /go-module/go.sum", module.sumSHA)
873 }
874 // drop any replaced modules
875 line("RUN cd /go-module && go mod edit -json | jq -r '.Replace? // [] | .[] | .Old.Path' | xargs -r -I{} go mod edit -dropreplace={} -droprequire={}")
876 // grab what’s left, best effort only to avoid breaking on (say) private modules
877 line("RUN cd /go-module && go mod download || true")
878 line("RUN rm -rf /go-module")
879 }
880
881 line("WORKDIR /app")
882 line(`CMD ["/bin/sketch"]`)
883 dockerfileContent := buf.String()
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700884
885 // Create a temporary directory for the Dockerfile
886 tmpDir, err := os.MkdirTemp("", "sketch-docker-*")
887 if err != nil {
888 return fmt.Errorf("failed to create temporary directory: %w", err)
889 }
890 defer os.RemoveAll(tmpDir)
891
892 dockerfilePath := filepath.Join(tmpDir, "Dockerfile")
893 if err := os.WriteFile(dockerfilePath, []byte(dockerfileContent), 0o666); err != nil {
894 return fmt.Errorf("failed to write Dockerfile: %w", err)
895 }
896
897 // Get git user info
Earl Lee2e463fb2025-04-17 11:22:22 -0700898 var gitUserEmail, gitUserName string
899 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700900 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 -0700901 } else {
902 gitUserEmail = strings.TrimSpace(string(out))
903 }
904 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700905 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 -0700906 } else {
907 gitUserName = strings.TrimSpace(string(out))
908 }
909
910 start := time.Now()
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700911 cmdArgs := []string{
912 "build",
Earl Lee2e463fb2025-04-17 11:22:22 -0700913 "-t", imgName,
914 "-f", dockerfilePath,
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700915 "--build-arg", "GIT_USER_EMAIL=" + gitUserEmail,
916 "--build-arg", "GIT_USER_NAME=" + gitUserName,
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700917 ".",
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700918 }
919
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000920 commonDir, err := gitCommonDir(ctx, gitRoot)
921 if err != nil {
922 return fmt.Errorf("failed to get git common dir: %w", err)
923 }
924
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700925 cmd := exec.CommandContext(ctx, "docker", cmdArgs...)
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000926 cmd.Dir = commonDir
David Crawshaw31f15242025-05-06 16:03:49 -0700927 // We print the docker build output whether or not the user
928 // has selected --verbose. Building an image takes a while
929 // and this gives good context.
David Crawshawb5f6a002025-05-05 08:27:16 -0700930 cmd.Stdout = os.Stdout
931 cmd.Stderr = os.Stderr
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700932 fmt.Printf("🏗️ building docker image %s from base %s...\n", imgName, baseImage)
Earl Lee2e463fb2025-04-17 11:22:22 -0700933
934 err = run(ctx, "docker build", cmd)
935 if err != nil {
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700936 return fmt.Errorf("docker build failed: %v", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700937 }
938 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700939 return nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700940}
941
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000942// requireGitRepo confirms that path is within a git repository.
943func requireGitRepo(ctx context.Context, path string) error {
944 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-dir")
Earl Lee2e463fb2025-04-17 11:22:22 -0700945 cmd.Dir = path
946 out, err := cmd.CombinedOutput()
947 if err != nil {
948 if strings.Contains(string(out), "not a git repository") {
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000949 return fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
Earl Lee2e463fb2025-04-17 11:22:22 -0700950Consider one of the following options:
951 - cd to a different dir that is already part of a git repo first, or
952 - to create a new git repo from this directory (%s), run this command:
953
954 git init . && git commit --allow-empty -m "initial commit"
955
956and try running sketch again.
957`, path, path)
958 }
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000959 return fmt.Errorf("git rev-parse --git-dir: %s: %w", out, err)
960 }
961 return nil
962}
963
964// gitRepoRoot attempts to find the git repository root directory.
965// Returns an error if not in a git repository or if it's a bare repository.
966// This is used to calculate relative paths for preserving user's working directory context.
967func gitRepoRoot(ctx context.Context, path string) (string, error) {
968 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel")
969 cmd.Dir = path
970 out, err := cmd.CombinedOutput()
971 if err != nil {
Marc-Antoine Ruel467c3962025-06-29 13:32:59 -0400972 return "", fmt.Errorf("git rev-parse --show-toplevel: %s: %w", out, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700973 }
Marc-Antoine Ruel467c3962025-06-29 13:32:59 -0400974 // The returned path is absolute.
975 return strings.TrimSpace(string(out)), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700976}
977
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000978// gitCommonDir finds the git common directory for path.
979func gitCommonDir(ctx context.Context, path string) (string, error) {
980 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
981 cmd.Dir = path
982 out, err := cmd.CombinedOutput()
983 if err != nil {
984 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
985 }
986 gitCommonDir := strings.TrimSpace(string(out))
987 if !filepath.IsAbs(gitCommonDir) {
988 gitCommonDir = filepath.Join(path, gitCommonDir)
989 }
990 return gitCommonDir, nil
991}
992
Josh Bleecher Snyderfa424f52025-07-11 18:43:55 +0000993// goModuleInfo represents a Go module with its file paths and blob SHAs
994type goModuleInfo struct {
995 // modPath is the path to the go.mod file, for debugging
996 modPath string
997 // modSHA is the git blob SHA of the go.mod file
998 modSHA string
999 // sumSHA is the git blob SHA of the go.sum file, empty if no go.sum exists
1000 sumSHA string
1001}
1002
1003// collectGoModules returns all go.mod files in the git repository with their blob SHAs.
1004func collectGoModules(ctx context.Context, gitRoot string) ([]goModuleInfo, error) {
1005 cmd := exec.CommandContext(ctx, "git", "ls-files", "-z", "*.mod")
1006 cmd.Dir = gitRoot
1007 out, err := cmd.CombinedOutput()
1008 if err != nil {
1009 return nil, fmt.Errorf("git ls-files -z *.mod: %s: %w", out, err)
1010 }
1011
1012 modFiles := strings.Split(string(out), "\x00")
1013 var modules []goModuleInfo
1014 for _, file := range modFiles {
1015 if filepath.Base(file) != "go.mod" {
1016 continue
1017 }
1018
1019 modSHA, err := getGitBlobSHA(ctx, gitRoot, file)
1020 if err != nil {
1021 return nil, fmt.Errorf("failed to get blob SHA for %s: %w", file, err)
1022 }
1023
1024 // If corresponding go.sum exists, get its SHA
1025 sumFile := filepath.Join(filepath.Dir(file), "go.sum")
1026 sumSHA, _ := getGitBlobSHA(ctx, gitRoot, sumFile) // best effort
1027
1028 modules = append(modules, goModuleInfo{
1029 modPath: file,
1030 modSHA: modSHA,
1031 sumSHA: sumSHA,
1032 })
1033 }
1034
1035 return modules, nil
1036}
1037
1038// getGitBlobSHA returns the git blob SHA for a file at HEAD
1039func getGitBlobSHA(ctx context.Context, gitRoot, filePath string) (string, error) {
1040 cmd := exec.CommandContext(ctx, "git", "rev-parse", "HEAD:"+filePath)
1041 cmd.Dir = gitRoot
1042 out, err := cmd.CombinedOutput()
1043 if err != nil {
1044 return "", fmt.Errorf("git rev-parse HEAD:%s: %s: %w", filePath, out, err)
1045 }
1046 return strings.TrimSpace(string(out)), nil
1047}
1048
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +00001049// getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker
1050// from git config using the sketch.envfwd multi-valued key.
1051func getEnvForwardingFromGitConfig(ctx context.Context) []string {
1052 outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput()
1053 out := string(outb)
1054 if err != nil {
1055 if strings.Contains(out, "key does not exist") {
1056 return nil
1057 }
1058 slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out)
1059 return nil
1060 }
1061
1062 var envVars []string
1063 for envVar := range strings.Lines(out) {
1064 envVar = strings.TrimSpace(envVar)
1065 if envVar == "" {
1066 continue
1067 }
1068 envVars = append(envVars, envVar+"="+os.Getenv(envVar))
1069 }
1070 return envVars
1071}
Philip Zeyliger1dc21372025-05-05 19:54:44 +00001072
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +00001073// getOriginalGitOrigin returns the URL of the git remote 'origin' if it exists in the given directory
1074func getOriginalGitOrigin(ctx context.Context, dir string) string {
1075 cmd := exec.CommandContext(ctx, "git", "config", "--get", "remote.origin.url")
1076 cmd.Dir = dir
1077 out, err := cmd.Output()
1078 if err != nil {
1079 return ""
1080 }
1081 return strings.TrimSpace(string(out))
1082}
1083
Philip Zeyliger1dc21372025-05-05 19:54:44 +00001084// parseDockerArgs parses a string containing space-separated Docker arguments into an array of strings.
1085// It handles quoted arguments and escaped characters.
1086//
1087// Examples:
1088//
1089// --memory=2g --cpus=2 -> ["--memory=2g", "--cpus=2"]
1090// --label="my label" --env=FOO=bar -> ["--label=my label", "--env=FOO=bar"]
1091// --env="KEY=\"quoted value\"" -> ["--env=KEY=\"quoted value\""]
1092func parseDockerArgs(args string) []string {
1093 if args = strings.TrimSpace(args); args == "" {
1094 return []string{}
1095 }
1096
1097 var result []string
1098 var current strings.Builder
1099 inQuotes := false
1100 escapeNext := false
1101 quoteChar := rune(0)
1102
1103 for _, char := range args {
1104 if escapeNext {
1105 current.WriteRune(char)
1106 escapeNext = false
1107 continue
1108 }
1109
1110 if char == '\\' {
1111 escapeNext = true
1112 continue
1113 }
1114
1115 if char == '"' || char == '\'' {
1116 if !inQuotes {
1117 inQuotes = true
1118 quoteChar = char
1119 continue
1120 } else if char == quoteChar {
1121 inQuotes = false
1122 quoteChar = rune(0)
1123 continue
1124 }
1125 // Non-matching quote character inside quotes
1126 current.WriteRune(char)
1127 continue
1128 }
1129
1130 // Space outside of quotes is an argument separator
1131 if char == ' ' && !inQuotes {
1132 if current.Len() > 0 {
1133 result = append(result, current.String())
1134 current.Reset()
1135 }
1136 continue
1137 }
1138
1139 current.WriteRune(char)
1140 }
1141
1142 // Add the last argument if there is one
1143 if current.Len() > 0 {
1144 result = append(result, current.String())
1145 }
1146
1147 return result
1148}
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001149
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001150// copyEmbeddedLinuxBinaryToContainer copies the embedded linux binary to the container
1151func copyEmbeddedLinuxBinaryToContainer(ctx context.Context, containerName string) error {
Josh Bleecher Snyder5ae245b2025-07-08 22:00:24 +00001152 out, err := combinedOutput(ctx, "docker", "version", "--format", "{{.Server.Arch}}")
1153 if err != nil {
1154 return fmt.Errorf("failed to detect Docker server architecture: %s: %w", out, err)
1155 }
1156 arch := strings.TrimSpace(string(out))
1157
1158 bin := embedded.LinuxBinary(arch)
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001159 if bin == nil {
Josh Bleecher Snyder5ae245b2025-07-08 22:00:24 +00001160 return fmt.Errorf("no embedded linux binary for architecture %q", arch)
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001161 }
1162
Josh Bleecher Snyderc9898fd2025-07-08 21:09:18 +00001163 // Stream a tarball to docker cp.
1164 pr, pw := io.Pipe()
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001165
Josh Bleecher Snyderc9898fd2025-07-08 21:09:18 +00001166 errCh := make(chan error, 1)
1167 go func() {
1168 defer pw.Close()
1169 tw := tar.NewWriter(pw)
1170
1171 hdr := &tar.Header{
1172 Name: "bin/sketch", // final path inside the container
1173 Mode: 0o700,
1174 Size: int64(len(bin)),
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001175 }
Josh Bleecher Snyderc9898fd2025-07-08 21:09:18 +00001176 if err := tw.WriteHeader(hdr); err != nil {
1177 errCh <- fmt.Errorf("failed to write tar header: %w", err)
1178 return
1179 }
1180 if _, err := tw.Write(bin); err != nil {
1181 errCh <- fmt.Errorf("failed to write binary to tar: %w", err)
1182 return
1183 }
1184 if err := tw.Close(); err != nil {
1185 errCh <- fmt.Errorf("failed to close tar writer: %w", err)
1186 return
1187 }
1188 errCh <- nil
1189 }()
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001190
Josh Bleecher Snyderc9898fd2025-07-08 21:09:18 +00001191 cmd := exec.CommandContext(ctx, "docker", "cp", "-", containerName+":/")
1192 cmd.Stdin = pr
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001193
Josh Bleecher Snyderc9898fd2025-07-08 21:09:18 +00001194 out, cmdErr := cmd.CombinedOutput()
1195
1196 if tarErr := <-errCh; tarErr != nil {
1197 return tarErr
1198 }
1199 if cmdErr != nil {
1200 return fmt.Errorf("docker cp failed: %s: %w", out, cmdErr)
1201 }
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001202 return nil
1203}
1204
David Crawshaw1bd636c2025-06-13 19:56:27 +00001205const seccompProfile = `{
1206 "defaultAction": "SCMP_ACT_ALLOW",
1207 "syscalls": [
1208 {
1209 "names": ["kill", "tkill", "tgkill", "pidfd_send_signal"],
1210 "action": "SCMP_ACT_ERRNO",
1211 "args": [
1212 {
1213 "index": 0,
1214 "value": 1,
1215 "op": "SCMP_CMP_EQ"
1216 }
1217 ]
1218 }
1219 ]
1220}`
1221
1222// ensureSeccompProfile creates the seccomp profile file in the sketch cache directory if it doesn't exist.
1223func ensureSeccompProfile(ctx context.Context) (seccompPath string, err error) {
1224 homeDir, err := os.UserHomeDir()
1225 if err != nil {
1226 return "", fmt.Errorf("failed to get home directory: %w", err)
1227 }
1228 cacheDir := filepath.Join(homeDir, ".cache", "sketch")
1229 if err := os.MkdirAll(cacheDir, 0o755); err != nil {
1230 return "", fmt.Errorf("failed to create cache directory: %w", err)
1231 }
1232 seccompPath = filepath.Join(cacheDir, "seccomp-no-kill-1.json")
1233
1234 curBytes, err := os.ReadFile(seccompPath)
1235 if err != nil && !os.IsNotExist(err) {
1236 return "", fmt.Errorf("failed to read seccomp profile file %s: %w", seccompPath, err)
1237 }
1238 if string(curBytes) == seccompProfile {
1239 return seccompPath, nil // File already exists and matches the expected profile
1240 }
1241
1242 if err := os.WriteFile(seccompPath, []byte(seccompProfile), 0o644); err != nil {
1243 return "", fmt.Errorf("failed to write seccomp profile to %s: %w", seccompPath, err)
1244 }
1245 slog.DebugContext(ctx, "created seccomp profile", "path", seccompPath)
1246 return seccompPath, nil
1247}