| 1 | package consult |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "fmt" |
| 6 | "io" |
| 7 | "os" |
| 8 | "strings" |
| 9 | |
| 10 | "the-valley/flow/internal/backend" |
| 11 | ) |
| 12 | |
| 13 | const MaxFileBytes = 200 * 1024 |
| 14 | |
| 15 | // Attachment is a file given with --file, read whole. |
| 16 | type Attachment struct { |
| 17 | Path string |
| 18 | Data []byte |
| 19 | } |
| 20 | |
| 21 | // ReadFiles reads the attachments, refusing them past MaxFileBytes in total. |
| 22 | func ReadFiles(paths []string) ([]Attachment, error) { |
| 23 | files := make([]Attachment, 0, len(paths)) |
| 24 | remaining := MaxFileBytes |
| 25 | for _, path := range paths { |
| 26 | f, err := os.Open(path) |
| 27 | if err != nil { |
| 28 | return nil, fmt.Errorf("reading attachment %s: %w", path, err) |
| 29 | } |
| 30 | data, err := io.ReadAll(io.LimitReader(f, int64(remaining)+1)) |
| 31 | f.Close() |
| 32 | if err != nil { |
| 33 | return nil, fmt.Errorf("reading attachment %s: %w", path, err) |
| 34 | } |
| 35 | remaining -= len(data) |
| 36 | if remaining < 0 { |
| 37 | return nil, fmt.Errorf("--file attachments exceed the 200KB total: %s takes them past %d bytes; attach fewer or smaller files", path, MaxFileBytes) |
| 38 | } |
| 39 | files = append(files, Attachment{Path: path, Data: data}) |
| 40 | } |
| 41 | return files, nil |
| 42 | } |
| 43 | |
| 44 | // InlineFiles appends the attachments to the prompt, each under a header |
| 45 | // naming its path. Headless agy can't open a path outside its workspace, and |
| 46 | // a denied read ends its turn with no answer, so for agy each file sits |
| 47 | // between BEGIN and END lines, behind a note that it is there in full. |
| 48 | func InlineFiles(kind backend.Kind, prompt string, files []Attachment) string { |
| 49 | var out strings.Builder |
| 50 | out.WriteString(prompt) |
| 51 | if kind != backend.Agy { |
| 52 | for _, f := range files { |
| 53 | fmt.Fprintf(&out, "\n\n### %s\n%s", f.Path, f.Data) |
| 54 | } |
| 55 | return out.String() |
| 56 | } |
| 57 | if len(files) == 0 { |
| 58 | return prompt |
| 59 | } |
| 60 | count := fmt.Sprintf("%d files are", len(files)) |
| 61 | if len(files) == 1 { |
| 62 | count = "1 file is" |
| 63 | } |
| 64 | fmt.Fprintf(&out, "\n\n%s attached below, each in full between its BEGIN and END lines. Read attachments here, not from disk: their paths can be outside your workspace, where you cannot open them.", count) |
| 65 | for i, f := range files { |
| 66 | fmt.Fprintf(&out, "\n\n===== BEGIN ATTACHED FILE %d of %d: %s =====\n%s", i+1, len(files), f.Path, f.Data) |
| 67 | if !bytes.HasSuffix(f.Data, []byte("\n")) { |
| 68 | out.WriteString("\n") |
| 69 | } |
| 70 | fmt.Fprintf(&out, "===== END ATTACHED FILE %d of %d: %s =====", i+1, len(files), f.Path) |
| 71 | } |
| 72 | return out.String() |
| 73 | } |