17 _ "golang.org/x/image/webp"
21 imageDirName = "images"
22 imageMaxBytes = 20 << 20
25 // ImageStore holds immutable images shared by the root, children, and
26 // subagents. Names are the SHA-256 of the bytes with the decoded format as
27 // extension. Publication is atomic and does not replace an existing image.
28 type ImageStore struct {
32 // Save validates and stores data, and returns its filename. Only JPEG, PNG, and
33 // WebP images up to 20 MB are accepted.
34 func (s *ImageStore) Save(data []byte) (name string, err error) {
35 format, err := imageFormat(data)
37 return "", fmt.Errorf("check image: %w", err)
40 sum := sha256.Sum256(data)
41 name = hex.EncodeToString(sum[:]) + "." + format
42 err = os.MkdirAll(s.dir, 0o700)
44 return "", fmt.Errorf("create image directory: %w", err)
47 file, err := os.CreateTemp(s.dir, ".image-*")
49 return "", fmt.Errorf("create image file: %w", err)
53 err = errors.Join(err, os.Remove(file.Name()))
56 _, err = file.Write(data)
61 err = errors.Join(err, file.Close())
63 return "", fmt.Errorf("write image: %w", err)
66 err = os.Link(file.Name(), filepath.Join(s.dir, name))
67 if err != nil && !errors.Is(err, os.ErrExist) {
68 return "", fmt.Errorf("publish image: %w", err)
74 // Read returns the bytes of a stored image after checking its name and content.
75 func (s *ImageStore) Read(name string) ([]byte, error) {
77 return nil, errors.New("invalid image name")
80 data, err := imageReadFile(filepath.Join(s.dir, name))
82 return nil, fmt.Errorf("read stored image: %w", err)
85 format, err := imageFormat(data)
87 return nil, fmt.Errorf("check stored image: %w", err)
90 sum := sha256.Sum256(data)
91 if name != hex.EncodeToString(sum[:])+"."+format {
92 return nil, errors.New("image content does not match its name")
98 func imageFormat(data []byte) (string, error) {
99 if len(data) > imageMaxBytes {
100 return "", errors.New("image exceeds 20 MB")
103 config, format, err := image.DecodeConfig(bytes.NewReader(data))
104 if err != nil || config.Width <= 0 || config.Height <= 0 {
105 return "", errors.New("use a JPEG, PNG, or WebP image")
114 return "", errors.New("use a JPEG, PNG, or WebP image")
118 func imageName(name string) bool {
119 hash, ext, found := strings.Cut(name, ".")
120 return found && len(hash) == 64 && strings.Trim(hash, "0123456789abcdef") == "" && (ext == "jpg" || ext == "png" || ext == "webp")
123 func imageReadFile(path string) (data []byte, err error) {
124 file, err := os.Open(path)
126 return nil, fmt.Errorf("open image: %w", err)
130 err = errors.Join(err, file.Close())
133 data, err = io.ReadAll(io.LimitReader(file, imageMaxBytes+1))
135 return nil, fmt.Errorf("read image: %w", err)
138 if len(data) > imageMaxBytes {
139 return nil, errors.New("image exceeds 20 MB")
145 // imageFiles reads only complete marker lines with valid store filenames.
146 func imageFiles(text string) []string {
149 for line := range strings.SplitSeq(text, "\n") {
150 name, found := strings.CutPrefix(line, "[image ")
151 if !found || !strings.HasSuffix(name, "]") {
155 name = strings.TrimSuffix(name, "]")
157 names = append(names, name)
164 func imageText(names []string, caption string) string {
165 var text strings.Builder
167 for _, name := range names {
168 text.WriteString("[image " + name + "]\n")
171 text.WriteString(caption)
173 return strings.TrimSuffix(text.String(), "\n")