blob: 02567980e027fecdb1807d36e22b39ce2e87045d [file] [log] [blame]
Earl Lee2e463fb2025-04-17 11:22:22 -07001// Package dockerimg
2package dockerimg
3
4import (
5 "bytes"
6 "context"
Philip Zeyliger5e227dd2025-04-21 15:55:29 -07007 "crypto/rand"
Earl Lee2e463fb2025-04-17 11:22:22 -07008 "crypto/sha256"
9 "encoding/hex"
10 "encoding/json"
11 "fmt"
12 "io"
13 "log/slog"
14 "net"
15 "net/http"
16 "os"
17 "os/exec"
18 "path/filepath"
19 "runtime"
20 "strings"
Josh Bleecher Snyder99570462025-05-05 10:26:14 -070021 "sync/atomic"
Earl Lee2e463fb2025-04-17 11:22:22 -070022 "time"
23
Josh Bleecher Snyder78707d62025-04-30 21:06:49 +000024 "sketch.dev/browser"
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070025 "sketch.dev/llm/ant"
Sean McCulloughbaa2b592025-04-23 10:40:08 -070026 "sketch.dev/loop/server"
Earl Lee2e463fb2025-04-17 11:22:22 -070027 "sketch.dev/skribe"
Philip Zeyliger5d6af872025-04-23 19:48:34 -070028 "sketch.dev/webui"
Earl Lee2e463fb2025-04-17 11:22:22 -070029)
30
31// ContainerConfig holds all configuration for launching a container
32type ContainerConfig struct {
33 // SessionID is the unique identifier for this session
34 SessionID string
35
36 // LocalAddr is the initial address to use (though it may be overwritten later)
37 LocalAddr string
38
39 // SkabandAddr is the address of the skaband service if available
40 SkabandAddr string
41
David Crawshaw5a7b3692025-05-05 16:49:15 -070042 // Model is the name of the LLM model to use.
43 Model string
Earl Lee2e463fb2025-04-17 11:22:22 -070044
David Crawshaw5a7b3692025-05-05 16:49:15 -070045 // ModelURL is the URL of the LLM service.
46 ModelURL string
47
48 // ModelAPIKey is the API key for LLM service.
49 ModelAPIKey string
Earl Lee2e463fb2025-04-17 11:22:22 -070050
51 // Path is the local filesystem path to use
52 Path string
53
54 // GitUsername is the username to use for git operations
55 GitUsername string
56
57 // GitEmail is the email to use for git operations
58 GitEmail string
59
60 // OpenBrowser determines whether to open a browser automatically
61 OpenBrowser bool
62
63 // NoCleanup prevents container cleanup when set to true
64 NoCleanup bool
65
66 // ForceRebuild forces rebuilding of the Docker image even if it exists
67 ForceRebuild bool
68
69 // Host directory to copy container logs into, if not set to ""
70 ContainerLogDest string
71
72 // Path to pre-built linux sketch binary, or build a new one if set to ""
73 SketchBinaryLinux string
74
75 // Sketch client public key.
76 SketchPubKey string
Philip Zeyligerd1402952025-04-23 03:54:37 +000077
Sean McCulloughbaa2b592025-04-23 10:40:08 -070078 // Host port for the container's ssh server
79 SSHPort int
80
Philip Zeyliger18532b22025-04-23 21:11:46 +000081 // Outside information to pass to the container
82 OutsideHostname string
83 OutsideOS string
84 OutsideWorkingDir string
Philip Zeyligerb74c4f62025-04-25 19:18:49 -070085
Pokey Rule0dcebe12025-04-28 14:51:04 +010086 // If true, exit after the first turn
87 OneShot bool
88
89 // Initial prompt
90 Prompt string
Philip Zeyliger1b47aa22025-04-28 19:25:38 +000091
92 // Initial commit to use as starting point
93 InitialCommit string
David Crawshawb5f6a002025-05-05 08:27:16 -070094
95 // Verbose enables verbose output
96 Verbose bool
Philip Zeyliger1dc21372025-05-05 19:54:44 +000097
98 // DockerArgs are additional arguments to pass to the docker create command
99 DockerArgs string
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000100
101 // ExperimentFlag contains the experimental features to enable
102 ExperimentFlag string
Earl Lee2e463fb2025-04-17 11:22:22 -0700103}
104
105// LaunchContainer creates a docker container for a project, installs sketch and opens a connection to it.
106// It writes status to stdout.
David Crawshawb5f6a002025-05-05 08:27:16 -0700107func LaunchContainer(ctx context.Context, config ContainerConfig) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700108 if _, err := exec.LookPath("docker"); err != nil {
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700109 if runtime.GOOS == "darwin" {
110 return fmt.Errorf("cannot find `docker` binary; run: brew install docker colima && colima start")
111 } else {
112 return fmt.Errorf("cannot find `docker` binary; install docker (e.g., apt-get install docker.io)")
113 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700114 }
115
116 if out, err := combinedOutput(ctx, "docker", "ps"); err != nil {
117 // `docker ps` provides a good error message here that can be
118 // easily chatgpt'ed by users, so send it to the user as-is:
119 // Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
120 return fmt.Errorf("docker ps: %s (%w)", out, err)
121 }
122
123 _, hostPort, err := net.SplitHostPort(config.LocalAddr)
124 if err != nil {
125 return err
126 }
127
128 gitRoot, err := findGitRoot(ctx, config.Path)
129 if err != nil {
130 return err
131 }
132
David Crawshaw5a7b3692025-05-05 16:49:15 -0700133 imgName, err := findOrBuildDockerImage(ctx, config.Path, gitRoot, config.Model, config.ModelURL, config.ModelAPIKey, config.ForceRebuild, config.Verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700134 if err != nil {
135 return err
136 }
137
138 linuxSketchBin := config.SketchBinaryLinux
139 if linuxSketchBin == "" {
David Crawshawb5f6a002025-05-05 08:27:16 -0700140 linuxSketchBin, err = buildLinuxSketchBin(ctx)
Earl Lee2e463fb2025-04-17 11:22:22 -0700141 if err != nil {
142 return err
143 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700144 }
145
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000146 cntrName := "sketch-" + config.SessionID
Earl Lee2e463fb2025-04-17 11:22:22 -0700147 defer func() {
148 if config.NoCleanup {
149 return
150 }
151 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
152 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
153 _ = out
154 }
155 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
156 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
157 _ = out
158 }
159 }()
160
161 // errCh receives errors from operations that this function calls in separate goroutines.
162 errCh := make(chan error)
163
164 // Start the git server
165 gitSrv, err := newGitServer(gitRoot)
166 if err != nil {
167 return fmt.Errorf("failed to start git server: %w", err)
168 }
169 defer gitSrv.shutdown(ctx)
170
171 go func() {
172 errCh <- gitSrv.serve(ctx)
173 }()
174
175 // Get the current host git commit
176 var commit string
Philip Zeyliger1b47aa22025-04-28 19:25:38 +0000177 if out, err := combinedOutput(ctx, "git", "rev-parse", config.InitialCommit); err != nil {
178 return fmt.Errorf("git rev-parse %s: %w", config.InitialCommit, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700179 } else {
180 commit = strings.TrimSpace(string(out))
181 }
182 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
183 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
184 }
185
186 relPath, err := filepath.Rel(gitRoot, config.Path)
187 if err != nil {
188 return err
189 }
190
191 // Create the sketch container
192 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000193 return fmt.Errorf("failed to create docker container: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700194 }
195
196 // Copy the sketch linux binary into the container
197 if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil {
198 return fmt.Errorf("docker cp: %s, %w", out, err)
199 }
Sean McCulloughf5bb3d32025-04-18 10:47:59 -0700200
201 // Make sure that the webui is built so we can copy the results to the container.
202 _, err = webui.Build()
203 if err != nil {
204 return fmt.Errorf("failed to build webui: %w", err)
205 }
206
David Crawshaw8bff16a2025-04-18 01:16:49 -0700207 webuiZipPath, err := webui.ZipPath()
208 if err != nil {
209 return err
210 }
211 if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil {
212 return fmt.Errorf("docker cp: %s, %w", out, err)
213 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700214
David Crawshaw53786ef2025-04-24 12:52:51 -0700215 fmt.Printf("📦 running in container %s\n", cntrName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700216
217 // Start the sketch container
218 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
219 return fmt.Errorf("docker start: %s, %w", out, err)
220 }
221
222 // Copies structured logs from the container to the host.
223 copyLogs := func() {
224 if config.ContainerLogDest == "" {
225 return
226 }
227 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
228 if err != nil {
229 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
230 return
231 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700232 prefix := []byte("structured logs:")
233 for line := range bytes.Lines(out) {
234 rest, ok := bytes.CutPrefix(line, prefix)
235 if !ok {
Earl Lee2e463fb2025-04-17 11:22:22 -0700236 continue
237 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700238 logFile := string(bytes.TrimSpace(rest))
Earl Lee2e463fb2025-04-17 11:22:22 -0700239 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
240 logFileName := filepath.Base(logFile)
241 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
242 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
243 if err != nil {
244 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
245 }
246 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
247 }
248 }
249
250 // NOTE: we want to see what the internal sketch binary prints
251 // regardless of the setting of the verbosity flag on the external
252 // binary, so reading "docker logs", which is the stdout/stderr of
253 // the internal binary is not conditional on the verbose flag.
254 appendInternalErr := func(err error) error {
255 if err == nil {
256 return nil
257 }
258 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000259 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700260 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
261 }
262 out = bytes.TrimSpace(out)
263 if len(out) > 0 {
264 return fmt.Errorf("docker logs: %s;\n%w", out, err)
265 }
266 return err
267 }
268
269 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700270 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700271 if err != nil {
272 return appendInternalErr(err)
273 }
274
Sean McCulloughae3480f2025-04-23 15:28:20 -0700275 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
276 if err != nil {
277 return appendInternalErr(err)
278 }
279 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
280 if err != nil {
David Crawshawb5f6a002025-05-05 08:27:16 -0700281 return appendInternalErr(fmt.Errorf("failed to split ssh host and port: %w", err))
Sean McCulloughae3480f2025-04-23 15:28:20 -0700282 }
Sean McCullough4854c652025-04-24 18:37:02 -0700283
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700284 var sshServerIdentity, sshUserIdentity []byte
Sean McCullough4854c652025-04-24 18:37:02 -0700285
Sean McCullough078e85a2025-05-08 17:28:34 -0700286 cst, err := NewSSHTheater(cntrName, sshHost, sshPort)
287 if err != nil {
288 return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err))
289 }
290
291 sshErr := CheckSSHReachability(cntrName)
Sean McCullough15c95282025-05-08 16:48:38 -0700292 sshAvailable := false
293 sshErrMsg := ""
294 if sshErr != nil {
295 fmt.Println(sshErr.Error())
296 sshErrMsg = sshErr.Error()
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700297 // continue - ssh config is not required for the rest of sketch to function locally.
298 } else {
Sean McCullough15c95282025-05-08 16:48:38 -0700299 sshAvailable = true
Sean McCulloughea3fc202025-04-28 12:53:37 -0700300 // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find:
301 // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700302 fmt.Printf(`Connect to this container via any of these methods:
Sean McCullough4854c652025-04-24 18:37:02 -0700303🖥️ ssh %s
304🖥️ code --remote ssh-remote+root@%s /app -n
Sean McCulloughea3fc202025-04-28 12:53:37 -0700305🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank
Sean McCullough4854c652025-04-24 18:37:02 -0700306`, cntrName, cntrName, cntrName)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700307 sshUserIdentity = cst.userIdentity
308 sshServerIdentity = cst.serverIdentity
309 defer func() {
310 if err := cst.Cleanup(); err != nil {
311 appendInternalErr(err)
312 }
313 }()
314 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700315
Earl Lee2e463fb2025-04-17 11:22:22 -0700316 // Tell the sketch container which git server port and commit to initialize with.
317 go func() {
318 // TODO: Why is this called in a goroutine? I have found that when I pull this out
319 // of the goroutine and call it inline, then the terminal UI clears itself and all
320 // the scrollback (which is not good, but also not fatal). I can't see why it does this
321 // though, since none of the calls in postContainerInitConfig obviously write to stdout
322 // or stderr.
Sean McCullough15c95282025-05-08 16:48:38 -0700323 if err := postContainerInitConfig(ctx, localAddr, commit, gitSrv.gitPort, gitSrv.pass, sshAvailable, sshErrMsg, sshServerIdentity, sshUserIdentity); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700324 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
325 errCh <- appendInternalErr(err)
326 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700327
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700328 // 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 -0700329 ps1URL := "http://" + localAddr
330 if config.SkabandAddr != "" {
331 ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700332 }
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700333 if config.OpenBrowser {
334 browser.Open(ps1URL)
335 }
336 gitSrv.ps1URL.Store(&ps1URL)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700337 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700338
339 go func() {
340 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
341 cmd.Stdin = os.Stdin
342 cmd.Stdout = os.Stdout
343 cmd.Stderr = os.Stderr
344 errCh <- run(ctx, "docker attach", cmd)
345 }()
346
347 defer copyLogs()
348
349 for {
350 select {
351 case <-ctx.Done():
352 return ctx.Err()
353 case err := <-errCh:
354 if err != nil {
355 return appendInternalErr(fmt.Errorf("container process: %w", err))
356 }
357 return nil
358 }
359 }
360}
361
362func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
363 cmd := exec.CommandContext(ctx, cmdName, args...)
Earl Lee2e463fb2025-04-17 11:22:22 -0700364 start := time.Now()
365
366 out, err := cmd.CombinedOutput()
367 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700368 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 -0700369 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700370 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 -0700371 }
372 return out, err
373}
374
375func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
376 start := time.Now()
377 err := cmd.Run()
378 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700379 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 -0700380 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700381 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 -0700382 }
383 return err
384}
385
386type gitServer struct {
387 gitLn net.Listener
388 gitPort string
389 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700390 pass string
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700391 ps1URL atomic.Pointer[string]
Earl Lee2e463fb2025-04-17 11:22:22 -0700392}
393
394func (gs *gitServer) shutdown(ctx context.Context) {
395 gs.srv.Shutdown(ctx)
396 gs.gitLn.Close()
397}
398
399// Serve a git remote from the host for the container to fetch from and push to.
400func (gs *gitServer) serve(ctx context.Context) error {
401 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
402 return gs.srv.Serve(gs.gitLn)
403}
404
405func newGitServer(gitRoot string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700406 ret := &gitServer{
407 pass: rand.Text(),
408 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700409
Earl Lee2e463fb2025-04-17 11:22:22 -0700410 gitLn, err := net.Listen("tcp4", ":0")
411 if err != nil {
412 return nil, fmt.Errorf("git listen: %w", err)
413 }
414 ret.gitLn = gitLn
415
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700416 browserC := make(chan bool, 1) // channel of browser open requests
417
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000418 go func() {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700419 for range browserC {
420 browser.Open(*ret.ps1URL.Load())
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000421 }
422 }()
423
424 srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass), browserC: browserC}}
Earl Lee2e463fb2025-04-17 11:22:22 -0700425 ret.srv = &srv
426
427 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
428 if err != nil {
429 return nil, fmt.Errorf("git port: %w", err)
430 }
431 ret.gitPort = gitPort
432 return ret, nil
433}
434
435func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
David Crawshaw69c67312025-04-17 13:42:00 -0700436 cmdArgs := []string{
437 "create",
David Crawshaw66cf74e2025-05-05 08:48:39 -0700438 "-i",
Earl Lee2e463fb2025-04-17 11:22:22 -0700439 "--name", cntrName,
440 "-p", hostPort + ":80", // forward container port 80 to a host port
David Crawshaw3659d872025-05-05 17:52:23 -0700441 "-e", "SKETCH_MODEL_API_KEY=" + config.ModelAPIKey,
Earl Lee2e463fb2025-04-17 11:22:22 -0700442 }
David Crawshaw66cf74e2025-05-05 08:48:39 -0700443 if !config.OneShot {
444 cmdArgs = append(cmdArgs, "-t")
445 }
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000446
447 for _, envVar := range getEnvForwardingFromGitConfig(ctx) {
448 cmdArgs = append(cmdArgs, "-e", envVar)
449 }
David Crawshaw5a7b3692025-05-05 16:49:15 -0700450 if config.ModelURL != "" {
David Crawshaw3659d872025-05-05 17:52:23 -0700451 cmdArgs = append(cmdArgs, "-e", "SKETCH_MODEL_URL="+config.ModelURL)
Earl Lee2e463fb2025-04-17 11:22:22 -0700452 }
453 if config.SketchPubKey != "" {
454 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
455 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700456 if config.SSHPort > 0 {
457 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
458 } else {
459 cmdArgs = append(cmdArgs, "-p", "22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700460 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700461 if relPath != "." {
462 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
463 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700464 // colima does this by default, but Linux docker seems to need this set explicitly
465 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Earl Lee2e463fb2025-04-17 11:22:22 -0700466 cmdArgs = append(
467 cmdArgs,
468 imgName,
469 "/bin/sketch",
470 "-unsafe",
471 "-addr=:80",
472 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000473 "-git-username="+config.GitUsername,
474 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000475 "-outside-hostname="+config.OutsideHostname,
476 "-outside-os="+config.OutsideOS,
477 "-outside-working-dir="+config.OutsideWorkingDir,
Josh Bleecher Snyder3cae7d92025-04-30 09:54:29 -0700478 "-open=false",
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000479 "-x="+config.ExperimentFlag,
Earl Lee2e463fb2025-04-17 11:22:22 -0700480 )
David Crawshaw5a7b3692025-05-05 16:49:15 -0700481 if config.Model != "" {
482 cmdArgs = append(cmdArgs, "-model="+config.Model)
483 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700484 if config.SkabandAddr != "" {
485 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
486 }
Pokey Rule0dcebe12025-04-28 14:51:04 +0100487 if config.Prompt != "" {
488 cmdArgs = append(cmdArgs, "-prompt", config.Prompt)
489 }
490 if config.OneShot {
491 cmdArgs = append(cmdArgs, "-one-shot")
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700492 }
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000493
494 // Add additional docker arguments if provided
495 if config.DockerArgs != "" {
496 // Parse space-separated docker arguments with support for quotes and escaping
497 args := parseDockerArgs(config.DockerArgs)
498 // Insert arguments after "create" but before other arguments
499 for i := len(args) - 1; i >= 0; i-- {
500 cmdArgs = append(cmdArgs[:1], append([]string{args[i]}, cmdArgs[1:]...)...)
501 }
502 }
503
Earl Lee2e463fb2025-04-17 11:22:22 -0700504 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
505 return fmt.Errorf("docker create: %s, %w", out, err)
506 }
507 return nil
508}
509
David Crawshawb5f6a002025-05-05 08:27:16 -0700510func buildLinuxSketchBin(ctx context.Context) (string, error) {
David Crawshaw8a617cb2025-04-18 01:28:43 -0700511 homeDir, err := os.UserHomeDir()
David Crawshaw69c67312025-04-17 13:42:00 -0700512 if err != nil {
513 return "", err
514 }
David Crawshaw8a617cb2025-04-18 01:28:43 -0700515 linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo")
516 if err := os.MkdirAll(linuxGopath, 0o777); err != nil {
517 return "", err
518 }
519
520 verToInstall := "@latest"
521 if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil {
522 return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err)
523 } else {
524 if strings.TrimSpace(string(out)) == "sketch.dev" {
David Crawshaw094e4d22025-04-24 11:35:14 -0700525 slog.DebugContext(ctx, "built linux agent from currently checked out module")
David Crawshaw8a617cb2025-04-18 01:28:43 -0700526 verToInstall = ""
527 }
528 }
David Crawshaw69c67312025-04-17 13:42:00 -0700529
Earl Lee2e463fb2025-04-17 11:22:22 -0700530 start := time.Now()
David Crawshaw8a617cb2025-04-18 01:28:43 -0700531 cmd := exec.CommandContext(ctx, "go", "install", "sketch.dev/cmd/sketch"+verToInstall)
David Crawshawb9eaef52025-04-17 15:23:18 -0700532 cmd.Env = append(
533 os.Environ(),
534 "GOOS=linux",
535 "CGO_ENABLED=0",
536 "GOTOOLCHAIN=auto",
David Crawshaw8a617cb2025-04-18 01:28:43 -0700537 "GOPATH="+linuxGopath,
Josh Bleecher Snyderfae17572025-04-21 11:48:05 -0700538 "GOBIN=",
David Crawshawb9eaef52025-04-17 15:23:18 -0700539 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700540
Earl Lee2e463fb2025-04-17 11:22:22 -0700541 out, err := cmd.CombinedOutput()
542 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700543 slog.ErrorContext(ctx, "go", slog.Duration("elapsed", time.Since(start)), slog.String("err", err.Error()), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
Earl Lee2e463fb2025-04-17 11:22:22 -0700544 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
545 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700546 slog.DebugContext(ctx, "go", slog.Duration("elapsed", time.Since(start)), slog.String("path", cmd.Path), slog.String("args", fmt.Sprintf("%v", skribe.Redact(cmd.Args))))
Earl Lee2e463fb2025-04-17 11:22:22 -0700547 }
548
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700549 if runtime.GOOS != "linux" {
David Crawshawc7e77962025-05-03 13:20:18 -0700550 return filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch"), nil
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700551 }
David Crawshawc7e77962025-05-03 13:20:18 -0700552 // If we are already on Linux, there's no extra platform name in the path
553 return filepath.Join(linuxGopath, "bin", "sketch"), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700554}
555
Sean McCulloughae3480f2025-04-23 15:28:20 -0700556func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700557 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700558 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700559 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
560 } else {
561 v4, _, found := strings.Cut(string(out), "\n")
562 if !found {
563 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
564 }
565 localAddr = v4
566 if strings.HasPrefix(localAddr, "0.0.0.0") {
567 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
568 }
569 }
570 return localAddr, nil
571}
572
573// Contact the container and configure it.
Sean McCullough15c95282025-05-08 16:48:38 -0700574func postContainerInitConfig(ctx context.Context, localAddr, commit, gitPort, gitPass string, sshAvailable bool, sshError string, sshServerIdentity, sshAuthorizedKeys []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700575 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700576
577 initMsg, err := json.Marshal(
578 server.InitRequest{
579 Commit: commit,
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000580 OutsideHTTP: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitPass, gitPort),
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700581 GitRemoteAddr: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitPass, gitPort),
582 HostAddr: localAddr,
583 SSHAuthorizedKeys: sshAuthorizedKeys,
584 SSHServerIdentity: sshServerIdentity,
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000585 SSHAvailable: sshAvailable,
586 SSHError: sshError,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700587 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700588 if err != nil {
589 return fmt.Errorf("init msg: %w", err)
590 }
591
Earl Lee2e463fb2025-04-17 11:22:22 -0700592 // Note: this /init POST is handled in loop/server/loophttp.go:
593 initMsgByteReader := bytes.NewReader(initMsg)
594 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
595 if err != nil {
596 return err
597 }
598
599 var res *http.Response
600 for i := 0; ; i++ {
601 time.Sleep(100 * time.Millisecond)
602 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
603 initMsgByteReader.Reset(initMsg)
604 res, err = http.DefaultClient.Do(req)
605 if err != nil {
David Crawshaw99231ba2025-05-03 10:48:26 -0700606 if i < 100 {
607 if i%10 == 0 {
608 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
609 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700610 continue
611 }
612 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
613 }
614 break
615 }
616 resBytes, _ := io.ReadAll(res.Body)
617 if res.StatusCode != http.StatusOK {
618 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
619 }
620 return nil
621}
622
David Crawshaw5a7b3692025-05-05 16:49:15 -0700623func findOrBuildDockerImage(ctx context.Context, cwd, gitRoot, model, modelURL, modelAPIKey string, forceRebuild, verbose bool) (imgName string, err error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700624 h := sha256.Sum256([]byte(gitRoot))
625 imgName = "sketch-" + hex.EncodeToString(h[:6])
626
627 var curImgInitFilesHash string
628 if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil {
629 if strings.Contains(string(out), "No such object") {
630 // Image does not exist, continue and build it.
631 curImgInitFilesHash = ""
632 } else {
633 return "", fmt.Errorf("docker inspect failed: %s, %v", out, err)
634 }
635 } else {
636 m := map[string]string{}
637 if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil {
638 return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err)
639 }
640 curImgInitFilesHash = m["sketch_context"]
641 }
642
643 candidates, err := findRepoDockerfiles(cwd, gitRoot)
644 if err != nil {
645 return "", fmt.Errorf("find dockerfile: %w", err)
646 }
647
648 var initFiles map[string]string
649 var dockerfilePath string
650
651 // TODO: prefer a "Dockerfile.sketch" so users can tailor any env to this tool.
652 if len(candidates) == 1 && strings.ToLower(filepath.Base(candidates[0])) == "dockerfile" {
653 dockerfilePath = candidates[0]
654 contents, err := os.ReadFile(dockerfilePath)
655 if err != nil {
656 return "", err
657 }
658 fmt.Printf("using %s as dev env\n", candidates[0])
659 if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700660 return imgName, nil
661 }
662 } else {
663 initFiles, err = readInitFiles(os.DirFS(gitRoot))
664 if err != nil {
665 return "", err
666 }
667 subPathWorkingDir, err := filepath.Rel(gitRoot, cwd)
668 if err != nil {
669 return "", err
670 }
671 initFileHash := hashInitFiles(initFiles)
672 if curImgInitFilesHash == initFileHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700673 return imgName, nil
674 }
675
David Crawshaw5a7b3692025-05-05 16:49:15 -0700676 if model == "gemini" {
677 if strings.HasSuffix(modelURL, "/gemmsgs") {
678 // Horrible hack! Switch back to anthropic for container building.
David Crawshaw3659d872025-05-05 17:52:23 -0700679 // We can do this because we are talking to skaband and know the address.
David Crawshaw5a7b3692025-05-05 16:49:15 -0700680 modelURL = strings.Replace(modelURL, "/gemmsgs", "/antmsgs", 1)
681 } else {
682 return "", fmt.Errorf("building docker image with gemini model is not supported yet; start with -model=anthropic first then use gemini")
683 }
684 }
685
Earl Lee2e463fb2025-04-17 11:22:22 -0700686 start := time.Now()
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700687 srv := &ant.Service{
David Crawshaw5a7b3692025-05-05 16:49:15 -0700688 URL: modelURL,
689 APIKey: modelAPIKey,
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700690 HTTPC: http.DefaultClient,
691 }
692 dockerfile, err := createDockerfile(ctx, srv, initFiles, subPathWorkingDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700693 if err != nil {
694 return "", fmt.Errorf("create dockerfile: %w", err)
695 }
David Crawshaw8fd51042025-05-05 12:52:43 -0700696 dockerfilePath = filepath.Join(cwd, tmpSketchDockerfile)
Earl Lee2e463fb2025-04-17 11:22:22 -0700697 if err := os.WriteFile(dockerfilePath, []byte(dockerfile), 0o666); err != nil {
698 return "", err
699 }
700 defer os.Remove(dockerfilePath)
701
David Crawshawb5f6a002025-05-05 08:27:16 -0700702 if verbose {
703 fmt.Fprintf(os.Stderr, "generated Dockerfile in %s:\n\t%s\n\n", time.Since(start).Round(time.Millisecond), strings.Replace(dockerfile, "\n", "\n\t", -1))
704 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700705 }
706
707 var gitUserEmail, gitUserName string
708 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
709 return "", fmt.Errorf("git config: %s: %v", out, err)
710 } else {
711 gitUserEmail = strings.TrimSpace(string(out))
712 }
713 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
714 return "", fmt.Errorf("git config: %s: %v", out, err)
715 } else {
716 gitUserName = strings.TrimSpace(string(out))
717 }
718
719 start := time.Now()
720 cmd := exec.CommandContext(ctx,
721 "docker", "build",
722 "-t", imgName,
723 "-f", dockerfilePath,
724 "--build-arg", "GIT_USER_EMAIL="+gitUserEmail,
725 "--build-arg", "GIT_USER_NAME="+gitUserName,
David Crawshaw31f15242025-05-06 16:03:49 -0700726 ".",
Earl Lee2e463fb2025-04-17 11:22:22 -0700727 )
David Crawshawb5f6a002025-05-05 08:27:16 -0700728 cmd.Dir = gitRoot
David Crawshaw31f15242025-05-06 16:03:49 -0700729 // We print the docker build output whether or not the user
730 // has selected --verbose. Building an image takes a while
731 // and this gives good context.
David Crawshawb5f6a002025-05-05 08:27:16 -0700732 cmd.Stdout = os.Stdout
733 cmd.Stderr = os.Stderr
734 fmt.Printf("🏗️ building docker image %s... (use -verbose to see build output)\n", imgName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700735
736 err = run(ctx, "docker build", cmd)
737 if err != nil {
738 return "", fmt.Errorf("docker build failed: %v", err)
739 }
740 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
741 return imgName, nil
742}
743
744func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) {
745 files, err := findDirDockerfiles(cwd)
746 if err != nil {
747 return nil, err
748 }
749 if len(files) > 0 {
750 return files, nil
751 }
752
753 path := cwd
754 for path != gitRoot {
755 path = filepath.Dir(path)
756 files, err := findDirDockerfiles(path)
757 if err != nil {
758 return nil, err
759 }
760 if len(files) > 0 {
761 return files, nil
762 }
763 }
764 return files, nil
765}
766
767// findDirDockerfiles finds all "Dockerfile*" files in a directory.
768func findDirDockerfiles(root string) (res []string, err error) {
769 err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
770 if err != nil {
771 return err
772 }
773 if info.IsDir() && root != path {
774 return filepath.SkipDir
775 }
776 name := strings.ToLower(info.Name())
777 if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") {
778 res = append(res, path)
779 }
780 return nil
781 })
782 if err != nil {
783 return nil, err
784 }
785 return res, nil
786}
787
788func findGitRoot(ctx context.Context, path string) (string, error) {
789 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
790 cmd.Dir = path
791 out, err := cmd.CombinedOutput()
792 if err != nil {
793 if strings.Contains(string(out), "not a git repository") {
794 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
795Consider one of the following options:
796 - cd to a different dir that is already part of a git repo first, or
797 - to create a new git repo from this directory (%s), run this command:
798
799 git init . && git commit --allow-empty -m "initial commit"
800
801and try running sketch again.
802`, path, path)
803 }
804 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
805 }
806 gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path
807 absGitDir := filepath.Join(path, gitDir)
808 return filepath.Dir(absGitDir), err
809}
810
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000811// getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker
812// from git config using the sketch.envfwd multi-valued key.
813func getEnvForwardingFromGitConfig(ctx context.Context) []string {
814 outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput()
815 out := string(outb)
816 if err != nil {
817 if strings.Contains(out, "key does not exist") {
818 return nil
819 }
820 slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out)
821 return nil
822 }
823
824 var envVars []string
825 for envVar := range strings.Lines(out) {
826 envVar = strings.TrimSpace(envVar)
827 if envVar == "" {
828 continue
829 }
830 envVars = append(envVars, envVar+"="+os.Getenv(envVar))
831 }
832 return envVars
833}
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000834
835// parseDockerArgs parses a string containing space-separated Docker arguments into an array of strings.
836// It handles quoted arguments and escaped characters.
837//
838// Examples:
839//
840// --memory=2g --cpus=2 -> ["--memory=2g", "--cpus=2"]
841// --label="my label" --env=FOO=bar -> ["--label=my label", "--env=FOO=bar"]
842// --env="KEY=\"quoted value\"" -> ["--env=KEY=\"quoted value\""]
843func parseDockerArgs(args string) []string {
844 if args = strings.TrimSpace(args); args == "" {
845 return []string{}
846 }
847
848 var result []string
849 var current strings.Builder
850 inQuotes := false
851 escapeNext := false
852 quoteChar := rune(0)
853
854 for _, char := range args {
855 if escapeNext {
856 current.WriteRune(char)
857 escapeNext = false
858 continue
859 }
860
861 if char == '\\' {
862 escapeNext = true
863 continue
864 }
865
866 if char == '"' || char == '\'' {
867 if !inQuotes {
868 inQuotes = true
869 quoteChar = char
870 continue
871 } else if char == quoteChar {
872 inQuotes = false
873 quoteChar = rune(0)
874 continue
875 }
876 // Non-matching quote character inside quotes
877 current.WriteRune(char)
878 continue
879 }
880
881 // Space outside of quotes is an argument separator
882 if char == ' ' && !inQuotes {
883 if current.Len() > 0 {
884 result = append(result, current.String())
885 current.Reset()
886 }
887 continue
888 }
889
890 current.WriteRune(char)
891 }
892
893 // Add the last argument if there is one
894 if current.Len() > 0 {
895 result = append(result, current.String())
896 }
897
898 return result
899}