blob: ba93ed0aee2238270bd24e7fe4cae2b47f2632bd [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
Josh Bleecher Snydere75d0ea2025-07-21 23:50:44 +0000142
Josh Bleecher Snyder57afbca2025-07-23 13:29:59 -0700143 // DumpLLM requests dumping of raw communications with LLM services to files
144 DumpLLM bool
Josh Bleecher Snyder1e551672025-07-30 03:16:54 +0000145
146 // FetchOnLaunch enables git fetch during initialization
147 FetchOnLaunch bool
Earl Lee2e463fb2025-04-17 11:22:22 -0700148}
149
150// LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it.
151// It writes status to stdout.
David Crawshawb5f6a002025-05-05 08:27:16 -0700152func LaunchContainer(ctx context.Context, config ContainerConfig) error {
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700153 slog.Debug("Container Config", slog.String("config", fmt.Sprintf("%+v", config)))
Earl Lee2e463fb2025-04-17 11:22:22 -0700154 if _, err := exec.LookPath("docker"); err != nil {
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700155 if runtime.GOOS == "darwin" {
156 return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start")
157 } else {
158 return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)")
159 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700160 }
161
162 if out, err := combinedOutput(ctx, "docker", "ps"); err != nil {
163 // `docker ps` provides a good error message here that can be
164 // easily chatgpt'ed by users, so send it to the user as-is:
165 // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
166 return fmt.Errorf("docker ps: %s (%w)", out, err)
167 }
168
169 _, hostPort, err := net.SplitHostPort(config.LocalAddr)
170 if err != nil {
171 return err
172 }
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000173 // Bail early if sketch was started from a path that isn't in a git repo.
174 err = requireGitRepo(ctx, config.Path)
Earl Lee2e463fb2025-04-17 11:22:22 -0700175 if err != nil {
176 return err
177 }
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000178
179 // Best effort attempt to get repo root; fall back to current directory.
180 gitRoot := config.Path
181 if root, err := gitRepoRoot(ctx, config.Path); err == nil {
182 gitRoot = root
183 }
184
185 // Capture the original git origin URL before we set up the temporary git server
186 config.OriginalGitOrigin = getOriginalGitOrigin(ctx, gitRoot)
187
Philip Zeyliger254c49f2025-07-17 17:26:24 -0700188 // If we've got an upstream, let's configure
189 if config.OriginalGitOrigin != "" {
190 config.PassthroughUpstream = true
191 }
192
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700193 imgName, err := findOrBuildDockerImage(ctx, gitRoot, config.BaseImage, config.ForceRebuild, config.Verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700194 if err != nil {
195 return err
196 }
197
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000198 cntrName := "sketch-" + config.SessionID
Earl Lee2e463fb2025-04-17 11:22:22 -0700199 defer func() {
200 if config.NoCleanup {
201 return
202 }
203 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
204 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
205 _ = out
206 }
207 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
208 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
209 _ = out
210 }
211 }()
212
213 // errCh receives errors from operations that this function calls in separate goroutines.
214 errCh := make(chan error)
215
Josh Bleecher Snyder725cfe02025-07-18 01:31:06 +0000216 var upstream string
217 if out, err := combinedOutput(ctx, "git", "branch", "--show-current"); err != nil {
218 slog.DebugContext(ctx, "git branch --show-current failed (continuing)", "error", err)
219 } else {
220 upstream = strings.TrimSpace(string(out))
221 }
222
Earl Lee2e463fb2025-04-17 11:22:22 -0700223 // Start the git server
Josh Bleecher Snyder725cfe02025-07-18 01:31:06 +0000224 gitSrv, err := newGitServer(gitRoot, config.PassthroughUpstream, upstream)
Earl Lee2e463fb2025-04-17 11:22:22 -0700225 if err != nil {
226 return fmt.Errorf("failed to start git server: %w", err)
227 }
228 defer gitSrv.shutdown(ctx)
229
230 go func() {
231 errCh <- gitSrv.serve(ctx)
232 }()
233
philz24613202025-07-15 20:56:21 -0700234 // Check if we have any commits, and if not, create an empty initial commit
235 cmd := exec.CommandContext(ctx, "git", "rev-list", "--all", "--count")
236 countOut, err := cmd.CombinedOutput()
237 if err != nil {
238 return fmt.Errorf("git rev-list --all --count: %s: %w", countOut, err)
239 }
240 commitCount := strings.TrimSpace(string(countOut))
241 if commitCount == "0" {
242 slog.Info("No commits found, creating empty initial commit")
243 cmd = exec.CommandContext(ctx, "git", "commit", "--allow-empty", "-m", "Initial empty commit")
244 if commitOut, err := cmd.CombinedOutput(); err != nil {
245 return fmt.Errorf("git commit --allow-empty: %s: %w", commitOut, err)
246 }
247 }
248
Earl Lee2e463fb2025-04-17 11:22:22 -0700249 // Get the current host git commit
250 var commit string
Philip Zeyligera347b172025-06-04 16:18:57 +0000251 if out, err := combinedOutput(ctx, "git", "rev-parse", "HEAD"); err != nil {
252 return fmt.Errorf("git rev-parse HEAD: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700253 } else {
254 commit = strings.TrimSpace(string(out))
255 }
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000256
Earl Lee2e463fb2025-04-17 11:22:22 -0700257 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
258 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
259 }
260
261 relPath, err := filepath.Rel(gitRoot, config.Path)
262 if err != nil {
263 return err
264 }
265
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700266 config.OutsideHTTP = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitSrv.pass, gitSrv.gitPort)
267 config.GitRemoteUrl = fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitSrv.pass, gitSrv.gitPort)
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000268 config.Upstream = upstream
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700269 config.Commit = commit
270
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -0700271 // Create the sketch container, copy over linux sketch
Earl Lee2e463fb2025-04-17 11:22:22 -0700272 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000273 return fmt.Errorf("failed to create docker container: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700274 }
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -0700275 if err := copyEmbeddedLinuxBinaryToContainer(ctx, cntrName); err != nil {
276 return fmt.Errorf("failed to copy linux binary to container: %w", err)
David Crawshaw8bff16a2025-04-18 01:16:49 -0700277 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700278
David Crawshaw53786ef2025-04-24 12:52:51 -0700279 fmt.Printf("📦 running in container %s\n", cntrName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700280
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700281 // Setup subtrace if token is provided (development only) - after container creation, before start
282 if config.SubtraceToken != "" {
283 fmt.Println("🔍 Setting up subtrace (development only)")
284 if err := setupSubtraceBeforeStart(ctx, cntrName, config.SubtraceToken); err != nil {
285 return fmt.Errorf("failed to setup subtrace: %w", err)
286 }
287 }
288
Earl Lee2e463fb2025-04-17 11:22:22 -0700289 // Start the sketch container
290 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
291 return fmt.Errorf("docker start: %s, %w", out, err)
292 }
293
294 // Copies structured logs from the container to the host.
295 copyLogs := func() {
296 if config.ContainerLogDest == "" {
297 return
298 }
299 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
300 if err != nil {
301 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
302 return
303 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700304 prefix := []byte("structured logs:")
305 for line := range bytes.Lines(out) {
306 rest, ok := bytes.CutPrefix(line, prefix)
307 if !ok {
Earl Lee2e463fb2025-04-17 11:22:22 -0700308 continue
309 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700310 logFile := string(bytes.TrimSpace(rest))
Earl Lee2e463fb2025-04-17 11:22:22 -0700311 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
312 logFileName := filepath.Base(logFile)
313 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
314 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
315 if err != nil {
316 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
317 }
318 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
319 }
320 }
321
322 // NOTE: we want to see what the internal sketch binary prints
323 // regardless of the setting of the verbosity flag on the external
324 // binary, so reading "docker logs", which is the stdout/stderr of
325 // the internal binary is not conditional on the verbose flag.
326 appendInternalErr := func(err error) error {
327 if err == nil {
328 return nil
329 }
330 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000331 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700332 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
333 }
334 out = bytes.TrimSpace(out)
335 if len(out) > 0 {
336 return fmt.Errorf("docker logs: %s;\n%w", out, err)
337 }
338 return err
339 }
340
341 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700342 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700343 if err != nil {
344 return appendInternalErr(err)
345 }
346
Philip Zeyliger00442412025-05-14 11:03:23 -0700347 if config.Verbose {
348 fmt.Fprintf(os.Stderr, "Host web server: http://%s/\n", localAddr)
349 }
350
Sean McCulloughae3480f2025-04-23 15:28:20 -0700351 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
352 if err != nil {
353 return appendInternalErr(err)
354 }
355 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
356 if err != nil {
David Crawshawb5f6a002025-05-05 08:27:16 -0700357 return appendInternalErr(fmt.Errorf("failed to split ssh host and port: %w", err))
Sean McCulloughae3480f2025-04-23 15:28:20 -0700358 }
Sean McCullough4854c652025-04-24 18:37:02 -0700359
Sean McCullough7013e9e2025-05-14 02:03:58 +0000360 var sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate []byte
Sean McCullough4854c652025-04-24 18:37:02 -0700361
banksean29d689f2025-06-23 15:41:26 +0000362 cst, err := NewLocalSSHimmer(cntrName, sshHost, sshPort)
Sean McCullough078e85a2025-05-08 17:28:34 -0700363 if err != nil {
364 return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err))
365 }
366
367 sshErr := CheckSSHReachability(cntrName)
Sean McCullough15c95282025-05-08 16:48:38 -0700368 sshAvailable := false
369 sshErrMsg := ""
370 if sshErr != nil {
371 fmt.Println(sshErr.Error())
372 sshErrMsg = sshErr.Error()
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700373 // continue - ssh config is not required for the rest of sketch to function locally.
374 } else {
Sean McCullough15c95282025-05-08 16:48:38 -0700375 sshAvailable = true
Sean McCulloughea3fc202025-04-28 12:53:37 -0700376 // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find:
377 // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700378 fmt.Printf(`Connect to this container via any of these methods:
Sean McCullough4854c652025-04-24 18:37:02 -0700379🖥️ ssh %s
380🖥️ code --remote ssh-remote+root@%s /app -n
Sean McCulloughea3fc202025-04-28 12:53:37 -0700381🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank
Sean McCullough4854c652025-04-24 18:37:02 -0700382`, cntrName, cntrName, cntrName)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700383 sshUserIdentity = cst.userIdentity
384 sshServerIdentity = cst.serverIdentity
Sean McCullough7013e9e2025-05-14 02:03:58 +0000385
386 // Get the Container CA public key for mutual auth
387 if cst.containerCAPublicKey != nil {
388 containerCAPublicKey = ssh.MarshalAuthorizedKey(cst.containerCAPublicKey)
389 fmt.Println("🔒 SSH Mutual Authentication enabled (container will verify host)")
390 }
391
392 // Get the host certificate for mutual auth
393 hostCertificate = cst.hostCertificate
394
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700395 defer func() {
396 if err := cst.Cleanup(); err != nil {
397 appendInternalErr(err)
398 }
399 }()
400 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700401
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700402 // Tell the sketch container to Init(), which starts the SSH server
403 // and checks out the right commit.
404 // TODO: I'm trying to move as much configuration as possible into the command-line
405 // arguments to avoid splitting them up. "localAddr" is the only difficult one:
406 // we run (effectively) "docker run -p 0:80 image sketch -flags" and you can't
407 // get the port Docker chose until after the process starts. The SSH config is
408 // mostly available ahead of time, but whether it works ("sshAvailable"/"sshErrMsg")
409 // may also empirically need to be done after the SSH server is up and running.
Earl Lee2e463fb2025-04-17 11:22:22 -0700410 go func() {
411 // TODO: Why is this called in a goroutine? I have found that when I pull this out
412 // of the goroutine and call it inline, then the terminal UI clears itself and all
413 // the scrollback (which is not good, but also not fatal). I can't see why it does this
414 // though, since none of the calls in postContainerInitConfig obviously write to stdout
415 // or stderr.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700416 if err := postContainerInitConfig(ctx, localAddr, sshAvailable, sshErrMsg, sshServerIdentity, sshUserIdentity, containerCAPublicKey, hostCertificate); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700417 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
418 errCh <- appendInternalErr(err)
419 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700420
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700421 // 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 -0700422 ps1URL := "http://" + localAddr
423 if config.SkabandAddr != "" {
424 ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700425 }
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700426 if config.OpenBrowser {
427 browser.Open(ps1URL)
428 }
429 gitSrv.ps1URL.Store(&ps1URL)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700430 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700431
432 go func() {
433 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
434 cmd.Stdin = os.Stdin
435 cmd.Stdout = os.Stdout
436 cmd.Stderr = os.Stderr
437 errCh <- run(ctx, "docker attach", cmd)
438 }()
439
440 defer copyLogs()
441
442 for {
443 select {
444 case <-ctx.Done():
445 return ctx.Err()
446 case err := <-errCh:
447 if err != nil {
448 return appendInternalErr(fmt.Errorf("container process: %w", err))
449 }
450 return nil
451 }
452 }
453}
454
455func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
456 cmd := exec.CommandContext(ctx, cmdName, args...)
Earl Lee2e463fb2025-04-17 11:22:22 -0700457 start := time.Now()
458
459 out, err := cmd.CombinedOutput()
460 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700461 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 -0700462 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700463 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 -0700464 }
465 return out, err
466}
467
468func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
469 start := time.Now()
470 err := cmd.Run()
471 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700472 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 -0700473 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700474 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 -0700475 }
476 return err
477}
478
479type gitServer struct {
480 gitLn net.Listener
481 gitPort string
482 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700483 pass string
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700484 ps1URL atomic.Pointer[string]
Earl Lee2e463fb2025-04-17 11:22:22 -0700485}
486
487func (gs *gitServer) shutdown(ctx context.Context) {
488 gs.srv.Shutdown(ctx)
489 gs.gitLn.Close()
490}
491
492// Serve a git remote from the host for the container to fetch from and push to.
493func (gs *gitServer) serve(ctx context.Context) error {
494 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
495 return gs.srv.Serve(gs.gitLn)
496}
497
Josh Bleecher Snyder725cfe02025-07-18 01:31:06 +0000498func newGitServer(gitRoot string, configureUpstreamPassthrough bool, upstream string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700499 ret := &gitServer{
500 pass: rand.Text(),
501 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700502
Earl Lee2e463fb2025-04-17 11:22:22 -0700503 gitLn, err := net.Listen("tcp4", ":0")
504 if err != nil {
505 return nil, fmt.Errorf("git listen: %w", err)
506 }
507 ret.gitLn = gitLn
508
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700509 browserC := make(chan bool, 1) // channel of browser open requests
510
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000511 go func() {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700512 for range browserC {
513 browser.Open(*ret.ps1URL.Load())
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000514 }
515 }()
516
Philip Zeyliger254c49f2025-07-17 17:26:24 -0700517 var hooksDir string
518 if configureUpstreamPassthrough {
Josh Bleecher Snyder725cfe02025-07-18 01:31:06 +0000519 hooksDir, err = setupHooksDir(upstream)
Philip Zeyliger254c49f2025-07-17 17:26:24 -0700520 if err != nil {
521 return nil, fmt.Errorf("failed to setup hooks directory: %w", err)
522 }
523 }
524
525 srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, hooksDir: hooksDir, pass: []byte(ret.pass), browserC: browserC}}
Earl Lee2e463fb2025-04-17 11:22:22 -0700526 ret.srv = &srv
527
528 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
529 if err != nil {
530 return nil, fmt.Errorf("git port: %w", err)
531 }
532 ret.gitPort = gitPort
533 return ret, nil
534}
535
536func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
David Crawshaw69c67312025-04-17 13:42:00 -0700537 cmdArgs := []string{
538 "create",
David Crawshaw66cf74e2025-05-05 08:48:39 -0700539 "-i",
Earl Lee2e463fb2025-04-17 11:22:22 -0700540 "--name", cntrName,
541 "-p", hostPort + ":80", // forward container port 80 to a host port
David Crawshaw3659d872025-05-05 17:52:23 -0700542 "-e", "SKETCH_MODEL_API_KEY=" + config.ModelAPIKey,
Earl Lee2e463fb2025-04-17 11:22:22 -0700543 }
Philip Zeyliger3d2eff02025-05-27 09:30:31 -0700544 if !(config.OneShot || !config.TermUI) {
David Crawshaw66cf74e2025-05-05 08:48:39 -0700545 cmdArgs = append(cmdArgs, "-t")
546 }
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000547
548 for _, envVar := range getEnvForwardingFromGitConfig(ctx) {
549 cmdArgs = append(cmdArgs, "-e", envVar)
550 }
David Crawshaw5a7b3692025-05-05 16:49:15 -0700551 if config.ModelURL != "" {
David Crawshaw3659d872025-05-05 17:52:23 -0700552 cmdArgs = append(cmdArgs, "-e", "SKETCH_MODEL_URL="+config.ModelURL)
Earl Lee2e463fb2025-04-17 11:22:22 -0700553 }
554 if config.SketchPubKey != "" {
555 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
556 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700557 if config.SSHPort > 0 {
558 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
559 } else {
Philip Zeyliger87d29ef2025-05-16 20:25:28 -0700560 cmdArgs = append(cmdArgs, "-p", "0:22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700561 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700562 // colima does this by default, but Linux docker seems to need this set explicitly
563 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000564
David Crawshaw1bd636c2025-06-13 19:56:27 +0000565 // Add seccomp profile to prevent killing PID 1 (the sketch process itself)
566 // Write the seccomp profile to cache directory if it doesn't exist
567 seccompPath, err := ensureSeccompProfile(ctx)
568 if err != nil {
569 return fmt.Errorf("failed to create seccomp profile: %w", err)
570 }
571 cmdArgs = append(cmdArgs, "--security-opt", "seccomp="+seccompPath)
572
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700573 // Add subtrace environment variable if token is provided
574 if config.SubtraceToken != "" {
575 cmdArgs = append(cmdArgs, "-e", "SUBTRACE_TOKEN="+config.SubtraceToken)
576 cmdArgs = append(cmdArgs, "-e", "SUBTRACE_HTTP2=1")
577 }
578
Josh Bleecher Snyderac761c92025-05-16 18:58:45 +0000579 // Add volume mounts if specified
580 for _, mount := range config.Mounts {
581 if mount != "" {
582 cmdArgs = append(cmdArgs, "-v", mount)
583 }
584 }
Philip Zeyligerd4be7a22025-06-15 09:39:00 -0700585 cmdArgs = append(cmdArgs, imgName)
586
587 // Add command: either [sketch] or [subtrace run -- sketch]
588 if config.SubtraceToken != "" {
589 cmdArgs = append(cmdArgs, "/usr/local/bin/subtrace", "run", "--", "/bin/sketch")
590 } else {
591 cmdArgs = append(cmdArgs, "/bin/sketch")
592 }
593
594 // Add all sketch arguments
595 cmdArgs = append(cmdArgs,
Earl Lee2e463fb2025-04-17 11:22:22 -0700596 "-unsafe",
597 "-addr=:80",
598 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000599 "-git-username="+config.GitUsername,
600 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000601 "-outside-hostname="+config.OutsideHostname,
602 "-outside-os="+config.OutsideOS,
603 "-outside-working-dir="+config.OutsideWorkingDir,
Josh Bleecher Snyder33032d32025-05-30 16:28:21 +0000604 fmt.Sprintf("-max-dollars=%f", config.MaxDollars),
Josh Bleecher Snyder3cae7d92025-04-30 09:54:29 -0700605 "-open=false",
Philip Zeyliger613c0f52025-05-15 16:36:22 -0700606 "-termui="+fmt.Sprintf("%t", config.TermUI),
Philip Zeyligercabfa552025-05-19 16:14:28 -0700607 "-verbose="+fmt.Sprintf("%t", config.Verbose),
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000608 "-x="+config.ExperimentFlag,
Philip Zeyligerbe7802a2025-06-04 20:15:25 +0000609 "-branch-prefix="+config.BranchPrefix,
philip.zeyliger6d3de482025-06-10 19:38:14 -0700610 "-link-to-github="+fmt.Sprintf("%t", config.LinkToGitHub),
Earl Lee2e463fb2025-04-17 11:22:22 -0700611 )
philip.zeyliger8773e682025-06-11 21:36:21 -0700612 // Set SSH connection string based on session ID for SSH Theater
613 cmdArgs = append(cmdArgs, "-ssh-connection-string=sketch-"+config.SessionID)
Josh Bleecher Snydera96f9d22025-07-11 02:47:33 +0000614 if relPath != "." {
615 cmdArgs = append(cmdArgs, "-C", relPath)
616 }
David Crawshaw5a7b3692025-05-05 16:49:15 -0700617 if config.Model != "" {
618 cmdArgs = append(cmdArgs, "-model="+config.Model)
619 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700620 if config.GitRemoteUrl != "" {
621 cmdArgs = append(cmdArgs, "-git-remote-url="+config.GitRemoteUrl)
622 if config.Commit == "" {
623 panic("Commit should have been set when GitRemoteUrl was set")
624 }
625 cmdArgs = append(cmdArgs, "-commit="+config.Commit)
Josh Bleecher Snyder664404e2025-06-04 21:56:42 +0000626 cmdArgs = append(cmdArgs, "-upstream="+config.Upstream)
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700627 }
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000628 if config.OriginalGitOrigin != "" {
629 cmdArgs = append(cmdArgs, "-original-git-origin="+config.OriginalGitOrigin)
630 }
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700631 if config.OutsideHTTP != "" {
632 cmdArgs = append(cmdArgs, "-outside-http="+config.OutsideHTTP)
633 }
Josh Bleecher Snydere3c2f222025-05-15 20:54:52 +0000634 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
Pokey Rule0dcebe12025-04-28 14:51:04 +0100635 if config.Prompt != "" {
636 cmdArgs = append(cmdArgs, "-prompt", config.Prompt)
637 }
638 if config.OneShot {
639 cmdArgs = append(cmdArgs, "-one-shot")
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700640 }
Josh Bleecher Snyder93860092025-07-23 13:24:14 -0700641 cmdArgs = append(cmdArgs, "-llm-api-key="+config.ModelAPIKey)
Philip Zeyliger194bfa82025-06-24 06:03:06 -0700642 // Add MCP server configurations
643 for _, mcpServer := range config.MCPServers {
644 cmdArgs = append(cmdArgs, "-mcp", mcpServer)
645 }
Philip Zeyliger254c49f2025-07-17 17:26:24 -0700646 if config.PassthroughUpstream {
647 cmdArgs = append(cmdArgs, "-passthrough-upstream")
648 }
Josh Bleecher Snyder57afbca2025-07-23 13:29:59 -0700649 if config.DumpLLM {
650 cmdArgs = append(cmdArgs, "-dump-llm")
Josh Bleecher Snydere75d0ea2025-07-21 23:50:44 +0000651 }
Josh Bleecher Snyder1e551672025-07-30 03:16:54 +0000652 if !config.FetchOnLaunch {
653 cmdArgs = append(cmdArgs, "-fetch-on-launch=false")
654 }
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000655
656 // Add additional docker arguments if provided
657 if config.DockerArgs != "" {
658 // Parse space-separated docker arguments with support for quotes and escaping
659 args := parseDockerArgs(config.DockerArgs)
660 // Insert arguments after "create" but before other arguments
661 for i := len(args) - 1; i >= 0; i-- {
662 cmdArgs = append(cmdArgs[:1], append([]string{args[i]}, cmdArgs[1:]...)...)
663 }
664 }
665
Earl Lee2e463fb2025-04-17 11:22:22 -0700666 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
667 return fmt.Errorf("docker create: %s, %w", out, err)
668 }
669 return nil
670}
671
Sean McCulloughae3480f2025-04-23 15:28:20 -0700672func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700673 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700674 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700675 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
676 } else {
677 v4, _, found := strings.Cut(string(out), "\n")
678 if !found {
679 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
680 }
681 localAddr = v4
682 if strings.HasPrefix(localAddr, "0.0.0.0") {
683 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
684 }
685 }
686 return localAddr, nil
687}
688
689// Contact the container and configure it.
Philip Zeyligerbc8c8dc2025-05-21 13:19:13 -0700690func postContainerInitConfig(ctx context.Context, localAddr string, sshAvailable bool, sshError string, sshServerIdentity, sshAuthorizedKeys, sshContainerCAKey, sshHostCertificate []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700691 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700692
693 initMsg, err := json.Marshal(
694 server.InitRequest{
Sean McCullough7013e9e2025-05-14 02:03:58 +0000695 HostAddr: localAddr,
696 SSHAuthorizedKeys: sshAuthorizedKeys,
697 SSHServerIdentity: sshServerIdentity,
698 SSHContainerCAKey: sshContainerCAKey,
699 SSHHostCertificate: sshHostCertificate,
700 SSHAvailable: sshAvailable,
701 SSHError: sshError,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700702 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700703 if err != nil {
704 return fmt.Errorf("init msg: %w", err)
705 }
706
Earl Lee2e463fb2025-04-17 11:22:22 -0700707 // Note: this /init POST is handled in loop/server/loophttp.go:
708 initMsgByteReader := bytes.NewReader(initMsg)
709 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
710 if err != nil {
711 return err
712 }
713
714 var res *http.Response
715 for i := 0; ; i++ {
716 time.Sleep(100 * time.Millisecond)
717 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
718 initMsgByteReader.Reset(initMsg)
719 res, err = http.DefaultClient.Do(req)
720 if err != nil {
David Crawshaw99231ba2025-05-03 10:48:26 -0700721 if i < 100 {
722 if i%10 == 0 {
723 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
724 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700725 continue
726 }
727 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
728 }
729 break
730 }
731 resBytes, _ := io.ReadAll(res.Body)
732 if res.StatusCode != http.StatusOK {
733 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
734 }
735 return nil
736}
737
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700738func findOrBuildDockerImage(ctx context.Context, gitRoot, baseImage string, forceRebuild, verbose bool) (imgName string, err error) {
739 // Default to the published sketch image if no base image is specified
740 if baseImage == "" {
741 imageTag := dockerfileBaseHash()
742 baseImage = fmt.Sprintf("%s:%s", dockerImgName, imageTag)
Earl Lee2e463fb2025-04-17 11:22:22 -0700743 }
744
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700745 // Ensure the base image exists locally, pull if necessary
746 if err := ensureBaseImageExists(ctx, baseImage); err != nil {
747 return "", fmt.Errorf("failed to ensure base image %s exists: %w", baseImage, err)
748 }
749
750 // Get the base image container ID for caching
751 baseImageID, err := getDockerImageID(ctx, baseImage)
Earl Lee2e463fb2025-04-17 11:22:22 -0700752 if err != nil {
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700753 return "", fmt.Errorf("failed to get base image ID for %s: %w", baseImage, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700754 }
755
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700756 // Create a cache key based on base image ID and working directory
757 // Docker naming conventions restrict you to 20 characters per path component
758 // and only allow lowercase letters, digits, underscores, and dashes, so encoding
759 // the hash and the repo directory is sadly a bit of a non-starter.
760 cacheKey := createCacheKey(baseImageID, gitRoot)
761 imgName = "sketch-" + cacheKey
Earl Lee2e463fb2025-04-17 11:22:22 -0700762
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700763 // Check if the cached image exists and is up to date
764 if !forceRebuild {
765 if exists, err := dockerImageExists(ctx, imgName); err != nil {
766 return "", fmt.Errorf("failed to check if image exists: %w", err)
767 } else if exists {
768 if verbose {
769 fmt.Printf("using cached image %s\n", imgName)
Kilian Lackhove23772f42025-06-18 20:28:58 +0200770 }
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700771 return imgName, nil
David Crawshawb5f6a002025-05-05 08:27:16 -0700772 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700773 }
774
Josh Bleecher Snyderd1171432025-07-18 15:04:05 +0000775 // Explain a bit what's happening, to help orient and de-FUD new users.
776 fmt.Println()
777 fmt.Println("┌──────────────────────────────────────────────────┐")
778 fmt.Println("│ Building Docker image (one-time) │")
779 fmt.Println("│ │")
780 fmt.Println("│ • Built and run locally │")
781 fmt.Println("│ • Packages your git repo into isolated container │")
782 fmt.Println("│ • Custom images: https://sketch.dev/docs/docker │")
783 fmt.Println("│ • Rebuild: sketch -rebuild │")
784 fmt.Println("└──────────────────────────────────────────────────┘")
785 fmt.Println()
786
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700787 if err := buildLayeredImage(ctx, imgName, baseImage, gitRoot, verbose); err != nil {
788 return "", fmt.Errorf("failed to build layered image: %w", err)
789 }
790
791 return imgName, nil
792}
793
794// ensureBaseImageExists checks if the base image exists locally and pulls it if not
795func ensureBaseImageExists(ctx context.Context, imageName string) error {
796 exists, err := dockerImageExists(ctx, imageName)
797 if err != nil {
798 return fmt.Errorf("failed to check if image exists: %w", err)
799 }
800
801 if !exists {
802 fmt.Printf("🐋 pulling base image %s...\n", imageName)
803 if out, err := combinedOutput(ctx, "docker", "pull", imageName); err != nil {
804 return fmt.Errorf("docker pull %s failed: %s: %w", imageName, out, err)
805 }
806 fmt.Printf("✅ successfully pulled %s\n", imageName)
807 }
808
809 return nil
810}
811
812// getDockerImageID gets the container ID for a Docker image
813func getDockerImageID(ctx context.Context, imageName string) (string, error) {
814 out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{.Id}}", imageName)
815 if err != nil {
816 return "", err
817 }
818 return strings.TrimSpace(string(out)), nil
819}
820
821// createCacheKey creates a cache key from base image ID and working directory
822func createCacheKey(baseImageID, gitRoot string) string {
823 h := sha256.New()
824 h.Write([]byte(baseImageID))
825 h.Write([]byte(gitRoot))
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000826 // one-time cache-busting for the transition from copying git repos to only copying git objects
827 h.Write([]byte("git-objects"))
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700828 return hex.EncodeToString(h.Sum(nil))[:12] // Use first 12 chars for shorter name
829}
830
831// dockerImageExists checks if a Docker image exists locally
832func dockerImageExists(ctx context.Context, imageName string) (bool, error) {
833 out, err := combinedOutput(ctx, "docker", "inspect", imageName)
834 if err != nil {
835 if strings.Contains(strings.ToLower(string(out)), "no such object") ||
836 strings.Contains(strings.ToLower(string(out)), "no such image") {
837 return false, nil
838 }
839 return false, err
840 }
841 return true, nil
842}
843
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000844// buildLayeredImage builds a new Docker image by layering the repo on top of the base image.
845//
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700846// TODO: git config stuff could be environment variables at runtime for email and username.
847// The git docs seem to say that http.postBuffer is a bug in our git proxy more than a thing
848// that's needed, but we haven't found the bug yet!
Philip Zeyliger882b1d12025-07-02 20:04:08 -0700849//
850// TODO: There is a caching tension. A base image is great for tools (like, some version
851// of Go). Then you want a git repo, which is much faster to incrementally fetch rather
852// than cloning every time. Then you want some build artifacts, like perhaps the
853// "go mod download" cache, or the "go build" cache or the "npm install" cache.
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000854// The implementation here copies the git objects into the base image.
855// That enables fast clones into the container, because most of the git objects are already there.
856// It also avoids copying uncommitted changes, configs/hooks, etc.
Josh Bleecher Snyderfa424f52025-07-11 18:43:55 +0000857// We also set up fake temporary Go module(s) so we can run "go mod download".
858// TODO: maybe 'go list ./...' and then do a build as well to populate the build cache.
859// TODO: 'npm install', etc? We have the rails for it.
Josh Bleecher Snyder369f2622025-07-15 00:02:59 +0000860// If /app/.git already exists, we fetch from the existing repo instead of cloning.
861// This lets advanced users arrange their git repo exactly as they desire.
Philip Zeyliger882b1d12025-07-02 20:04:08 -0700862// Note that buildx has some support for conditional COPY, but without buildx, which
863// we can't reliably depend on, we have to run the base image to inspect its file system,
864// and then we can decide what to do.
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000865//
866// We may in the future want to enable people to bring along uncommitted changes to tracked files.
867// To do that, we would run `git stash create` in outie at launch time, treat HEAD as the base commit,
868// and add in the stash commit as a new commit atop it.
869// That would accurately model the base commit as well as the uncommitted changes.
870// (This wouldn't happen here, but at agent/container initialization time.)
871//
872// repoPath is the current working directory where sketch is being run from.
873func buildLayeredImage(ctx context.Context, imgName, baseImage, gitRoot string, verbose bool) error {
Josh Bleecher Snyderfa424f52025-07-11 18:43:55 +0000874 goModules, err := collectGoModules(ctx, gitRoot)
875 if err != nil {
876 return fmt.Errorf("failed to collect go modules: %w", err)
877 }
878
879 buf := new(strings.Builder)
880 line := func(msg string, args ...any) {
881 fmt.Fprintf(buf, msg+"\n", args...)
882 }
883
884 line("FROM %s", baseImage)
885 line("COPY . /git-ref")
886
887 for _, module := range goModules {
888 line("RUN mkdir -p /go-module")
889 line("RUN git --git-dir=/git-ref --work-tree=/go-module cat-file blob %s > /go-module/go.mod", module.modSHA)
890 if module.sumSHA != "" {
891 line("RUN git --git-dir=/git-ref --work-tree=/go-module cat-file blob %s > /go-module/go.sum", module.sumSHA)
892 }
893 // drop any replaced modules
894 line("RUN cd /go-module && go mod edit -json | jq -r '.Replace? // [] | .[] | .Old.Path' | xargs -r -I{} go mod edit -dropreplace={} -droprequire={}")
895 // grab what’s left, best effort only to avoid breaking on (say) private modules
896 line("RUN cd /go-module && go mod download || true")
897 line("RUN rm -rf /go-module")
898 }
899
900 line("WORKDIR /app")
901 line(`CMD ["/bin/sketch"]`)
902 dockerfileContent := buf.String()
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700903
904 // Create a temporary directory for the Dockerfile
905 tmpDir, err := os.MkdirTemp("", "sketch-docker-*")
906 if err != nil {
907 return fmt.Errorf("failed to create temporary directory: %w", err)
908 }
909 defer os.RemoveAll(tmpDir)
910
911 dockerfilePath := filepath.Join(tmpDir, "Dockerfile")
912 if err := os.WriteFile(dockerfilePath, []byte(dockerfileContent), 0o666); err != nil {
913 return fmt.Errorf("failed to write Dockerfile: %w", err)
914 }
915
916 // Get git user info
Earl Lee2e463fb2025-04-17 11:22:22 -0700917 var gitUserEmail, gitUserName string
918 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700919 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 -0700920 } else {
921 gitUserEmail = strings.TrimSpace(string(out))
922 }
923 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700924 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 -0700925 } else {
926 gitUserName = strings.TrimSpace(string(out))
927 }
928
929 start := time.Now()
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700930 cmdArgs := []string{
931 "build",
Earl Lee2e463fb2025-04-17 11:22:22 -0700932 "-t", imgName,
933 "-f", dockerfilePath,
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700934 "--build-arg", "GIT_USER_EMAIL=" + gitUserEmail,
935 "--build-arg", "GIT_USER_NAME=" + gitUserName,
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700936 ".",
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700937 }
938
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000939 commonDir, err := gitCommonDir(ctx, gitRoot)
940 if err != nil {
941 return fmt.Errorf("failed to get git common dir: %w", err)
942 }
943
Philip Zeyliger2343f8a2025-06-17 06:16:19 -0700944 cmd := exec.CommandContext(ctx, "docker", cmdArgs...)
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000945 cmd.Dir = commonDir
David Crawshaw31f15242025-05-06 16:03:49 -0700946 // We print the docker build output whether or not the user
947 // has selected --verbose. Building an image takes a while
948 // and this gives good context.
David Crawshawb5f6a002025-05-05 08:27:16 -0700949 cmd.Stdout = os.Stdout
950 cmd.Stderr = os.Stderr
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700951 fmt.Printf("🏗️ building docker image %s from base %s...\n", imgName, baseImage)
Earl Lee2e463fb2025-04-17 11:22:22 -0700952
953 err = run(ctx, "docker build", cmd)
954 if err != nil {
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700955 return fmt.Errorf("docker build failed: %v", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700956 }
957 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
Philip Zeyliger983b58a2025-07-02 19:42:08 -0700958 return nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700959}
960
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000961// requireGitRepo confirms that path is within a git repository.
962func requireGitRepo(ctx context.Context, path string) error {
963 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-dir")
Earl Lee2e463fb2025-04-17 11:22:22 -0700964 cmd.Dir = path
965 out, err := cmd.CombinedOutput()
966 if err != nil {
967 if strings.Contains(string(out), "not a git repository") {
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000968 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 -0700969Consider one of the following options:
970 - cd to a different dir that is already part of a git repo first, or
971 - to create a new git repo from this directory (%s), run this command:
972
973 git init . && git commit --allow-empty -m "initial commit"
974
975and try running sketch again.
976`, path, path)
977 }
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000978 return fmt.Errorf("git rev-parse --git-dir: %s: %w", out, err)
979 }
980 return nil
981}
982
983// gitRepoRoot attempts to find the git repository root directory.
984// Returns an error if not in a git repository or if it's a bare repository.
985// This is used to calculate relative paths for preserving user's working directory context.
986func gitRepoRoot(ctx context.Context, path string) (string, error) {
987 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--show-toplevel")
988 cmd.Dir = path
989 out, err := cmd.CombinedOutput()
990 if err != nil {
Marc-Antoine Ruel467c3962025-06-29 13:32:59 -0400991 return "", fmt.Errorf("git rev-parse --show-toplevel: %s: %w", out, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700992 }
Marc-Antoine Ruel467c3962025-06-29 13:32:59 -0400993 // The returned path is absolute.
994 return strings.TrimSpace(string(out)), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700995}
996
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +0000997// gitCommonDir finds the git common directory for path.
998func gitCommonDir(ctx context.Context, path string) (string, error) {
999 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
1000 cmd.Dir = path
1001 out, err := cmd.CombinedOutput()
1002 if err != nil {
1003 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
1004 }
1005 gitCommonDir := strings.TrimSpace(string(out))
1006 if !filepath.IsAbs(gitCommonDir) {
1007 gitCommonDir = filepath.Join(path, gitCommonDir)
1008 }
1009 return gitCommonDir, nil
1010}
1011
Josh Bleecher Snyderfa424f52025-07-11 18:43:55 +00001012// goModuleInfo represents a Go module with its file paths and blob SHAs
1013type goModuleInfo struct {
1014 // modPath is the path to the go.mod file, for debugging
1015 modPath string
1016 // modSHA is the git blob SHA of the go.mod file
1017 modSHA string
1018 // sumSHA is the git blob SHA of the go.sum file, empty if no go.sum exists
1019 sumSHA string
1020}
1021
1022// collectGoModules returns all go.mod files in the git repository with their blob SHAs.
1023func collectGoModules(ctx context.Context, gitRoot string) ([]goModuleInfo, error) {
1024 cmd := exec.CommandContext(ctx, "git", "ls-files", "-z", "*.mod")
1025 cmd.Dir = gitRoot
1026 out, err := cmd.CombinedOutput()
1027 if err != nil {
1028 return nil, fmt.Errorf("git ls-files -z *.mod: %s: %w", out, err)
1029 }
1030
1031 modFiles := strings.Split(string(out), "\x00")
1032 var modules []goModuleInfo
1033 for _, file := range modFiles {
1034 if filepath.Base(file) != "go.mod" {
1035 continue
1036 }
1037
1038 modSHA, err := getGitBlobSHA(ctx, gitRoot, file)
1039 if err != nil {
1040 return nil, fmt.Errorf("failed to get blob SHA for %s: %w", file, err)
1041 }
1042
1043 // If corresponding go.sum exists, get its SHA
1044 sumFile := filepath.Join(filepath.Dir(file), "go.sum")
1045 sumSHA, _ := getGitBlobSHA(ctx, gitRoot, sumFile) // best effort
1046
1047 modules = append(modules, goModuleInfo{
1048 modPath: file,
1049 modSHA: modSHA,
1050 sumSHA: sumSHA,
1051 })
1052 }
1053
1054 return modules, nil
1055}
1056
1057// getGitBlobSHA returns the git blob SHA for a file at HEAD
1058func getGitBlobSHA(ctx context.Context, gitRoot, filePath string) (string, error) {
1059 cmd := exec.CommandContext(ctx, "git", "rev-parse", "HEAD:"+filePath)
1060 cmd.Dir = gitRoot
1061 out, err := cmd.CombinedOutput()
1062 if err != nil {
1063 return "", fmt.Errorf("git rev-parse HEAD:%s: %s: %w", filePath, out, err)
1064 }
1065 return strings.TrimSpace(string(out)), nil
1066}
1067
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +00001068// getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker
1069// from git config using the sketch.envfwd multi-valued key.
1070func getEnvForwardingFromGitConfig(ctx context.Context) []string {
1071 outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput()
1072 out := string(outb)
1073 if err != nil {
1074 if strings.Contains(out, "key does not exist") {
1075 return nil
1076 }
1077 slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out)
1078 return nil
1079 }
1080
1081 var envVars []string
1082 for envVar := range strings.Lines(out) {
1083 envVar = strings.TrimSpace(envVar)
1084 if envVar == "" {
1085 continue
1086 }
1087 envVars = append(envVars, envVar+"="+os.Getenv(envVar))
1088 }
1089 return envVars
1090}
Philip Zeyliger1dc21372025-05-05 19:54:44 +00001091
Josh Bleecher Snyder784d5bd2025-07-11 00:09:30 +00001092// getOriginalGitOrigin returns the URL of the git remote 'origin' if it exists in the given directory
1093func getOriginalGitOrigin(ctx context.Context, dir string) string {
1094 cmd := exec.CommandContext(ctx, "git", "config", "--get", "remote.origin.url")
1095 cmd.Dir = dir
1096 out, err := cmd.Output()
1097 if err != nil {
1098 return ""
1099 }
1100 return strings.TrimSpace(string(out))
1101}
1102
Philip Zeyliger1dc21372025-05-05 19:54:44 +00001103// parseDockerArgs parses a string containing space-separated Docker arguments into an array of strings.
1104// It handles quoted arguments and escaped characters.
1105//
1106// Examples:
1107//
1108// --memory=2g --cpus=2 -> ["--memory=2g", "--cpus=2"]
1109// --label="my label" --env=FOO=bar -> ["--label=my label", "--env=FOO=bar"]
1110// --env="KEY=\"quoted value\"" -> ["--env=KEY=\"quoted value\""]
1111func parseDockerArgs(args string) []string {
1112 if args = strings.TrimSpace(args); args == "" {
1113 return []string{}
1114 }
1115
1116 var result []string
1117 var current strings.Builder
1118 inQuotes := false
1119 escapeNext := false
1120 quoteChar := rune(0)
1121
1122 for _, char := range args {
1123 if escapeNext {
1124 current.WriteRune(char)
1125 escapeNext = false
1126 continue
1127 }
1128
1129 if char == '\\' {
1130 escapeNext = true
1131 continue
1132 }
1133
1134 if char == '"' || char == '\'' {
1135 if !inQuotes {
1136 inQuotes = true
1137 quoteChar = char
1138 continue
1139 } else if char == quoteChar {
1140 inQuotes = false
1141 quoteChar = rune(0)
1142 continue
1143 }
1144 // Non-matching quote character inside quotes
1145 current.WriteRune(char)
1146 continue
1147 }
1148
1149 // Space outside of quotes is an argument separator
1150 if char == ' ' && !inQuotes {
1151 if current.Len() > 0 {
1152 result = append(result, current.String())
1153 current.Reset()
1154 }
1155 continue
1156 }
1157
1158 current.WriteRune(char)
1159 }
1160
1161 // Add the last argument if there is one
1162 if current.Len() > 0 {
1163 result = append(result, current.String())
1164 }
1165
1166 return result
1167}
Philip Zeyliger4acf0062025-05-22 13:53:46 -07001168
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001169// copyEmbeddedLinuxBinaryToContainer copies the embedded linux binary to the container
1170func copyEmbeddedLinuxBinaryToContainer(ctx context.Context, containerName string) error {
Josh Bleecher Snyder5ae245b2025-07-08 22:00:24 +00001171 out, err := combinedOutput(ctx, "docker", "version", "--format", "{{.Server.Arch}}")
1172 if err != nil {
1173 return fmt.Errorf("failed to detect Docker server architecture: %s: %w", out, err)
1174 }
1175 arch := strings.TrimSpace(string(out))
1176
1177 bin := embedded.LinuxBinary(arch)
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001178 if bin == nil {
Josh Bleecher Snyder5ae245b2025-07-08 22:00:24 +00001179 return fmt.Errorf("no embedded linux binary for architecture %q", arch)
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001180 }
1181
Josh Bleecher Snyderc9898fd2025-07-08 21:09:18 +00001182 // Stream a tarball to docker cp.
1183 pr, pw := io.Pipe()
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001184
Josh Bleecher Snyderc9898fd2025-07-08 21:09:18 +00001185 errCh := make(chan error, 1)
1186 go func() {
1187 defer pw.Close()
1188 tw := tar.NewWriter(pw)
1189
1190 hdr := &tar.Header{
1191 Name: "bin/sketch", // final path inside the container
1192 Mode: 0o700,
1193 Size: int64(len(bin)),
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001194 }
Josh Bleecher Snyderc9898fd2025-07-08 21:09:18 +00001195 if err := tw.WriteHeader(hdr); err != nil {
1196 errCh <- fmt.Errorf("failed to write tar header: %w", err)
1197 return
1198 }
1199 if _, err := tw.Write(bin); err != nil {
1200 errCh <- fmt.Errorf("failed to write binary to tar: %w", err)
1201 return
1202 }
1203 if err := tw.Close(); err != nil {
1204 errCh <- fmt.Errorf("failed to close tar writer: %w", err)
1205 return
1206 }
1207 errCh <- nil
1208 }()
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001209
Josh Bleecher Snyderc9898fd2025-07-08 21:09:18 +00001210 cmd := exec.CommandContext(ctx, "docker", "cp", "-", containerName+":/")
1211 cmd.Stdin = pr
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001212
Josh Bleecher Snyderc9898fd2025-07-08 21:09:18 +00001213 out, cmdErr := cmd.CombinedOutput()
1214
1215 if tarErr := <-errCh; tarErr != nil {
1216 return tarErr
1217 }
1218 if cmdErr != nil {
1219 return fmt.Errorf("docker cp failed: %s: %w", out, cmdErr)
1220 }
Josh Bleecher Snyder1c18ec92025-07-08 10:55:54 -07001221 return nil
1222}
1223
David Crawshaw1bd636c2025-06-13 19:56:27 +00001224const seccompProfile = `{
1225 "defaultAction": "SCMP_ACT_ALLOW",
1226 "syscalls": [
1227 {
1228 "names": ["kill", "tkill", "tgkill", "pidfd_send_signal"],
1229 "action": "SCMP_ACT_ERRNO",
1230 "args": [
1231 {
1232 "index": 0,
1233 "value": 1,
1234 "op": "SCMP_CMP_EQ"
1235 }
1236 ]
1237 }
1238 ]
1239}`
1240
1241// ensureSeccompProfile creates the seccomp profile file in the sketch cache directory if it doesn't exist.
1242func ensureSeccompProfile(ctx context.Context) (seccompPath string, err error) {
1243 homeDir, err := os.UserHomeDir()
1244 if err != nil {
1245 return "", fmt.Errorf("failed to get home directory: %w", err)
1246 }
1247 cacheDir := filepath.Join(homeDir, ".cache", "sketch")
1248 if err := os.MkdirAll(cacheDir, 0o755); err != nil {
1249 return "", fmt.Errorf("failed to create cache directory: %w", err)
1250 }
1251 seccompPath = filepath.Join(cacheDir, "seccomp-no-kill-1.json")
1252
1253 curBytes, err := os.ReadFile(seccompPath)
1254 if err != nil && !os.IsNotExist(err) {
1255 return "", fmt.Errorf("failed to read seccomp profile file %s: %w", seccompPath, err)
1256 }
1257 if string(curBytes) == seccompProfile {
1258 return seccompPath, nil // File already exists and matches the expected profile
1259 }
1260
1261 if err := os.WriteFile(seccompPath, []byte(seccompProfile), 0o644); err != nil {
1262 return "", fmt.Errorf("failed to write seccomp profile to %s: %w", seccompPath, err)
1263 }
1264 slog.DebugContext(ctx, "created seccomp profile", "path", seccompPath)
1265 return seccompPath, nil
1266}