| 1 | package control |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "path" |
| 8 | "strings" |
| 9 | |
| 10 | "reasonix/internal/attachment" |
| 11 | "reasonix/internal/config" |
| 12 | "reasonix/internal/provider" |
| 13 | "reasonix/internal/provider/openai" |
| 14 | ) |
| 15 | |
| 16 | func (c *Controller) StageImage(ctx context.Context, displayName, mime, dataURL string) (attachment.DraftCredential, error) { |
| 17 | ctx, cancel := c.NewAttachmentOperationContext(ctx) |
| 18 | defer cancel() |
| 19 | scope := c.attachmentScope() |
| 20 | svc := c.attachmentService() |
| 21 | prepared, err := svc.PrepareBatch(ctx, []attachment.Source{{DisplayName: displayName, DeclaredMIME: mime, DataURL: dataURL}}) |
| 22 | if err != nil { |
| 23 | return attachment.DraftCredential{}, err |
| 24 | } |
| 25 | refs, err := svc.CommitBatch(ctx, prepared) |
| 26 | if err != nil { |
| 27 | return attachment.DraftCredential{}, err |
| 28 | } |
| 29 | if err := ctx.Err(); err != nil { |
| 30 | return attachment.DraftCredential{}, err |
| 31 | } |
| 32 | if scope != c.attachmentScope() { |
| 33 | return attachment.DraftCredential{}, attachment.Error{Code: attachment.CodeChanged, Message: "attachment owner changed; please retry"} |
| 34 | } |
| 35 | return svc.Drafts().Issue(scope, refs[0]), nil |
| 36 | } |
| 37 | |
| 38 | func (c *Controller) ReadDraftImage(ctx context.Context, draftID string) (attachment.DraftCredential, []byte, error) { |
| 39 | draft, ok := c.attachmentService().Drafts().Lookup(c.attachmentScope(), draftID) |
| 40 | if !ok { |
| 41 | return attachment.DraftCredential{}, nil, attachment.Error{Code: attachment.CodeMissing, Message: "draft credential is not valid", Retry: true} |
| 42 | } |
| 43 | raw, err := c.attachmentService().ReadVerified(ctx, draft.Ref) |
| 44 | return draft, raw, err |
| 45 | } |
| 46 | |
| 47 | func (c *Controller) ReleaseDraftImage(draftID string) { |
| 48 | c.attachmentService().Drafts().Release(c.attachmentScope(), draftID) |
| 49 | } |
| 50 | |
| 51 | // ReadSessionAttachment returns one bounded range of an admitted original. |
| 52 | // digest is the only client-supplied identity; size and integrity come from |
| 53 | // this session's content graph. |
| 54 | func (c *Controller) ReadSessionAttachment(ctx context.Context, digest string, offset, length int64) ([]byte, int64, error) { |
| 55 | if c == nil { |
| 56 | return nil, 0, attachment.Error{Code: attachment.CodeMissing, Message: "attachment is not authorized for this session"} |
| 57 | } |
| 58 | service := c.SessionService() |
| 59 | ref, bound := c.SessionRef() |
| 60 | if service == nil || service.Query() == nil || !bound { |
| 61 | return nil, 0, attachment.Error{Code: attachment.CodeMissing, Message: "attachment is not authorized for this session"} |
| 62 | } |
| 63 | return service.Query().ReadSessionAttachment(ctx, ref, digest, offset, length) |
| 64 | } |
| 65 | |
| 66 | func (c *Controller) PersistToolImages(ctx context.Context, images []string) ([]attachment.ImageInput, error) { |
| 67 | if len(images) == 0 { |
| 68 | return nil, nil |
| 69 | } |
| 70 | out := make([]attachment.ImageInput, 0, len(images)) |
| 71 | var sources []attachment.Source |
| 72 | var slots []int |
| 73 | for _, image := range images { |
| 74 | switch provider.ClassifyImage(image) { |
| 75 | case provider.ImageHTTPURL: |
| 76 | out = append(out, attachment.ImageInput{Kind: attachment.KindURL, URL: image}) |
| 77 | case provider.ImageFileID: |
| 78 | out = append(out, attachment.ImageInput{Kind: attachment.KindFiles, FilesID: image}) |
| 79 | default: |
| 80 | slots = append(slots, len(out)) |
| 81 | out = append(out, attachment.ImageInput{}) |
| 82 | sources = append(sources, attachment.Source{DataURL: image}) |
| 83 | } |
| 84 | } |
| 85 | if len(sources) == 0 { |
| 86 | return out, nil |
| 87 | } |
| 88 | svc := c.attachmentService() |
| 89 | prepared, err := svc.PrepareBatch(ctx, sources) |
| 90 | if err != nil { |
| 91 | return nil, err |
| 92 | } |
| 93 | refs, err := svc.CommitBatch(ctx, prepared) |
| 94 | if err != nil { |
| 95 | return nil, err |
| 96 | } |
| 97 | for i, ref := range refs { |
| 98 | item := ref |
| 99 | out[slots[i]] = attachment.ImageInput{Kind: attachment.KindAttachment, Attachment: &item} |
| 100 | } |
| 101 | return out, nil |
| 102 | } |
| 103 | |
| 104 | func (c *Controller) ResolveRequestImages(ctx context.Context, msgs []provider.Message) ([]provider.Message, error) { |
| 105 | if c == nil { |
| 106 | return msgs, nil |
| 107 | } |
| 108 | return c.ResolveRequestImagesForModel(ctx, msgs, c.selection.ref, c.imageInputEnabled()) |
| 109 | } |
| 110 | |
| 111 | // ImageRequestRoute is request-local and must never be persisted in history. |
| 112 | type ImageRequestRoute struct { |
| 113 | Model string |
| 114 | BaseURL string |
| 115 | APIKey string |
| 116 | AuthHeader bool |
| 117 | Protocol string |
| 118 | } |
| 119 | |
| 120 | func (c *Controller) captureImageRoutes(cfg *config.Config) { |
| 121 | c.imageRoutes = make(map[string]ImageRequestRoute) |
| 122 | for _, entry := range cfg.Providers { |
| 123 | protocol := "openai" |
| 124 | if strings.EqualFold(entry.Kind, "anthropic") { |
| 125 | protocol = "anthropic" |
| 126 | } |
| 127 | route := ImageRequestRoute{BaseURL: entry.BaseURL, APIKey: entry.APIKey(), AuthHeader: entry.AuthHeader, Protocol: protocol} |
| 128 | c.imageRoutes[entry.Name] = route |
| 129 | } |
| 130 | if prefix, _, ok := strings.Cut(cfg.DefaultModel, "/"); ok { |
| 131 | c.imageRoutes[""] = c.imageRoutes[prefix] |
| 132 | } |
| 133 | c.imageRoutesReady = true |
| 134 | } |
| 135 | |
| 136 | func (c *Controller) imageRequestRoute(model string) (ImageRequestRoute, error) { |
| 137 | c.imageRoutesMu.Lock() |
| 138 | defer c.imageRoutesMu.Unlock() |
| 139 | if !c.imageRoutesReady { |
| 140 | cfg, err := config.LoadForRootReadOnly(c.workspaceRoot) |
| 141 | if err != nil { |
| 142 | // Failed reads are not a usable snapshot. A corrected configuration |
| 143 | // must take effect on the next attempt without rebuilding the task. |
| 144 | return ImageRequestRoute{}, err |
| 145 | } |
| 146 | c.captureImageRoutes(cfg) |
| 147 | } |
| 148 | prefix, _, _ := strings.Cut(model, "/") |
| 149 | route := c.imageRoutes[prefix] |
| 150 | route.Model = model |
| 151 | return route, nil |
| 152 | } |
| 153 | |
| 154 | func (c *Controller) ResolveRequestImagesForModel(ctx context.Context, msgs []provider.Message, model string, native bool) ([]provider.Message, error) { |
| 155 | if c == nil { |
| 156 | return msgs, nil |
| 157 | } |
| 158 | if _, ok := ctx.Value(imageReplayWarningsKey{}).(*imageReplayWarnings); !ok { |
| 159 | ctx = withImageReplayWarnings(ctx) |
| 160 | } |
| 161 | out := append([]provider.Message(nil), msgs...) |
| 162 | currentTurn := lastImageRequestTurn(msgs) |
| 163 | for i := range out { |
| 164 | if err := ctx.Err(); err != nil { |
| 165 | return nil, err |
| 166 | } |
| 167 | if out[i].LocalOnly { |
| 168 | continue |
| 169 | } |
| 170 | if err := out[i].ValidateImageFields(); err != nil { |
| 171 | if out[i].Role == provider.RoleTool && c.omitReplayImageFailure(ctx, &out[i], err, i < currentTurn) { |
| 172 | continue |
| 173 | } |
| 174 | if i >= currentTurn { |
| 175 | return nil, imageRequestFailure(ctx, err) |
| 176 | } |
| 177 | if len(out[i].Images) > 0 && len(out[i].ImageInputs) > 0 { |
| 178 | positions := make([]int, len(out[i].Images)+len(out[i].ImageInputs)) |
| 179 | for j := range positions { |
| 180 | positions[j] = j + 1 |
| 181 | } |
| 182 | noteUnavailableImages(&out[i], positions) |
| 183 | out[i].Images, out[i].ImageInputs = nil, nil |
| 184 | continue |
| 185 | } |
| 186 | // Per-input validation below preserves healthy historical siblings. |
| 187 | } |
| 188 | if len(out[i].ImageInputs) == 0 { |
| 189 | continue |
| 190 | } |
| 191 | if !native { |
| 192 | if err := c.understandReplayImages(ctx, &out[i], model, i < currentTurn); err != nil { |
| 193 | if !c.omitReplayImageFailure(ctx, &out[i], err, i < currentTurn) { |
| 194 | return nil, imageRequestFailure(ctx, err) |
| 195 | } |
| 196 | } |
| 197 | out[i].ImageInputs = nil |
| 198 | continue |
| 199 | } |
| 200 | route, err := c.imageRequestRoute(model) |
| 201 | if err != nil { |
| 202 | if c.omitReplayImageFailure(ctx, &out[i], err, i < currentTurn) { |
| 203 | continue |
| 204 | } |
| 205 | return nil, imageRequestFailure(ctx, err) |
| 206 | } |
| 207 | resolved, missing, err := c.resolveReplayImages(ctx, out[i].ImageInputs, route, i < currentTurn || out[i].Role == provider.RoleTool) |
| 208 | if err != nil { |
| 209 | return nil, imageRequestFailure(ctx, err) |
| 210 | } |
| 211 | noteUnavailableImages(&out[i], missing) |
| 212 | out[i].Images = resolved |
| 213 | out[i].ImageInputs = nil |
| 214 | } |
| 215 | return out, nil |
| 216 | } |
| 217 | |
| 218 | func (c *Controller) resolveImageInputsForRoute(ctx context.Context, inputs []attachment.ImageInput, route ImageRequestRoute) ([]string, error) { |
| 219 | out := make([]string, 0, len(inputs)) |
| 220 | for i, in := range inputs { |
| 221 | if err := ctx.Err(); err != nil { |
| 222 | return nil, err |
| 223 | } |
| 224 | if err := in.Validate(); err != nil { |
| 225 | return nil, err |
| 226 | } |
| 227 | switch in.Kind { |
| 228 | case attachment.KindURL: |
| 229 | out = append(out, in.URL) |
| 230 | case attachment.KindFiles: |
| 231 | out = append(out, in.FilesID) |
| 232 | case attachment.KindAttachment: |
| 233 | value, err := c.wireImageFromRefForRoute(ctx, *in.Attachment, route) |
| 234 | if err != nil { |
| 235 | var item attachment.Error |
| 236 | if errors.As(err, &item) { |
| 237 | item.Index = i + 1 |
| 238 | var readErr imageReadError |
| 239 | if errors.As(err, &readErr) { |
| 240 | return nil, imageReadError{item} |
| 241 | } |
| 242 | return nil, item |
| 243 | } |
| 244 | return nil, err |
| 245 | } |
| 246 | out = append(out, value) |
| 247 | } |
| 248 | } |
| 249 | return out, nil |
| 250 | } |
| 251 | |
| 252 | func (c *Controller) wireImageFromRefForRoute(ctx context.Context, ref attachment.AttachmentRef, route ImageRequestRoute) (string, error) { |
| 253 | svc := c.attachmentService() |
| 254 | variant, err := svc.PrepareVariant(ctx, ref, attachment.VariantPolicyV1) |
| 255 | if err != nil { |
| 256 | return "", imageReadError{err} |
| 257 | } |
| 258 | if len(variant.Bytes) <= inlineImageLimit { |
| 259 | return attachment.DataURL(variant.MIME, variant.Bytes), nil |
| 260 | } |
| 261 | id, err := uploadImageForRoute(ctx, route, ref.DisplayName, variant.Bytes) |
| 262 | if err == nil { |
| 263 | return id, nil |
| 264 | } |
| 265 | if ctx.Err() != nil { |
| 266 | return "", ctx.Err() |
| 267 | } |
| 268 | if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) { |
| 269 | return "", err |
| 270 | } |
| 271 | if len(variant.Bytes) > provider.MaxInlineImageBytes { |
| 272 | return "", err |
| 273 | } |
| 274 | return attachment.DataURL(variant.MIME, variant.Bytes), nil |
| 275 | } |
| 276 | |
| 277 | func uploadImageForRoute(ctx context.Context, route ImageRequestRoute, filename string, data []byte) (string, error) { |
| 278 | if err := ctx.Err(); err != nil { |
| 279 | return "", err |
| 280 | } |
| 281 | if !openai.IsDeepSeek(route.BaseURL) { |
| 282 | return "", errFilesAPI() |
| 283 | } |
| 284 | return uploadVisionFile(ctx, provider.FileUpload{ |
| 285 | BaseURL: route.BaseURL, |
| 286 | APIKey: route.APIKey, |
| 287 | AuthHeader: route.AuthHeader, |
| 288 | Protocol: route.Protocol, |
| 289 | Filename: path.Base(filename), |
| 290 | Data: data, |
| 291 | }) |
| 292 | } |
| 293 | |
| 294 | func errFilesAPI() error { return fmt.Errorf("files api requires official DeepSeek") } |
| 295 |