package opencode import ( "crypto/rand" "encoding/hex" "errors" "io" "math" "os" "path/filepath" "runtime" "strconv" "strings" "syscall" "amadan.net/oficina/equipo/internal/runner/provider" ) // Install is where a runner's OpenCode is: the installed tree and the // binary in it, with the digests a launch requires (this platform's // pins; a test passes its fake's). type Install struct { Tree, Binary, TreeSHA256, BinarySHA256 string } // Pinned fills the digests from this platform's pins. func (i Install) Pinned() (Install, bool) { tree, platform, ok := Pins(runtime.GOARCH) if !ok { return i, false } if i.TreeSHA256 == "" { i.TreeSHA256 = tree } if i.BinarySHA256 == "" { i.BinarySHA256 = platform.BinarySHA256 } return i, i.Tree != "" && i.Binary != "" } // At is the install under root (EQUIPO_OPENCODE_ROOT) for this platform. func At(root string) (Install, bool) { _, platform, ok := Pins(runtime.GOARCH) if !ok || root == "" { return Install{}, false } tree, binary := Paths(root, platform.Package) return Install{Tree: tree, Binary: binary}, true } // Run is one OpenCode launch's inputs, before the policy is built. type Run struct { Install Bwrap, ToolProxy string Workspace, Action string Provider, Model string Equipo []string Resume string EgressHosts []string ExtraCA string } // Prepare makes the attempt's runtime home (under scratchRoot/homes, // 0700: the containment mounts only a home there), writes OpenCode's // configuration into it, and returns the policy inputs. Cleanup removes // the home. func Prepare(scratchRoot string, r Run) (provider.OpenCodePolicyInputs, func(), error) { homes := filepath.Join(scratchRoot, "homes") if err := os.MkdirAll(homes, 0700); err != nil { return provider.OpenCodePolicyInputs{}, nil, err } var b [6]byte rand.Read(b[:]) home := filepath.Join(homes, "opencode-"+hex.EncodeToString(b[:])) if err := os.Mkdir(home, 0700); err != nil { return provider.OpenCodePolicyInputs{}, nil, err } cleanup := func() { os.RemoveAll(home) } readOnly := r.Action != "implement" tools := provider.OpenCodeTools(r.Action, r.Equipo) in := provider.OpenCodePolicyInputs{Binary: r.Binary, BinarySHA256: r.BinarySHA256, Tree: r.Tree, TreeSHA256: r.TreeSHA256, Bwrap: r.Bwrap, ToolProxy: r.ToolProxy, Home: home, Workspace: r.Workspace, Action: r.Action, Provider: r.Provider, Model: r.Model, KeyEnv: provider.OpenCodeKeyEnvs[r.Provider], Tools: tools, Resume: r.Resume, EgressHosts: r.EgressHosts, Config: provider.OpenCodeConfig(r.Provider, r.Model, tools, readOnly), ExtraCA: r.ExtraCA} if err := provider.WriteOpenCodeConfig(in); err != nil { cleanup() return provider.OpenCodePolicyInputs{}, nil, err } return in, cleanup, nil } // ErrNoSession: the session's database is not where it should be. var ErrNoSession = errors.New("opencode: no such session") // sessionFiles are OpenCode's database and its journal files, as its // data directory holds them. var sessionFiles = []string{"opencode.db", "opencode.db-wal", "opencode.db-shm"} // dataRel is OpenCode's data directory, relative to a runtime home. const dataRel = ".local/share/opencode" // keptRel is where a keep directory holds session id's database, // relative to it. func keptRel(id string) (string, error) { if !provider.OpenCodeSessionID(id) { return "", ErrNoSession } return "opencode/" + id, nil } // openFrom opens rel beneath root's descriptor: no link in any // component of root's path or of rel (security round finding 1). func openFrom(root, rel string) (*os.File, error) { dir, err := provider.OpenDirectoryNoLinks(root) if err != nil { return nil, err } defer dir.Close() return provider.OpenBeneath(dir, rel, syscall.O_RDONLY|syscall.O_NONBLOCK) } // costFile records a kept session's reported cost so far, the baseline a // resumed launch starts from (session/load says no cost). const costFile = "cost" // KeepSession copies a run's session database from its runtime home into // dir, for a question or a fix round to resume, with its reported cost so // far, and returns its size. // The home is the model's to write in, so every file is read beneath the // home's own descriptor, with no link in any component, and must be a // regular file. func KeepSession(home, id, dir string, cost float64) (int64, error) { rel, err := keptRel(id) if err != nil { return 0, err } to := filepath.Join(dir, filepath.FromSlash(rel)) if err := os.MkdirAll(filepath.Dir(to), 0700); err != nil { return 0, err } staged := to + ".tmp" os.RemoveAll(staged) if err := os.Mkdir(staged, 0700); err != nil { return 0, err } var total int64 for i, name := range sessionFiles { in, err := openFrom(home, dataRel+"/"+name) if errors.Is(err, os.ErrNotExist) && i > 0 { continue } if err != nil { os.RemoveAll(staged) return 0, ErrNoSession } n, err := copyFrom(in, filepath.Join(staged, name)) in.Close() if err != nil { os.RemoveAll(staged) return 0, ErrNoSession } total += n } if err := os.WriteFile(filepath.Join(staged, costFile), []byte(strconv.FormatFloat(cost, 'f', -1, 64)), 0600); err != nil { os.RemoveAll(staged) return 0, err } os.RemoveAll(to) if err := os.Rename(staged, to); err != nil { os.RemoveAll(staged) return 0, err } return total, nil } // RestoreSession puts a kept session database into a fresh runtime home // and returns the session's reported cost when it was kept (0 when none // was recorded: the whole cost then counts as the next turn's, never // less). func RestoreSession(dir, id, home string) (float64, error) { rel, err := keptRel(id) if err != nil { return 0, err } data := filepath.Join(home, filepath.FromSlash(dataRel)) if err := os.MkdirAll(data, 0700); err != nil { return 0, err } for i, name := range sessionFiles { in, err := openFrom(dir, rel+"/"+name) if errors.Is(err, os.ErrNotExist) && i > 0 { continue } if err != nil { return 0, ErrNoSession } _, err = copyFrom(in, filepath.Join(data, name)) in.Close() if err != nil { return 0, ErrNoSession } } base := 0.0 if f, err := openFrom(dir, rel+"/"+costFile); err == nil { raw, _ := io.ReadAll(io.LimitReader(f, 64)) f.Close() if v, err := strconv.ParseFloat(strings.TrimSpace(string(raw)), 64); err == nil && v >= 0 && !math.IsInf(v, 0) && !math.IsNaN(v) { base = v } } return base, nil } // HasSession reports whether dir keeps session id. func HasSession(dir, id string) bool { rel, err := keptRel(id) if err != nil { return false } f, err := openFrom(dir, rel+"/"+sessionFiles[0]) if err != nil { return false } defer f.Close() info, err := f.Stat() return err == nil && info.Mode().IsRegular() } // copyFrom copies an open regular file to a new file. func copyFrom(in *os.File, to string) (int64, error) { info, err := in.Stat() if err != nil || !info.Mode().IsRegular() { return 0, ErrNoSession } out, err := os.OpenFile(to, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) if err != nil { return 0, err } n, err := io.Copy(out, in) if err == nil { err = out.Sync() } if cerr := out.Close(); err == nil { err = cerr } if err != nil { os.Remove(to) } return n, err }