blob: 7ff0f903af0f89791d5c10f72b69e53a468ffdcd [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 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700127 gitRoot, err := findGitRoot(ctx, config.Path)
128 if err != nil {
129 return err
130 }
131
David Crawshaw5a7b3692025-05-05 16:49:15 -0700132 imgName, err := findOrBuildDockerImage(ctx, config.Path, gitRoot, config.Model, config.ModelURL, config.ModelAPIKey, config.ForceRebuild, config.Verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700133 if err != nil {
134 return err
135 }
136
137 linuxSketchBin := config.SketchBinaryLinux
138 if linuxSketchBin == "" {
David Crawshawb5f6a002025-05-05 08:27:16 -0700139 linuxSketchBin, err = buildLinuxSketchBin(ctx)
Earl Lee2e463fb2025-04-17 11:22:22 -0700140 if err != nil {
141 return err
142 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700143 }
144
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000145 cntrName := "sketch-" + config.SessionID
Earl Lee2e463fb2025-04-17 11:22:22 -0700146 defer func() {
147 if config.NoCleanup {
148 return
149 }
150 if out, err := combinedOutput(ctx, "docker", "kill", cntrName); err != nil {
151 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
152 _ = out
153 }
154 if out, err := combinedOutput(ctx, "docker", "rm", cntrName); err != nil {
155 // TODO: print in verbose mode? fmt.Fprintf(os.Stderr, "docker kill: %s: %v\n", out, err)
156 _ = out
157 }
158 }()
159
160 // errCh receives errors from operations that this function calls in separate goroutines.
161 errCh := make(chan error)
162
163 // Start the git server
164 gitSrv, err := newGitServer(gitRoot)
165 if err != nil {
166 return fmt.Errorf("failed to start git server: %w", err)
167 }
168 defer gitSrv.shutdown(ctx)
169
170 go func() {
171 errCh <- gitSrv.serve(ctx)
172 }()
173
174 // Get the current host git commit
175 var commit string
Philip Zeyliger1b47aa22025-04-28 19:25:38 +0000176 if out, err := combinedOutput(ctx, "git", "rev-parse", config.InitialCommit); err != nil {
177 return fmt.Errorf("git rev-parse %s: %w", config.InitialCommit, err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700178 } else {
179 commit = strings.TrimSpace(string(out))
180 }
181 if out, err := combinedOutput(ctx, "git", "config", "http.receivepack", "true"); err != nil {
182 return fmt.Errorf("git config http.receivepack true: %s: %w", out, err)
183 }
184
185 relPath, err := filepath.Rel(gitRoot, config.Path)
186 if err != nil {
187 return err
188 }
189
190 // Create the sketch container
191 if err := createDockerContainer(ctx, cntrName, hostPort, relPath, imgName, config); err != nil {
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000192 return fmt.Errorf("failed to create docker container: %w", err)
Earl Lee2e463fb2025-04-17 11:22:22 -0700193 }
194
195 // Copy the sketch linux binary into the container
196 if out, err := combinedOutput(ctx, "docker", "cp", linuxSketchBin, cntrName+":/bin/sketch"); err != nil {
197 return fmt.Errorf("docker cp: %s, %w", out, err)
198 }
Sean McCulloughf5bb3d32025-04-18 10:47:59 -0700199
200 // Make sure that the webui is built so we can copy the results to the container.
201 _, err = webui.Build()
202 if err != nil {
203 return fmt.Errorf("failed to build webui: %w", err)
204 }
205
David Crawshaw8bff16a2025-04-18 01:16:49 -0700206 webuiZipPath, err := webui.ZipPath()
207 if err != nil {
208 return err
209 }
210 if out, err := combinedOutput(ctx, "docker", "cp", webuiZipPath, cntrName+":/root/.cache/sketch/webui/"+filepath.Base(webuiZipPath)); err != nil {
211 return fmt.Errorf("docker cp: %s, %w", out, err)
212 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700213
David Crawshaw53786ef2025-04-24 12:52:51 -0700214 fmt.Printf("📦 running in container %s\n", cntrName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700215
216 // Start the sketch container
217 if out, err := combinedOutput(ctx, "docker", "start", cntrName); err != nil {
218 return fmt.Errorf("docker start: %s, %w", out, err)
219 }
220
221 // Copies structured logs from the container to the host.
222 copyLogs := func() {
223 if config.ContainerLogDest == "" {
224 return
225 }
226 out, err := combinedOutput(ctx, "docker", "logs", cntrName)
227 if err != nil {
228 fmt.Fprintf(os.Stderr, "docker logs failed: %v\n", err)
229 return
230 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700231 prefix := []byte("structured logs:")
232 for line := range bytes.Lines(out) {
233 rest, ok := bytes.CutPrefix(line, prefix)
234 if !ok {
Earl Lee2e463fb2025-04-17 11:22:22 -0700235 continue
236 }
Josh Bleecher Snyder7660e4e2025-04-24 10:34:17 -0700237 logFile := string(bytes.TrimSpace(rest))
Earl Lee2e463fb2025-04-17 11:22:22 -0700238 srcPath := fmt.Sprintf("%s:%s", cntrName, logFile)
239 logFileName := filepath.Base(logFile)
240 dstPath := filepath.Join(config.ContainerLogDest, logFileName)
241 _, err := combinedOutput(ctx, "docker", "cp", srcPath, dstPath)
242 if err != nil {
243 fmt.Fprintf(os.Stderr, "docker cp %s %s failed: %v\n", srcPath, dstPath, err)
244 }
245 fmt.Fprintf(os.Stderr, "\ncopied container log %s to %s\n", srcPath, dstPath)
246 }
247 }
248
249 // NOTE: we want to see what the internal sketch binary prints
250 // regardless of the setting of the verbosity flag on the external
251 // binary, so reading "docker logs", which is the stdout/stderr of
252 // the internal binary is not conditional on the verbose flag.
253 appendInternalErr := func(err error) error {
254 if err == nil {
255 return nil
256 }
257 out, logsErr := combinedOutput(ctx, "docker", "logs", cntrName)
Philip Zeyligerd1402952025-04-23 03:54:37 +0000258 if logsErr != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700259 return fmt.Errorf("%w; and docker logs failed: %s, %v", err, out, logsErr)
260 }
261 out = bytes.TrimSpace(out)
262 if len(out) > 0 {
263 return fmt.Errorf("docker logs: %s;\n%w", out, err)
264 }
265 return err
266 }
267
268 // Get the sketch server port from the container
Sean McCulloughae3480f2025-04-23 15:28:20 -0700269 localAddr, err := getContainerPort(ctx, cntrName, "80")
Earl Lee2e463fb2025-04-17 11:22:22 -0700270 if err != nil {
271 return appendInternalErr(err)
272 }
273
Philip Zeyliger00442412025-05-14 11:03:23 -0700274 if config.Verbose {
275 fmt.Fprintf(os.Stderr, "Host web server: http://%s/\n", localAddr)
276 }
277
Sean McCulloughae3480f2025-04-23 15:28:20 -0700278 localSSHAddr, err := getContainerPort(ctx, cntrName, "22")
279 if err != nil {
280 return appendInternalErr(err)
281 }
282 sshHost, sshPort, err := net.SplitHostPort(localSSHAddr)
283 if err != nil {
David Crawshawb5f6a002025-05-05 08:27:16 -0700284 return appendInternalErr(fmt.Errorf("failed to split ssh host and port: %w", err))
Sean McCulloughae3480f2025-04-23 15:28:20 -0700285 }
Sean McCullough4854c652025-04-24 18:37:02 -0700286
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700287 var sshServerIdentity, sshUserIdentity []byte
Sean McCullough4854c652025-04-24 18:37:02 -0700288
Sean McCullough078e85a2025-05-08 17:28:34 -0700289 cst, err := NewSSHTheater(cntrName, sshHost, sshPort)
290 if err != nil {
291 return appendInternalErr(fmt.Errorf("NewContainerSSHTheather: %w", err))
292 }
293
294 sshErr := CheckSSHReachability(cntrName)
Sean McCullough15c95282025-05-08 16:48:38 -0700295 sshAvailable := false
296 sshErrMsg := ""
297 if sshErr != nil {
298 fmt.Println(sshErr.Error())
299 sshErrMsg = sshErr.Error()
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700300 // continue - ssh config is not required for the rest of sketch to function locally.
301 } else {
Sean McCullough15c95282025-05-08 16:48:38 -0700302 sshAvailable = true
Sean McCulloughea3fc202025-04-28 12:53:37 -0700303 // Note: The vscode: link uses an undocumented request parameter that I really had to dig to find:
304 // https://github.com/microsoft/vscode/blob/2b9486161abaca59b5132ce3c59544f3cc7000f6/src/vs/code/electron-main/app.ts#L878
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700305 fmt.Printf(`Connect to this container via any of these methods:
Sean McCullough4854c652025-04-24 18:37:02 -0700306🖥️ ssh %s
307🖥️ code --remote ssh-remote+root@%s /app -n
Sean McCulloughea3fc202025-04-28 12:53:37 -0700308🔗 vscode://vscode-remote/ssh-remote+root@%s/app?windowId=_blank
Sean McCullough4854c652025-04-24 18:37:02 -0700309`, cntrName, cntrName, cntrName)
Sean McCulloughf5e28f62025-04-25 10:48:00 -0700310 sshUserIdentity = cst.userIdentity
311 sshServerIdentity = cst.serverIdentity
312 defer func() {
313 if err := cst.Cleanup(); err != nil {
314 appendInternalErr(err)
315 }
316 }()
317 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700318
Earl Lee2e463fb2025-04-17 11:22:22 -0700319 // Tell the sketch container which git server port and commit to initialize with.
320 go func() {
321 // TODO: Why is this called in a goroutine? I have found that when I pull this out
322 // of the goroutine and call it inline, then the terminal UI clears itself and all
323 // the scrollback (which is not good, but also not fatal). I can't see why it does this
324 // though, since none of the calls in postContainerInitConfig obviously write to stdout
325 // or stderr.
Sean McCullough15c95282025-05-08 16:48:38 -0700326 if err := postContainerInitConfig(ctx, localAddr, commit, gitSrv.gitPort, gitSrv.pass, sshAvailable, sshErrMsg, sshServerIdentity, sshUserIdentity); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700327 slog.ErrorContext(ctx, "LaunchContainer.postContainerInitConfig", slog.String("err", err.Error()))
328 errCh <- appendInternalErr(err)
329 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700330
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700331 // 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 -0700332 ps1URL := "http://" + localAddr
333 if config.SkabandAddr != "" {
334 ps1URL = fmt.Sprintf("%s/s/%s", config.SkabandAddr, config.SessionID)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700335 }
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700336 if config.OpenBrowser {
337 browser.Open(ps1URL)
338 }
339 gitSrv.ps1URL.Store(&ps1URL)
Philip Zeyliger6ed6adb2025-04-23 19:56:38 -0700340 }()
Earl Lee2e463fb2025-04-17 11:22:22 -0700341
342 go func() {
343 cmd := exec.CommandContext(ctx, "docker", "attach", cntrName)
344 cmd.Stdin = os.Stdin
345 cmd.Stdout = os.Stdout
346 cmd.Stderr = os.Stderr
347 errCh <- run(ctx, "docker attach", cmd)
348 }()
349
350 defer copyLogs()
351
352 for {
353 select {
354 case <-ctx.Done():
355 return ctx.Err()
356 case err := <-errCh:
357 if err != nil {
358 return appendInternalErr(fmt.Errorf("container process: %w", err))
359 }
360 return nil
361 }
362 }
363}
364
365func combinedOutput(ctx context.Context, cmdName string, args ...string) ([]byte, error) {
366 cmd := exec.CommandContext(ctx, cmdName, args...)
Earl Lee2e463fb2025-04-17 11:22:22 -0700367 start := time.Now()
368
369 out, err := cmd.CombinedOutput()
370 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700371 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 -0700372 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700373 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 -0700374 }
375 return out, err
376}
377
378func run(ctx context.Context, cmdName string, cmd *exec.Cmd) error {
379 start := time.Now()
380 err := cmd.Run()
381 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700382 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 -0700383 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700384 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 -0700385 }
386 return err
387}
388
389type gitServer struct {
390 gitLn net.Listener
391 gitPort string
392 srv *http.Server
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700393 pass string
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700394 ps1URL atomic.Pointer[string]
Earl Lee2e463fb2025-04-17 11:22:22 -0700395}
396
397func (gs *gitServer) shutdown(ctx context.Context) {
398 gs.srv.Shutdown(ctx)
399 gs.gitLn.Close()
400}
401
402// Serve a git remote from the host for the container to fetch from and push to.
403func (gs *gitServer) serve(ctx context.Context) error {
404 slog.DebugContext(ctx, "starting git server", slog.String("git_remote_addr", "http://host.docker.internal:"+gs.gitPort+"/.git"))
405 return gs.srv.Serve(gs.gitLn)
406}
407
408func newGitServer(gitRoot string) (*gitServer, error) {
Josh Bleecher Snyder9f6a9982025-04-22 17:34:15 -0700409 ret := &gitServer{
410 pass: rand.Text(),
411 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700412
Earl Lee2e463fb2025-04-17 11:22:22 -0700413 gitLn, err := net.Listen("tcp4", ":0")
414 if err != nil {
415 return nil, fmt.Errorf("git listen: %w", err)
416 }
417 ret.gitLn = gitLn
418
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700419 browserC := make(chan bool, 1) // channel of browser open requests
420
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000421 go func() {
Josh Bleecher Snyder99570462025-05-05 10:26:14 -0700422 for range browserC {
423 browser.Open(*ret.ps1URL.Load())
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000424 }
425 }()
426
427 srv := http.Server{Handler: &gitHTTP{gitRepoRoot: gitRoot, pass: []byte(ret.pass), browserC: browserC}}
Earl Lee2e463fb2025-04-17 11:22:22 -0700428 ret.srv = &srv
429
430 _, gitPort, err := net.SplitHostPort(gitLn.Addr().String())
431 if err != nil {
432 return nil, fmt.Errorf("git port: %w", err)
433 }
434 ret.gitPort = gitPort
435 return ret, nil
436}
437
438func createDockerContainer(ctx context.Context, cntrName, hostPort, relPath, imgName string, config ContainerConfig) error {
David Crawshaw69c67312025-04-17 13:42:00 -0700439 cmdArgs := []string{
440 "create",
David Crawshaw66cf74e2025-05-05 08:48:39 -0700441 "-i",
Earl Lee2e463fb2025-04-17 11:22:22 -0700442 "--name", cntrName,
443 "-p", hostPort + ":80", // forward container port 80 to a host port
David Crawshaw3659d872025-05-05 17:52:23 -0700444 "-e", "SKETCH_MODEL_API_KEY=" + config.ModelAPIKey,
Earl Lee2e463fb2025-04-17 11:22:22 -0700445 }
David Crawshaw66cf74e2025-05-05 08:48:39 -0700446 if !config.OneShot {
447 cmdArgs = append(cmdArgs, "-t")
448 }
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000449
450 for _, envVar := range getEnvForwardingFromGitConfig(ctx) {
451 cmdArgs = append(cmdArgs, "-e", envVar)
452 }
David Crawshaw5a7b3692025-05-05 16:49:15 -0700453 if config.ModelURL != "" {
David Crawshaw3659d872025-05-05 17:52:23 -0700454 cmdArgs = append(cmdArgs, "-e", "SKETCH_MODEL_URL="+config.ModelURL)
Earl Lee2e463fb2025-04-17 11:22:22 -0700455 }
456 if config.SketchPubKey != "" {
457 cmdArgs = append(cmdArgs, "-e", "SKETCH_PUB_KEY="+config.SketchPubKey)
458 }
Sean McCulloughae3480f2025-04-23 15:28:20 -0700459 if config.SSHPort > 0 {
460 cmdArgs = append(cmdArgs, "-p", fmt.Sprintf("%d:22", config.SSHPort)) // forward container ssh port to host ssh port
461 } else {
462 cmdArgs = append(cmdArgs, "-p", "22") // use an ephemeral host port for ssh.
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700463 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700464 if relPath != "." {
465 cmdArgs = append(cmdArgs, "-w", "/app/"+relPath)
466 }
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700467 // colima does this by default, but Linux docker seems to need this set explicitly
468 cmdArgs = append(cmdArgs, "--add-host", "host.docker.internal:host-gateway")
Earl Lee2e463fb2025-04-17 11:22:22 -0700469 cmdArgs = append(
470 cmdArgs,
471 imgName,
472 "/bin/sketch",
473 "-unsafe",
474 "-addr=:80",
475 "-session-id="+config.SessionID,
Philip Zeyligerd1402952025-04-23 03:54:37 +0000476 "-git-username="+config.GitUsername,
477 "-git-email="+config.GitEmail,
Philip Zeyliger18532b22025-04-23 21:11:46 +0000478 "-outside-hostname="+config.OutsideHostname,
479 "-outside-os="+config.OutsideOS,
480 "-outside-working-dir="+config.OutsideWorkingDir,
Josh Bleecher Snyder3cae7d92025-04-30 09:54:29 -0700481 "-open=false",
Josh Bleecher Snyderb1cca6f2025-05-06 01:52:55 +0000482 "-x="+config.ExperimentFlag,
Earl Lee2e463fb2025-04-17 11:22:22 -0700483 )
David Crawshaw5a7b3692025-05-05 16:49:15 -0700484 if config.Model != "" {
485 cmdArgs = append(cmdArgs, "-model="+config.Model)
486 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700487 if config.SkabandAddr != "" {
488 cmdArgs = append(cmdArgs, "-skaband-addr="+config.SkabandAddr)
489 }
Pokey Rule0dcebe12025-04-28 14:51:04 +0100490 if config.Prompt != "" {
491 cmdArgs = append(cmdArgs, "-prompt", config.Prompt)
492 }
493 if config.OneShot {
494 cmdArgs = append(cmdArgs, "-one-shot")
Philip Zeyligerb74c4f62025-04-25 19:18:49 -0700495 }
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000496
497 // Add additional docker arguments if provided
498 if config.DockerArgs != "" {
499 // Parse space-separated docker arguments with support for quotes and escaping
500 args := parseDockerArgs(config.DockerArgs)
501 // Insert arguments after "create" but before other arguments
502 for i := len(args) - 1; i >= 0; i-- {
503 cmdArgs = append(cmdArgs[:1], append([]string{args[i]}, cmdArgs[1:]...)...)
504 }
505 }
506
Earl Lee2e463fb2025-04-17 11:22:22 -0700507 if out, err := combinedOutput(ctx, "docker", cmdArgs...); err != nil {
508 return fmt.Errorf("docker create: %s, %w", out, err)
509 }
510 return nil
511}
512
David Crawshawb5f6a002025-05-05 08:27:16 -0700513func buildLinuxSketchBin(ctx context.Context) (string, error) {
Pokey Rulea9a786b2025-05-12 10:52:34 +0100514 // Change to directory containing dockerimg.go for module detection
515 _, codeFile, _, _ := runtime.Caller(0)
516 codeDir := filepath.Dir(codeFile)
517 if currentDir, err := os.Getwd(); err != nil {
518 slog.WarnContext(ctx, "could not get current directory", "err", err)
519 } else {
520 if err := os.Chdir(codeDir); err != nil {
521 slog.WarnContext(ctx, "could not change to code directory for module check", "err", err)
522 } else {
523 defer func() {
524 _ = os.Chdir(currentDir)
525 }()
526 }
527 }
528
David Crawshaw8a617cb2025-04-18 01:28:43 -0700529 homeDir, err := os.UserHomeDir()
David Crawshaw69c67312025-04-17 13:42:00 -0700530 if err != nil {
531 return "", err
532 }
David Crawshaw8a617cb2025-04-18 01:28:43 -0700533 linuxGopath := filepath.Join(homeDir, ".cache", "sketch", "linuxgo")
534 if err := os.MkdirAll(linuxGopath, 0o777); err != nil {
535 return "", err
536 }
537
538 verToInstall := "@latest"
539 if out, err := exec.Command("go", "list", "-m").CombinedOutput(); err != nil {
540 return "", fmt.Errorf("failed to run go list -m: %s: %v", out, err)
541 } else {
542 if strings.TrimSpace(string(out)) == "sketch.dev" {
David Crawshaw094e4d22025-04-24 11:35:14 -0700543 slog.DebugContext(ctx, "built linux agent from currently checked out module")
David Crawshaw8a617cb2025-04-18 01:28:43 -0700544 verToInstall = ""
545 }
546 }
David Crawshaw69c67312025-04-17 13:42:00 -0700547
Earl Lee2e463fb2025-04-17 11:22:22 -0700548 start := time.Now()
David Crawshaw8a617cb2025-04-18 01:28:43 -0700549 cmd := exec.CommandContext(ctx, "go", "install", "sketch.dev/cmd/sketch"+verToInstall)
David Crawshawb9eaef52025-04-17 15:23:18 -0700550 cmd.Env = append(
551 os.Environ(),
552 "GOOS=linux",
553 "CGO_ENABLED=0",
554 "GOTOOLCHAIN=auto",
David Crawshaw8a617cb2025-04-18 01:28:43 -0700555 "GOPATH="+linuxGopath,
Josh Bleecher Snyderfae17572025-04-21 11:48:05 -0700556 "GOBIN=",
David Crawshawb9eaef52025-04-17 15:23:18 -0700557 )
Earl Lee2e463fb2025-04-17 11:22:22 -0700558
Earl Lee2e463fb2025-04-17 11:22:22 -0700559 out, err := cmd.CombinedOutput()
560 if err != nil {
David Crawshawc7e77962025-05-03 13:20:18 -0700561 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 -0700562 return "", fmt.Errorf("failed to build linux sketch binary: %s: %w", out, err)
563 } else {
David Crawshawc7e77962025-05-03 13:20:18 -0700564 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 -0700565 }
566
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700567 if runtime.GOOS != "linux" {
David Crawshawc7e77962025-05-03 13:20:18 -0700568 return filepath.Join(linuxGopath, "bin", "linux_"+runtime.GOARCH, "sketch"), nil
Philip Zeyliger5e227dd2025-04-21 15:55:29 -0700569 }
David Crawshawc7e77962025-05-03 13:20:18 -0700570 // If we are already on Linux, there's no extra platform name in the path
571 return filepath.Join(linuxGopath, "bin", "sketch"), nil
Earl Lee2e463fb2025-04-17 11:22:22 -0700572}
573
Sean McCulloughae3480f2025-04-23 15:28:20 -0700574func getContainerPort(ctx context.Context, cntrName, cntrPort string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700575 localAddr := ""
Sean McCulloughae3480f2025-04-23 15:28:20 -0700576 if out, err := combinedOutput(ctx, "docker", "port", cntrName, cntrPort); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700577 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
578 } else {
579 v4, _, found := strings.Cut(string(out), "\n")
580 if !found {
581 return "", fmt.Errorf("failed to find container port: %s: %v", out, err)
582 }
583 localAddr = v4
584 if strings.HasPrefix(localAddr, "0.0.0.0") {
585 localAddr = "127.0.0.1" + strings.TrimPrefix(localAddr, "0.0.0.0")
586 }
587 }
588 return localAddr, nil
589}
590
591// Contact the container and configure it.
Sean McCullough15c95282025-05-08 16:48:38 -0700592func postContainerInitConfig(ctx context.Context, localAddr, commit, gitPort, gitPass string, sshAvailable bool, sshError string, sshServerIdentity, sshAuthorizedKeys []byte) error {
Earl Lee2e463fb2025-04-17 11:22:22 -0700593 localURL := "http://" + localAddr
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700594
595 initMsg, err := json.Marshal(
596 server.InitRequest{
597 Commit: commit,
Josh Bleecher Snyder3e2111b2025-04-30 17:53:28 +0000598 OutsideHTTP: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s", gitPass, gitPort),
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700599 GitRemoteAddr: fmt.Sprintf("http://sketch:%s@host.docker.internal:%s/.git", gitPass, gitPort),
600 HostAddr: localAddr,
601 SSHAuthorizedKeys: sshAuthorizedKeys,
602 SSHServerIdentity: sshServerIdentity,
Philip Zeyligerc72fff52025-04-29 20:17:54 +0000603 SSHAvailable: sshAvailable,
604 SSHError: sshError,
Sean McCulloughbaa2b592025-04-23 10:40:08 -0700605 })
Earl Lee2e463fb2025-04-17 11:22:22 -0700606 if err != nil {
607 return fmt.Errorf("init msg: %w", err)
608 }
609
Earl Lee2e463fb2025-04-17 11:22:22 -0700610 // Note: this /init POST is handled in loop/server/loophttp.go:
611 initMsgByteReader := bytes.NewReader(initMsg)
612 req, err := http.NewRequest("POST", localURL+"/init", initMsgByteReader)
613 if err != nil {
614 return err
615 }
616
617 var res *http.Response
618 for i := 0; ; i++ {
619 time.Sleep(100 * time.Millisecond)
620 // If you DON'T reset this byteReader, then subsequent retries may end up sending 0 bytes.
621 initMsgByteReader.Reset(initMsg)
622 res, err = http.DefaultClient.Do(req)
623 if err != nil {
David Crawshaw99231ba2025-05-03 10:48:26 -0700624 if i < 100 {
625 if i%10 == 0 {
626 slog.DebugContext(ctx, "postContainerInitConfig retrying", slog.Int("retry", i), slog.String("err", err.Error()))
627 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700628 continue
629 }
630 return fmt.Errorf("failed to %s/init sketch in container, NOT retrying: err: %v", localURL, err)
631 }
632 break
633 }
634 resBytes, _ := io.ReadAll(res.Body)
635 if res.StatusCode != http.StatusOK {
636 return fmt.Errorf("failed to initialize sketch in container, response status code %d: %s", res.StatusCode, resBytes)
637 }
638 return nil
639}
640
David Crawshaw5a7b3692025-05-05 16:49:15 -0700641func findOrBuildDockerImage(ctx context.Context, cwd, gitRoot, model, modelURL, modelAPIKey string, forceRebuild, verbose bool) (imgName string, err error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700642 h := sha256.Sum256([]byte(gitRoot))
643 imgName = "sketch-" + hex.EncodeToString(h[:6])
644
645 var curImgInitFilesHash string
646 if out, err := combinedOutput(ctx, "docker", "inspect", "--format", "{{json .Config.Labels}}", imgName); err != nil {
647 if strings.Contains(string(out), "No such object") {
648 // Image does not exist, continue and build it.
649 curImgInitFilesHash = ""
650 } else {
651 return "", fmt.Errorf("docker inspect failed: %s, %v", out, err)
652 }
653 } else {
654 m := map[string]string{}
655 if err := json.Unmarshal(bytes.TrimSpace(out), &m); err != nil {
656 return "", fmt.Errorf("docker inspect output unparsable: %s, %v", out, err)
657 }
658 curImgInitFilesHash = m["sketch_context"]
659 }
660
661 candidates, err := findRepoDockerfiles(cwd, gitRoot)
662 if err != nil {
663 return "", fmt.Errorf("find dockerfile: %w", err)
664 }
665
666 var initFiles map[string]string
667 var dockerfilePath string
David Crawshawff2df6a2025-05-12 14:45:29 -0700668 var generatedDockerfile string
Earl Lee2e463fb2025-04-17 11:22:22 -0700669
670 // TODO: prefer a "Dockerfile.sketch" so users can tailor any env to this tool.
671 if len(candidates) == 1 && strings.ToLower(filepath.Base(candidates[0])) == "dockerfile" {
672 dockerfilePath = candidates[0]
673 contents, err := os.ReadFile(dockerfilePath)
674 if err != nil {
675 return "", err
676 }
677 fmt.Printf("using %s as dev env\n", candidates[0])
678 if hashInitFiles(map[string]string{dockerfilePath: string(contents)}) == curImgInitFilesHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700679 return imgName, nil
680 }
681 } else {
682 initFiles, err = readInitFiles(os.DirFS(gitRoot))
683 if err != nil {
684 return "", err
685 }
686 subPathWorkingDir, err := filepath.Rel(gitRoot, cwd)
687 if err != nil {
688 return "", err
689 }
690 initFileHash := hashInitFiles(initFiles)
691 if curImgInitFilesHash == initFileHash && !forceRebuild {
Earl Lee2e463fb2025-04-17 11:22:22 -0700692 return imgName, nil
693 }
694
David Crawshaw5a7b3692025-05-05 16:49:15 -0700695 if model == "gemini" {
696 if strings.HasSuffix(modelURL, "/gemmsgs") {
697 // Horrible hack! Switch back to anthropic for container building.
David Crawshaw3659d872025-05-05 17:52:23 -0700698 // We can do this because we are talking to skaband and know the address.
David Crawshaw5a7b3692025-05-05 16:49:15 -0700699 modelURL = strings.Replace(modelURL, "/gemmsgs", "/antmsgs", 1)
700 } else {
701 return "", fmt.Errorf("building docker image with gemini model is not supported yet; start with -model=anthropic first then use gemini")
702 }
703 }
704
Earl Lee2e463fb2025-04-17 11:22:22 -0700705 start := time.Now()
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700706 srv := &ant.Service{
David Crawshaw5a7b3692025-05-05 16:49:15 -0700707 URL: modelURL,
708 APIKey: modelAPIKey,
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700709 HTTPC: http.DefaultClient,
710 }
Pokey Rulec31e2962025-05-13 10:53:33 +0000711 generatedDockerfile, err = createDockerfile(ctx, srv, initFiles, subPathWorkingDir, verbose)
Earl Lee2e463fb2025-04-17 11:22:22 -0700712 if err != nil {
713 return "", fmt.Errorf("create dockerfile: %w", err)
714 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000715 // Create a unique temporary directory for the Dockerfile
716 tmpDir, err := os.MkdirTemp("", "sketch-docker-*")
717 if err != nil {
718 return "", fmt.Errorf("failed to create temporary directory: %w", err)
719 }
720 dockerfilePath = filepath.Join(tmpDir, tmpSketchDockerfile)
David Crawshawff2df6a2025-05-12 14:45:29 -0700721 if err := os.WriteFile(dockerfilePath, []byte(generatedDockerfile), 0o666); err != nil {
Earl Lee2e463fb2025-04-17 11:22:22 -0700722 return "", err
723 }
Josh Bleecher Snyder7c58b022025-05-14 17:30:39 +0000724 // Remove the temporary directory and all contents when done
725 defer os.RemoveAll(tmpDir)
Earl Lee2e463fb2025-04-17 11:22:22 -0700726
David Crawshawb5f6a002025-05-05 08:27:16 -0700727 if verbose {
David Crawshawff2df6a2025-05-12 14:45:29 -0700728 fmt.Fprintf(os.Stderr, "generated Dockerfile in %s:\n\t%s\n\n", time.Since(start).Round(time.Millisecond), strings.Replace(generatedDockerfile, "\n", "\n\t", -1))
David Crawshawb5f6a002025-05-05 08:27:16 -0700729 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700730 }
731
732 var gitUserEmail, gitUserName string
733 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.email"); err != nil {
734 return "", fmt.Errorf("git config: %s: %v", out, err)
735 } else {
736 gitUserEmail = strings.TrimSpace(string(out))
737 }
738 if out, err := combinedOutput(ctx, "git", "config", "--get", "user.name"); err != nil {
739 return "", fmt.Errorf("git config: %s: %v", out, err)
740 } else {
741 gitUserName = strings.TrimSpace(string(out))
742 }
743
744 start := time.Now()
745 cmd := exec.CommandContext(ctx,
746 "docker", "build",
747 "-t", imgName,
748 "-f", dockerfilePath,
749 "--build-arg", "GIT_USER_EMAIL="+gitUserEmail,
750 "--build-arg", "GIT_USER_NAME="+gitUserName,
David Crawshaw31f15242025-05-06 16:03:49 -0700751 ".",
Earl Lee2e463fb2025-04-17 11:22:22 -0700752 )
David Crawshawb5f6a002025-05-05 08:27:16 -0700753 cmd.Dir = gitRoot
David Crawshaw31f15242025-05-06 16:03:49 -0700754 // We print the docker build output whether or not the user
755 // has selected --verbose. Building an image takes a while
756 // and this gives good context.
David Crawshawb5f6a002025-05-05 08:27:16 -0700757 cmd.Stdout = os.Stdout
758 cmd.Stderr = os.Stderr
759 fmt.Printf("🏗️ building docker image %s... (use -verbose to see build output)\n", imgName)
Earl Lee2e463fb2025-04-17 11:22:22 -0700760
761 err = run(ctx, "docker build", cmd)
762 if err != nil {
David Crawshawff2df6a2025-05-12 14:45:29 -0700763 var msg string
764 if generatedDockerfile != "" {
765 if !verbose {
766 fmt.Fprintf(os.Stderr, "Generated Dockerfile:\n\t%s\n\n", strings.Replace(generatedDockerfile, "\n", "\n\t", -1))
767 }
768 msg = fmt.Sprintf("\n\nThe generated Dockerfile failed to build.\nYou can override it by committing a Dockerfile to your project.")
769 }
770 return "", fmt.Errorf("docker build failed: %v%s", err, msg)
Earl Lee2e463fb2025-04-17 11:22:22 -0700771 }
772 fmt.Printf("built docker image %s in %s\n", imgName, time.Since(start).Round(time.Millisecond))
773 return imgName, nil
774}
775
776func findRepoDockerfiles(cwd, gitRoot string) ([]string, error) {
777 files, err := findDirDockerfiles(cwd)
778 if err != nil {
779 return nil, err
780 }
781 if len(files) > 0 {
782 return files, nil
783 }
784
785 path := cwd
786 for path != gitRoot {
787 path = filepath.Dir(path)
788 files, err := findDirDockerfiles(path)
789 if err != nil {
790 return nil, err
791 }
792 if len(files) > 0 {
793 return files, nil
794 }
795 }
796 return files, nil
797}
798
799// findDirDockerfiles finds all "Dockerfile*" files in a directory.
800func findDirDockerfiles(root string) (res []string, err error) {
801 err = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
802 if err != nil {
803 return err
804 }
805 if info.IsDir() && root != path {
806 return filepath.SkipDir
807 }
808 name := strings.ToLower(info.Name())
809 if name == "dockerfile" || strings.HasPrefix(name, "dockerfile.") {
810 res = append(res, path)
811 }
812 return nil
813 })
814 if err != nil {
815 return nil, err
816 }
817 return res, nil
818}
819
820func findGitRoot(ctx context.Context, path string) (string, error) {
821 cmd := exec.CommandContext(ctx, "git", "rev-parse", "--git-common-dir")
822 cmd.Dir = path
823 out, err := cmd.CombinedOutput()
824 if err != nil {
825 if strings.Contains(string(out), "not a git repository") {
826 return "", fmt.Errorf(`sketch needs to run from within a git repo, but %s is not part of a git repo.
827Consider one of the following options:
828 - cd to a different dir that is already part of a git repo first, or
829 - to create a new git repo from this directory (%s), run this command:
830
831 git init . && git commit --allow-empty -m "initial commit"
832
833and try running sketch again.
834`, path, path)
835 }
836 return "", fmt.Errorf("git rev-parse --git-common-dir: %s: %w", out, err)
837 }
838 gitDir := strings.TrimSpace(string(out)) // location of .git dir, often as a relative path
839 absGitDir := filepath.Join(path, gitDir)
840 return filepath.Dir(absGitDir), err
841}
842
Josh Bleecher Snyder2772f632025-05-01 21:42:35 +0000843// getEnvForwardingFromGitConfig retrieves environment variables to pass through to Docker
844// from git config using the sketch.envfwd multi-valued key.
845func getEnvForwardingFromGitConfig(ctx context.Context) []string {
846 outb, err := exec.CommandContext(ctx, "git", "config", "--get-all", "sketch.envfwd").CombinedOutput()
847 out := string(outb)
848 if err != nil {
849 if strings.Contains(out, "key does not exist") {
850 return nil
851 }
852 slog.ErrorContext(ctx, "failed to get sketch.envfwd from git config", "err", err, "output", out)
853 return nil
854 }
855
856 var envVars []string
857 for envVar := range strings.Lines(out) {
858 envVar = strings.TrimSpace(envVar)
859 if envVar == "" {
860 continue
861 }
862 envVars = append(envVars, envVar+"="+os.Getenv(envVar))
863 }
864 return envVars
865}
Philip Zeyliger1dc21372025-05-05 19:54:44 +0000866
867// parseDockerArgs parses a string containing space-separated Docker arguments into an array of strings.
868// It handles quoted arguments and escaped characters.
869//
870// Examples:
871//
872// --memory=2g --cpus=2 -> ["--memory=2g", "--cpus=2"]
873// --label="my label" --env=FOO=bar -> ["--label=my label", "--env=FOO=bar"]
874// --env="KEY=\"quoted value\"" -> ["--env=KEY=\"quoted value\""]
875func parseDockerArgs(args string) []string {
876 if args = strings.TrimSpace(args); args == "" {
877 return []string{}
878 }
879
880 var result []string
881 var current strings.Builder
882 inQuotes := false
883 escapeNext := false
884 quoteChar := rune(0)
885
886 for _, char := range args {
887 if escapeNext {
888 current.WriteRune(char)
889 escapeNext = false
890 continue
891 }
892
893 if char == '\\' {
894 escapeNext = true
895 continue
896 }
897
898 if char == '"' || char == '\'' {
899 if !inQuotes {
900 inQuotes = true
901 quoteChar = char
902 continue
903 } else if char == quoteChar {
904 inQuotes = false
905 quoteChar = rune(0)
906 continue
907 }
908 // Non-matching quote character inside quotes
909 current.WriteRune(char)
910 continue
911 }
912
913 // Space outside of quotes is an argument separator
914 if char == ' ' && !inQuotes {
915 if current.Len() > 0 {
916 result = append(result, current.String())
917 current.Reset()
918 }
919 continue
920 }
921
922 current.WriteRune(char)
923 }
924
925 // Add the last argument if there is one
926 if current.Len() > 0 {
927 result = append(result, current.String())
928 }
929
930 return result
931}