| 1 | package opencode |
| 2 | |
| 3 | import ( |
| 4 | "crypto/rand" |
| 5 | "encoding/hex" |
| 6 | "errors" |
| 7 | "io" |
| 8 | "math" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "runtime" |
| 12 | "strconv" |
| 13 | "strings" |
| 14 | "syscall" |
| 15 | |
| 16 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 17 | ) |
| 18 | |
| 19 | // Install is where a runner's OpenCode is: the installed tree and the |
| 20 | // binary in it, with the digests a launch requires (this platform's |
| 21 | // pins; a test passes its fake's). |
| 22 | type Install struct { |
| 23 | Tree, Binary, TreeSHA256, BinarySHA256 string |
| 24 | } |
| 25 | |
| 26 | // Pinned fills the digests from this platform's pins. |
| 27 | func (i Install) Pinned() (Install, bool) { |
| 28 | tree, platform, ok := Pins(runtime.GOARCH) |
| 29 | if !ok { |
| 30 | return i, false |
| 31 | } |
| 32 | if i.TreeSHA256 == "" { |
| 33 | i.TreeSHA256 = tree |
| 34 | } |
| 35 | if i.BinarySHA256 == "" { |
| 36 | i.BinarySHA256 = platform.BinarySHA256 |
| 37 | } |
| 38 | return i, i.Tree != "" && i.Binary != "" |
| 39 | } |
| 40 | |
| 41 | // At is the install under root (EQUIPO_OPENCODE_ROOT) for this platform. |
| 42 | func At(root string) (Install, bool) { |
| 43 | _, platform, ok := Pins(runtime.GOARCH) |
| 44 | if !ok || root == "" { |
| 45 | return Install{}, false |
| 46 | } |
| 47 | tree, binary := Paths(root, platform.Package) |
| 48 | return Install{Tree: tree, Binary: binary}, true |
| 49 | } |
| 50 | |
| 51 | // Run is one OpenCode launch's inputs, before the policy is built. |
| 52 | type Run struct { |
| 53 | Install |
| 54 | Bwrap, ToolProxy string |
| 55 | Workspace, Action string |
| 56 | Provider, Model string |
| 57 | Equipo []string |
| 58 | Resume string |
| 59 | EgressHosts []string |
| 60 | ExtraCA string |
| 61 | } |
| 62 | |
| 63 | // Prepare makes the attempt's runtime home (under scratchRoot/homes, |
| 64 | // 0700: the containment mounts only a home there), writes OpenCode's |
| 65 | // configuration into it, and returns the policy inputs. Cleanup removes |
| 66 | // the home. |
| 67 | func Prepare(scratchRoot string, r Run) (provider.OpenCodePolicyInputs, func(), error) { |
| 68 | homes := filepath.Join(scratchRoot, "homes") |
| 69 | if err := os.MkdirAll(homes, 0700); err != nil { |
| 70 | return provider.OpenCodePolicyInputs{}, nil, err |
| 71 | } |
| 72 | var b [6]byte |
| 73 | rand.Read(b[:]) |
| 74 | home := filepath.Join(homes, "opencode-"+hex.EncodeToString(b[:])) |
| 75 | if err := os.Mkdir(home, 0700); err != nil { |
| 76 | return provider.OpenCodePolicyInputs{}, nil, err |
| 77 | } |
| 78 | cleanup := func() { os.RemoveAll(home) } |
| 79 | readOnly := r.Action != "implement" |
| 80 | tools := provider.OpenCodeTools(r.Action, r.Equipo) |
| 81 | in := provider.OpenCodePolicyInputs{Binary: r.Binary, BinarySHA256: r.BinarySHA256, Tree: r.Tree, TreeSHA256: r.TreeSHA256, Bwrap: r.Bwrap, ToolProxy: r.ToolProxy, |
| 82 | Home: home, Workspace: r.Workspace, Action: r.Action, Provider: r.Provider, Model: r.Model, KeyEnv: provider.OpenCodeKeyEnvs[r.Provider], Tools: tools, Resume: r.Resume, |
| 83 | EgressHosts: r.EgressHosts, Config: provider.OpenCodeConfig(r.Provider, r.Model, tools, readOnly), ExtraCA: r.ExtraCA} |
| 84 | if err := provider.WriteOpenCodeConfig(in); err != nil { |
| 85 | cleanup() |
| 86 | return provider.OpenCodePolicyInputs{}, nil, err |
| 87 | } |
| 88 | return in, cleanup, nil |
| 89 | } |
| 90 | |
| 91 | // ErrNoSession: the session's database is not where it should be. |
| 92 | var ErrNoSession = errors.New("opencode: no such session") |
| 93 | |
| 94 | // sessionFiles are OpenCode's database and its journal files, as its |
| 95 | // data directory holds them. |
| 96 | var sessionFiles = []string{"opencode.db", "opencode.db-wal", "opencode.db-shm"} |
| 97 | |
| 98 | // dataRel is OpenCode's data directory, relative to a runtime home. |
| 99 | const dataRel = ".local/share/opencode" |
| 100 | |
| 101 | // keptRel is where a keep directory holds session id's database, |
| 102 | // relative to it. |
| 103 | func keptRel(id string) (string, error) { |
| 104 | if !provider.OpenCodeSessionID(id) { |
| 105 | return "", ErrNoSession |
| 106 | } |
| 107 | return "opencode/" + id, nil |
| 108 | } |
| 109 | |
| 110 | // openFrom opens rel beneath root's descriptor: no link in any |
| 111 | // component of root's path or of rel (security round finding 1). |
| 112 | func openFrom(root, rel string) (*os.File, error) { |
| 113 | dir, err := provider.OpenDirectoryNoLinks(root) |
| 114 | if err != nil { |
| 115 | return nil, err |
| 116 | } |
| 117 | defer dir.Close() |
| 118 | return provider.OpenBeneath(dir, rel, syscall.O_RDONLY|syscall.O_NONBLOCK) |
| 119 | } |
| 120 | |
| 121 | // costFile records a kept session's reported cost so far, the baseline a |
| 122 | // resumed launch starts from (session/load says no cost). |
| 123 | const costFile = "cost" |
| 124 | |
| 125 | // KeepSession copies a run's session database from its runtime home into |
| 126 | // dir, for a question or a fix round to resume, with its reported cost so |
| 127 | // far, and returns its size. |
| 128 | // The home is the model's to write in, so every file is read beneath the |
| 129 | // home's own descriptor, with no link in any component, and must be a |
| 130 | // regular file. |
| 131 | func KeepSession(home, id, dir string, cost float64) (int64, error) { |
| 132 | rel, err := keptRel(id) |
| 133 | if err != nil { |
| 134 | return 0, err |
| 135 | } |
| 136 | to := filepath.Join(dir, filepath.FromSlash(rel)) |
| 137 | if err := os.MkdirAll(filepath.Dir(to), 0700); err != nil { |
| 138 | return 0, err |
| 139 | } |
| 140 | staged := to + ".tmp" |
| 141 | os.RemoveAll(staged) |
| 142 | if err := os.Mkdir(staged, 0700); err != nil { |
| 143 | return 0, err |
| 144 | } |
| 145 | var total int64 |
| 146 | for i, name := range sessionFiles { |
| 147 | in, err := openFrom(home, dataRel+"/"+name) |
| 148 | if errors.Is(err, os.ErrNotExist) && i > 0 { |
| 149 | continue |
| 150 | } |
| 151 | if err != nil { |
| 152 | os.RemoveAll(staged) |
| 153 | return 0, ErrNoSession |
| 154 | } |
| 155 | n, err := copyFrom(in, filepath.Join(staged, name)) |
| 156 | in.Close() |
| 157 | if err != nil { |
| 158 | os.RemoveAll(staged) |
| 159 | return 0, ErrNoSession |
| 160 | } |
| 161 | total += n |
| 162 | } |
| 163 | if err := os.WriteFile(filepath.Join(staged, costFile), []byte(strconv.FormatFloat(cost, 'f', -1, 64)), 0600); err != nil { |
| 164 | os.RemoveAll(staged) |
| 165 | return 0, err |
| 166 | } |
| 167 | os.RemoveAll(to) |
| 168 | if err := os.Rename(staged, to); err != nil { |
| 169 | os.RemoveAll(staged) |
| 170 | return 0, err |
| 171 | } |
| 172 | return total, nil |
| 173 | } |
| 174 | |
| 175 | // RestoreSession puts a kept session database into a fresh runtime home |
| 176 | // and returns the session's reported cost when it was kept (0 when none |
| 177 | // was recorded: the whole cost then counts as the next turn's, never |
| 178 | // less). |
| 179 | func RestoreSession(dir, id, home string) (float64, error) { |
| 180 | rel, err := keptRel(id) |
| 181 | if err != nil { |
| 182 | return 0, err |
| 183 | } |
| 184 | data := filepath.Join(home, filepath.FromSlash(dataRel)) |
| 185 | if err := os.MkdirAll(data, 0700); err != nil { |
| 186 | return 0, err |
| 187 | } |
| 188 | for i, name := range sessionFiles { |
| 189 | in, err := openFrom(dir, rel+"/"+name) |
| 190 | if errors.Is(err, os.ErrNotExist) && i > 0 { |
| 191 | continue |
| 192 | } |
| 193 | if err != nil { |
| 194 | return 0, ErrNoSession |
| 195 | } |
| 196 | _, err = copyFrom(in, filepath.Join(data, name)) |
| 197 | in.Close() |
| 198 | if err != nil { |
| 199 | return 0, ErrNoSession |
| 200 | } |
| 201 | } |
| 202 | base := 0.0 |
| 203 | if f, err := openFrom(dir, rel+"/"+costFile); err == nil { |
| 204 | raw, _ := io.ReadAll(io.LimitReader(f, 64)) |
| 205 | f.Close() |
| 206 | if v, err := strconv.ParseFloat(strings.TrimSpace(string(raw)), 64); err == nil && v >= 0 && !math.IsInf(v, 0) && !math.IsNaN(v) { |
| 207 | base = v |
| 208 | } |
| 209 | } |
| 210 | return base, nil |
| 211 | } |
| 212 | |
| 213 | // HasSession reports whether dir keeps session id. |
| 214 | func HasSession(dir, id string) bool { |
| 215 | rel, err := keptRel(id) |
| 216 | if err != nil { |
| 217 | return false |
| 218 | } |
| 219 | f, err := openFrom(dir, rel+"/"+sessionFiles[0]) |
| 220 | if err != nil { |
| 221 | return false |
| 222 | } |
| 223 | defer f.Close() |
| 224 | info, err := f.Stat() |
| 225 | return err == nil && info.Mode().IsRegular() |
| 226 | } |
| 227 | |
| 228 | // copyFrom copies an open regular file to a new file. |
| 229 | func copyFrom(in *os.File, to string) (int64, error) { |
| 230 | info, err := in.Stat() |
| 231 | if err != nil || !info.Mode().IsRegular() { |
| 232 | return 0, ErrNoSession |
| 233 | } |
| 234 | out, err := os.OpenFile(to, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) |
| 235 | if err != nil { |
| 236 | return 0, err |
| 237 | } |
| 238 | n, err := io.Copy(out, in) |
| 239 | if err == nil { |
| 240 | err = out.Sync() |
| 241 | } |
| 242 | if cerr := out.Close(); err == nil { |
| 243 | err = cerr |
| 244 | } |
| 245 | if err != nil { |
| 246 | os.Remove(to) |
| 247 | } |
| 248 | return n, err |
| 249 | } |
| 250 | |