blob: a7f641c5f27241e975f6553c0e7844cb663a9bca [file] [log] [blame]
Earl Lee2e463fb2025-04-17 11:22:22 -07001package dockerimg
2
3import (
4 "bytes"
5 "context"
6 "crypto/sha256"
7 "encoding/hex"
8 "encoding/json"
9 "fmt"
David Crawshaw2a5bd6d2025-04-30 14:29:46 -070010 "io"
Earl Lee2e463fb2025-04-17 11:22:22 -070011 "io/fs"
12 "maps"
13 "net/http"
14 "slices"
15 "strings"
16 "text/template"
17
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -070018 "sketch.dev/llm"
19 "sketch.dev/llm/conversation"
Earl Lee2e463fb2025-04-17 11:22:22 -070020)
21
22func hashInitFiles(initFiles map[string]string) string {
23 h := sha256.New()
24 for _, path := range slices.Sorted(maps.Keys(initFiles)) {
25 fmt.Fprintf(h, "%s\n%s\n\n", path, initFiles[path])
26 }
David Crawshaw2a5bd6d2025-04-30 14:29:46 -070027 fmt.Fprintf(h, "docker template\n%s\n", dockerfileDefaultTmpl)
Earl Lee2e463fb2025-04-17 11:22:22 -070028 return hex.EncodeToString(h.Sum(nil))
29}
30
David Crawshaw11129492025-04-25 20:41:53 -070031// DefaultImage is intended to ONLY be used by the pushdockerimg.go script.
David Crawshaw2a5bd6d2025-04-30 14:29:46 -070032func DefaultImage() (name, dockerfile, tag string) {
33 return dockerImgName, dockerfileBase, dockerfileBaseHash()
David Crawshaw11129492025-04-25 20:41:53 -070034}
35
Philip Zeyligerbce3a132025-04-30 22:03:39 +000036const (
37 dockerImgRepo = "boldsoftware/sketch"
38 dockerImgName = "ghcr.io/" + dockerImgRepo
39)
David Crawshaw5bff6502025-04-26 09:11:40 -070040
David Crawshaw2a5bd6d2025-04-30 14:29:46 -070041func dockerfileBaseHash() string {
42 h := sha256.New()
43 io.WriteString(h, dockerfileBase)
44 return hex.EncodeToString(h.Sum(nil))[:32]
45}
David Crawshaw11129492025-04-25 20:41:53 -070046
David Crawshaw2a5bd6d2025-04-30 14:29:46 -070047const dockerfileBase = `FROM golang:1.24-bookworm
David Crawshawbe10fa92025-04-18 01:16:00 -070048
David Crawshaw5228b582025-05-01 11:18:12 -070049# attempt to keep package installs lean
50RUN printf '%s\n' \
51 'path-exclude=/usr/share/man/*' \
52 'path-exclude=/usr/share/doc/*' \
53 'path-exclude=/usr/share/doc-base/*' \
54 'path-exclude=/usr/share/info/*' \
55 'path-exclude=/usr/share/locale/*' \
56 'path-exclude=/usr/share/groff/*' \
57 'path-exclude=/usr/share/lintian/*' \
58 'path-exclude=/usr/share/zoneinfo/*' \
59 > /etc/dpkg/dpkg.cfg.d/01_nodoc
60
David Crawshawfa67fe52025-05-01 20:42:08 +000061RUN set -eux; \
David Crawshaw2a5bd6d2025-04-30 14:29:46 -070062 apt-get update; \
63 apt-get install -y --no-install-recommends \
David Crawshawfa67fe52025-05-01 20:42:08 +000064 git jq sqlite3 npm nodejs gh ripgrep fzf python3 curl vim && \
65 apt-get clean && \
66 rm -rf /var/lib/apt/lists/*
David Crawshawbe10fa92025-04-18 01:16:00 -070067
David Crawshaw5228b582025-05-01 11:18:12 -070068# Strip out docs from debian.
69RUN rm -rf /usr/share/{doc,doc-base,info,lintian,man,groff,locale,zoneinfo}/*
70
David Crawshawbe10fa92025-04-18 01:16:00 -070071ENV PATH="$GOPATH/bin:$PATH"
72
David Crawshaw5228b582025-05-01 11:18:12 -070073# While these binaries install generally useful supporting packages,
74# the specific versions are rarely what a user wants so there is no
75# point polluting the base image module with them.
76
David Crawshawfa67fe52025-05-01 20:42:08 +000077RUN set -eux; \
David Crawshaw5228b582025-05-01 11:18:12 -070078 go install golang.org/x/tools/cmd/goimports@latest; \
79 go install golang.org/x/tools/gopls@latest; \
80 go install mvdan.cc/gofumpt@latest; \
David Crawshawfa67fe52025-05-01 20:42:08 +000081 go clean -cache -testcache -modcache
David Crawshawbe10fa92025-04-18 01:16:00 -070082
David Crawshaw2a5bd6d2025-04-30 14:29:46 -070083ENV GOTOOLCHAIN=auto
David Crawshaw5228b582025-05-01 11:18:12 -070084ENV SKETCH=1
David Crawshaw2a5bd6d2025-04-30 14:29:46 -070085
David Crawshawbe10fa92025-04-18 01:16:00 -070086RUN mkdir -p /root/.cache/sketch/webui
David Crawshaw11129492025-04-25 20:41:53 -070087`
David Crawshawbe10fa92025-04-18 01:16:00 -070088
David Crawshaw11129492025-04-25 20:41:53 -070089const dockerfileFragment = `
David Crawshawbe10fa92025-04-18 01:16:00 -070090ARG GIT_USER_EMAIL
91ARG GIT_USER_NAME
92
93RUN git config --global user.email "$GIT_USER_EMAIL" && \
David Crawshawca535582025-05-03 13:04:34 -070094 git config --global user.name "$GIT_USER_NAME" && \
95 git config --global http.postBuffer 524288000
David Crawshawbe10fa92025-04-18 01:16:00 -070096
Josh Bleecher Snyderc76a3922025-05-01 01:18:56 +000097LABEL sketch_context="{{.InitFilesHash}}"
David Crawshawbe10fa92025-04-18 01:16:00 -070098COPY . /app
99
100WORKDIR /app{{.SubDir}}
101RUN if [ -f go.mod ]; then go mod download; fi
102
David Crawshaw11129492025-04-25 20:41:53 -0700103{{.ExtraCmds}}
104
105CMD ["/bin/sketch"]
106`
107
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700108var dockerfileDefaultTmpl = "FROM " + dockerImgName + ":" + dockerfileBaseHash() + "\n" + dockerfileFragment
David Crawshaw11129492025-04-25 20:41:53 -0700109
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700110func readPublishedTags() ([]string, error) {
111 req, err := http.NewRequest("GET", "https://ghcr.io/token?service=ghcr.io&scope=repository:"+dockerImgRepo+":pull", nil)
112 if err != nil {
113 return nil, fmt.Errorf("token: %w", err)
114 }
115 res, err := http.DefaultClient.Do(req)
116 if err != nil {
117 return nil, fmt.Errorf("token: %w", err)
118 }
119 body, err := io.ReadAll(res.Body)
120 res.Body.Close()
121 if err != nil || res.StatusCode != 200 {
122 return nil, fmt.Errorf("token: %d: %s: %w", res.StatusCode, body, err)
123 }
124 var tokenBody struct {
125 Token string `json:"token"`
126 }
127 if err := json.Unmarshal(body, &tokenBody); err != nil {
128 return nil, fmt.Errorf("token: %w: %s", err, body)
129 }
130
131 req, err = http.NewRequest("GET", "https://ghcr.io/v2/"+dockerImgRepo+"/tags/list", nil)
132 if err != nil {
133 return nil, fmt.Errorf("tags: %w", err)
134 }
135 req.Header.Set("Authorization", "Bearer "+tokenBody.Token)
136 res, err = http.DefaultClient.Do(req)
137 if err != nil {
138 return nil, fmt.Errorf("tags: %w", err)
139 }
140 body, err = io.ReadAll(res.Body)
141 res.Body.Close()
142 if err != nil || res.StatusCode != 200 {
143 return nil, fmt.Errorf("tags: %d: %s: %w", res.StatusCode, body, err)
144 }
145 var tags struct {
146 Tags []string `json:"tags"`
147 }
148 if err := json.Unmarshal(body, &tags); err != nil {
149 return nil, fmt.Errorf("tags: %w: %s", err, body)
150 }
151 return tags.Tags, nil
152}
153
154func checkTagExists(tag string) error {
155 tags, err := readPublishedTags()
156 if err != nil {
157 return fmt.Errorf("check tag exists: %w", err)
158 }
159 for _, t := range tags {
160 if t == tag {
161 return nil // found it
162 }
163 }
164 return fmt.Errorf("check tag exists: %q not found in %v", tag, tags)
165}
David Crawshawbe10fa92025-04-18 01:16:00 -0700166
Earl Lee2e463fb2025-04-17 11:22:22 -0700167// createDockerfile creates a Dockerfile for a git repo.
168// It expects the relevant initFiles to have been provided.
169// If the sketch binary is being executed in a sub-directory of the repository,
170// the relative path is provided on subPathWorkingDir.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700171func createDockerfile(ctx context.Context, srv llm.Service, initFiles map[string]string, subPathWorkingDir string) (string, error) {
Earl Lee2e463fb2025-04-17 11:22:22 -0700172 if subPathWorkingDir == "." {
173 subPathWorkingDir = ""
174 } else if subPathWorkingDir != "" && subPathWorkingDir[0] != '/' {
175 subPathWorkingDir = "/" + subPathWorkingDir
176 }
177 toolCalled := false
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700178 var dockerfileExtraCmds string
Earl Lee2e463fb2025-04-17 11:22:22 -0700179 runDockerfile := func(ctx context.Context, input json.RawMessage) (string, error) {
180 // TODO: unmarshal straight into a struct
181 var m map[string]any
182 if err := json.Unmarshal(input, &m); err != nil {
183 return "", fmt.Errorf(`input=%[1]v (%[1]T), wanted a map[string]any, got: %w`, input, err)
184 }
185 var ok bool
Earl Lee2e463fb2025-04-17 11:22:22 -0700186 dockerfileExtraCmds, ok = m["extra_cmds"].(string)
187 if !ok {
188 return "", fmt.Errorf(`input["extra_cmds"]=%[1]v (%[1]T), wanted a string`, m["path"])
189 }
190 toolCalled = true
191 return "OK", nil
192 }
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700193
194 convo := conversation.New(ctx, srv)
195
196 convo.Tools = []*llm.Tool{{
Earl Lee2e463fb2025-04-17 11:22:22 -0700197 Name: "dockerfile",
198 Description: "Helps define a Dockerfile that sets up a dev environment for this project.",
199 Run: runDockerfile,
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700200 InputSchema: llm.MustSchema(`{
Earl Lee2e463fb2025-04-17 11:22:22 -0700201 "type": "object",
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700202 "required": ["extra_cmds"],
Earl Lee2e463fb2025-04-17 11:22:22 -0700203 "properties": {
Earl Lee2e463fb2025-04-17 11:22:22 -0700204 "extra_cmds": {
205 "type": "string",
206 "description": "Extra commands to add to the dockerfile."
207 }
208 }
209}`),
210 }}
211
Earl Lee2e463fb2025-04-17 11:22:22 -0700212 // TODO: it's basically impossible to one-shot a python env. We need an agent loop for that.
213 // Right now the prompt contains a set of half-baked workarounds.
214
215 // If you want to edit the model prompt, run:
216 //
Philip Zeyligercc3ba222025-04-23 14:52:21 -0700217 // go test ./dockerimg -httprecord ".*" -rewritewant
Earl Lee2e463fb2025-04-17 11:22:22 -0700218 //
219 // Then look at the changes with:
220 //
Philip Zeyligercc3ba222025-04-23 14:52:21 -0700221 // git diff dockerimg/testdata/*.dockerfile
Earl Lee2e463fb2025-04-17 11:22:22 -0700222 //
223 // If the dockerfile changes are a strict improvement, commit all the changes.
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700224 msg := llm.Message{
225 Role: llm.MessageRoleUser,
226 Content: []llm.Content{{
227 Type: llm.ContentTypeText,
Earl Lee2e463fb2025-04-17 11:22:22 -0700228 Text: `
229Call the dockerfile tool to create a Dockerfile.
230The parameters to dockerfile fill out the From and ExtraCmds
231template variables in the following Go template:
232
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700233` + "```\n" + dockerfileBase + dockerfileFragment + "\n```" + `
Earl Lee2e463fb2025-04-17 11:22:22 -0700234
235In particular:
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700236- Assume it is primarily a Go project.
Earl Lee2e463fb2025-04-17 11:22:22 -0700237- Python env setup is challenging and often no required, so any RUN commands involving python tooling should be written to let docker build continue if there is a failure.
238- Include any tools particular to this repository that can be inferred from the given context.
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700239- Append || true to any apt-get install commands in case the package does not exist.
240- MINIMIZE the number of extra_cmds generated. Straightforward environments do not need any.
David Crawshaw11129492025-04-25 20:41:53 -0700241- Do NOT expose any ports.
242- Do NOT generate any CMD or ENTRYPOINT extra commands.
Earl Lee2e463fb2025-04-17 11:22:22 -0700243`,
244 }},
245 }
246 if len(initFiles) > 0 {
247 msg.Content[0].Text += "Here is the content of several files from the repository that may be relevant:\n\n"
248 }
249
250 for _, name := range slices.Sorted(maps.Keys(initFiles)) {
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700251 msg.Content = append(msg.Content, llm.StringContent(fmt.Sprintf("Here is the contents %s:\n<file>\n%s\n</file>\n\n", name, initFiles[name])))
Earl Lee2e463fb2025-04-17 11:22:22 -0700252 }
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700253 msg.Content = append(msg.Content, llm.StringContent("Now call the dockerfile tool."))
Earl Lee2e463fb2025-04-17 11:22:22 -0700254 res, err := convo.SendMessage(msg)
255 if err != nil {
256 return "", err
257 }
Josh Bleecher Snyder4f84ab72025-04-22 16:40:54 -0700258 if res.StopReason != llm.StopReasonToolUse {
259 return "", fmt.Errorf("expected stop reason %q, got %q", llm.StopReasonToolUse, res.StopReason)
Earl Lee2e463fb2025-04-17 11:22:22 -0700260 }
261 if _, err := convo.ToolResultContents(context.TODO(), res); err != nil {
262 return "", err
263 }
264 if !toolCalled {
265 return "", fmt.Errorf("no dockerfile returned")
266 }
267
David Crawshaw2a5bd6d2025-04-30 14:29:46 -0700268 tmpl := dockerfileDefaultTmpl
269 if tag := dockerfileBaseHash(); checkTagExists(tag) != nil {
270 // In development, if you edit dockerfileBase but don't release
271 // (as is reasonable for testing things!) the hash won't exist
272 // yet. In that case, we skip the sketch image and build it ourselves.
273 fmt.Printf("published container tag %s:%s missing; building locally\n", dockerImgName, tag)
274 tmpl = dockerfileBase + dockerfileFragment
David Crawshaw11129492025-04-25 20:41:53 -0700275 }
Earl Lee2e463fb2025-04-17 11:22:22 -0700276 buf := new(bytes.Buffer)
David Crawshaw11129492025-04-25 20:41:53 -0700277 err = template.Must(template.New("dockerfile").Parse(tmpl)).Execute(buf, map[string]string{
Josh Bleecher Snyderc76a3922025-05-01 01:18:56 +0000278 "ExtraCmds": dockerfileExtraCmds,
279 "SubDir": subPathWorkingDir,
280 "InitFilesHash": hashInitFiles(initFiles),
Earl Lee2e463fb2025-04-17 11:22:22 -0700281 })
282 if err != nil {
283 return "", fmt.Errorf("dockerfile template failed: %w", err)
284 }
285
286 return buf.String(), nil
287}
288
289// For future reference: we can find the current git branch/checkout with: git symbolic-ref -q --short HEAD || git describe --tags --exact-match 2>/dev/null || git rev-parse HEAD
290
291func readInitFiles(fsys fs.FS) (map[string]string, error) {
292 result := make(map[string]string)
293
294 err := fs.WalkDir(fsys, ".", func(path string, d fs.DirEntry, err error) error {
295 if err != nil {
296 return err
297 }
298 if d.IsDir() && (d.Name() == ".git" || d.Name() == "node_modules") {
299 return fs.SkipDir
300 }
301 if !d.Type().IsRegular() {
302 return nil
303 }
304
305 // Case 1: Check for README files
306 // TODO: find README files between the .git root (where we start)
307 // and the dir that sketch was initialized. This needs more info
308 // plumbed to this function.
309 if strings.HasPrefix(strings.ToLower(path), "readme") {
310 content, err := fs.ReadFile(fsys, path)
311 if err != nil {
312 return err
313 }
314 result[path] = string(content)
315 return nil
316 }
317
318 // Case 2: Check for GitHub workflow files
319 if strings.HasPrefix(path, ".github/workflows/") {
320 content, err := fs.ReadFile(fsys, path)
321 if err != nil {
322 return err
323 }
324 result[path] = string(content)
325 return nil
326 }
327
328 return nil
329 })
330 if err != nil {
331 return nil, err
332 }
333 return result, nil
334}