package provider import ( "bytes" "crypto/sha256" "encoding/hex" "encoding/json" "io" "os" "path/filepath" "reflect" "slices" "sort" "strings" "golang.org/x/sys/unix" ) // The OpenCode harness's effective policy (connectors spec §3 and §4.2, // slice S5), built and attested like Pi's: no account lease, every input // exact. OpenCode v2 runs as `opencode acp`, its Agent Client Protocol // mode over stdio (probe OC-P2 found it, so the in-namespace bridge of // §4.2 is not built): the runner already owns the namespace's stdio. // OpenCode loads only the configuration the runner wrote into the // attempt's runtime home, hashed here: project configuration, Claude // Code compatibility, the model catalogue fetch, update checks and the // free models are off by environment, and the configuration turns off // every model call that is not the step's own (title, summary, automatic // compaction), names the one provider and model, Equipo's MCP server, // and the role's permissions. The key is not in it: it reaches the // namespace as KeyEnv through the secret pipe. const opencodePolicyVersion = "opencode-v1" // Paths inside an OpenCode namespace. The runtime home is /home/runner: // OpenCode's configuration, data (its session database) and state are // under it, by the XDG variables the policy sets. const ( OpenCodeBinary = "/opt/opencode" OpenCodeConfigDir = "/home/runner/.config" OpenCodeDataDir = "/home/runner/.local/share" OpenCodeStateDir = "/home/runner/.local/state" OpenCodeCacheDir = "/home/runner/.cache" // OpenCodeProviderID is the provider's id in OpenCode's // configuration: Equipo's own, never a built-in catalogue provider's // (OpenCode's catalogue has an "opencode-go" of its own). OpenCodeProviderID = "equipo" // OpenCodeProviderPackage is the provider implementation OpenCode // uses: bundled in the pinned binary (probe OC-P1 saw no package // fetch), so no npm package is installed for it. OpenCodeProviderPackage = "@opencode/ai/providers/openai-compatible" ) // OpenCodeKeyEnvs are the variables an OpenCode launch may receive its // key in, one per provider behind OpenCode. var OpenCodeKeyEnvs = map[string]string{"opencode-go": "OPENCODE_GO_API_KEY"} // OpenCodeBaseURLs are the OpenAI-compatible base URLs of the providers // behind OpenCode (the provider table's upstream and API path). var OpenCodeBaseURLs = map[string]string{"opencode-go": "https://opencode.ai/inference/go/openai/v1"} // openCodeEnv are the switches every OpenCode launch sets (§3: update // checks, telemetry and catalogue fetches off by configuration): the // configuration only from the runtime home, no project configuration, // no Claude Code compatibility (CLAUDE.md, .claude skills), no models.dev // catalogue fetch, no update check, no free models (the built-in // opencode provider), and no file watcher. var openCodeEnv = map[string]string{ "XDG_CONFIG_HOME": OpenCodeConfigDir, "XDG_DATA_HOME": OpenCodeDataDir, "XDG_STATE_HOME": OpenCodeStateDir, "XDG_CACHE_HOME": OpenCodeCacheDir, "OPENCODE_DISABLE_PROJECT_CONFIG": "1", "OPENCODE_DISABLE_CLAUDE_CODE": "1", "OPENCODE_DISABLE_MODELS_FETCH": "1", "OPENCODE_DISABLE_AUTOUPDATE": "1", "OPENCODE_DISABLE_FREE_MODELS": "1", "OPENCODE_DISABLE_FILEWATCHER": "1", } // OpenCodeEnvSwitches are the variables and values openCodeEnv sets, for // the containment's own check of an OpenCode launch's environment. func OpenCodeEnvSwitches() map[string]string { out := make(map[string]string, len(openCodeEnv)) for k, v := range openCodeEnv { out[k] = v } return out } // OpenCode's permission actions (its v2 permissions list). var ( openCodeReadTools = []string{"read", "glob", "grep"} openCodeWriteTools = []string{"edit", "shell"} // openCodeDenied are the actions no Equipo role allows: they end every // list, after the role's allows, so the last match for them is deny. openCodeDenied = []string{"subagent", "skill", "question", "webfetch", "websearch", "execute", "external_directory", "experimental_image_generate"} ) // OpenCodeTools are the tools a role pins: Review and a question read // only (read, glob, grep); Engineering also edits and runs commands // inside the namespace; then the step's own Equipo tools, each named as // OpenCode names an MCP tool (equipo_). func OpenCodeTools(action string, equipo []string) []string { tools := slices.Clone(openCodeReadTools) if action == "implement" { tools = append(tools, openCodeWriteTools...) } for _, name := range equipo { tools = append(tools, "equipo_"+name) } return tools } type openCodeRule struct { Action string `json:"action"` Resource string `json:"resource"` Effect string `json:"effect"` } // openCodePermissions is the role's permissions list. OpenCode applies // the last matching rule, and asks when none matches, so the list starts // with a deny of everything (nothing is ever asked or allowed unless // named), then allows the role's tools, then denies, last, what no role // may do, and for a read-only role edit and shell explicitly. func openCodePermissions(tools []string, readOnly bool) []openCodeRule { rules := []openCodeRule{{"*", "*", "deny"}} for _, t := range tools { rules = append(rules, openCodeRule{t, "*", "allow"}) } denied := slices.Clone(openCodeDenied) if readOnly { denied = append(denied, openCodeWriteTools...) } for _, a := range denied { rules = append(rules, openCodeRule{a, "*", "deny"}) } return rules } // OpenCodeConfig is opencode.json for one launch: updates and sharing // off, the one // provider (Equipo's id, the bundled OpenAI-compatible package, the base // URL from the provider table, the key by its variable, never the key) // and its one model, the title and summary agents off and automatic // compaction off (each would be a model call whose usage OpenCode does // not report in the turn's), Equipo's MCP server through the tool proxy // on the attempt's socket, and the role's permissions. func OpenCodeConfig(provider, model string, tools []string, readOnly bool) json.RawMessage { raw, _ := json.Marshal(map[string]any{ "update": "disable", // Sessions are never shared (2.2.7's share setting; its sharing // service is gone, the setting is pinned regardless). "share": "disabled", "model": OpenCodeProviderID + "/" + model, "agents": map[string]any{"title": map[string]bool{"disabled": true}, "summary": map[string]bool{"disabled": true}}, "compaction": map[string]bool{"auto": false}, "providers": map[string]any{OpenCodeProviderID: map[string]any{ "name": provider, "package": OpenCodeProviderPackage, "env": []string{OpenCodeKeyEnvs[provider]}, "settings": map[string]string{"baseURL": OpenCodeBaseURLs[provider]}, "models": map[string]any{model: map[string]string{"name": model}}, }}, "mcp": map[string]any{"equipo": map[string]any{"type": "local", "command": []string{"/opt/equipo-tool-proxy", "--socket", "/tool/equipo.sock"}}}, "permissions": openCodePermissions(tools, readOnly), }) return raw } // OpenCodeModel is the model reference OpenCode reports for a launch's // model (its session's model option). func OpenCodeModel(model string) string { return OpenCodeProviderID + "/" + model } // OpenCodePolicyInputs are one OpenCode launch's inputs. Binary, Tree, // Bwrap and ToolProxy are host paths (Binary inside Tree); Home is the // attempt's runtime home (under the scratch root's homes), whose config // directory holds Config as WriteOpenCodeConfig wrote it. type OpenCodePolicyInputs struct { Binary, BinarySHA256, Tree, TreeSHA256 string Bwrap, ToolProxy string Home, Workspace, Action string Provider, Model, KeyEnv string Tools, EgressHosts []string Resume string Config json.RawMessage // ExtraCA is a test build's certificate authority for its fake // provider (TestCAAllowed); a release build refuses one. ExtraCA string } // OpenCodeArgv is OpenCode's exact argv inside the namespace: its Agent // Client Protocol mode on stdio. func OpenCodeArgv() []string { return []string{OpenCodeBinary, "acp"} } func openCodeEnvFor(in OpenCodePolicyInputs) map[string]string { env := OpenCodeEnvSwitches() env["LANG"] = "C.UTF-8" if in.ExtraCA != "" { env["NODE_EXTRA_CA_CERTS"] = piTestCA } return env } // openCodeConfigDir is where opencode.json is in the runtime home. func openCodeConfigDir(home string) string { return filepath.Join(home, ".config", "opencode") } // WriteOpenCodeConfig writes opencode.json into the runtime home, 0600, // with the data, state and cache directories OpenCode uses, as the // policy will hash it. func WriteOpenCodeConfig(in OpenCodePolicyInputs) error { for _, d := range []string{".config", ".config/opencode", ".local", ".local/share", ".local/state", ".cache"} { if err := os.Mkdir(filepath.Join(in.Home, d), 0700); err != nil && !os.IsExist(err) { return err } } dir, err := pinDirectory(openCodeConfigDir(in.Home)) if err != nil { return err } defer dir.Close() c, err := canonical(in.Config) if err != nil { return err } return atomicPrivate(dir, "opencode.json", c) } // readOpenCodeConfig reads opencode.json back from the home, and refuses // any other file in its configuration directory (a second config file // there, opencode.jsonc, would be read too). func readOpenCodeConfig(home string) (json.RawMessage, error) { dir, err := pinDirectory(openCodeConfigDir(home)) if err != nil { return nil, ErrPolicy } defer dir.Close() names, err := dir.Readdirnames(-1) if err != nil || len(names) != 1 || names[0] != "opencode.json" { return nil, ErrPolicy } raw, err := readPrivate(dir, "opencode.json") if err != nil { return nil, ErrPolicy } return canonical(raw) } // validOpenCodeTools: names only, each once; OpenCode's own tools and // Equipo's MCP tools; no edit or shell in a read-only role. func validOpenCodeTools(tools []string, readOnly bool) bool { if len(tools) == 0 { return false } seen := map[string]bool{} for _, t := range tools { name, mcp := strings.CutPrefix(t, "equipo_") switch { case seen[t]: return false case mcp: if name == "" || strings.Trim(name, "abcdefghijklmnopqrstuvwxyz_") != "" { return false } case slices.Contains(openCodeReadTools, t): case slices.Contains(openCodeWriteTools, t): if readOnly { return false } default: return false } seen[t] = true } return true } // OpenDirectoryNoLinks opens a directory, refusing a symbolic link in // any component of its path. func OpenDirectoryNoLinks(path string) (*os.File, error) { return pinDirectory(path) } // sealedBinary reports whether a binary is as the seal left it: a // regular file root or this user owns, with one name, that nobody may // write (security round finding 2). func sealedBinary(info os.FileInfo) bool { return info.Mode().IsRegular() && ownedHere(info) && singleLink(info) && info.Mode().Perm()&0222 == 0 } // SealedBinarySHA256 is an OpenCode binary's digest, read through f (a // descriptor opened on it), once it is held to its seal: sealed, and // every directory above path safe (TreeRootSafe). func SealedBinarySHA256(f *os.File, path string) (string, error) { info, err := f.Stat() if err != nil || !sealedBinary(info) || TreeRootSafe(filepath.Dir(path)) != nil { return "", ErrTree } return ReaderSHA256(f) } // openCodeBinarySHA256 opens the binary without following links and // holds it to its seal and its digest. func openCodeBinarySHA256(path string) (string, error) { fd, err := openNoLinks(path, unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NONBLOCK) if err != nil { return "", ErrTree } f := os.NewFile(uintptr(fd), path) defer f.Close() return SealedBinarySHA256(f, path) } // FileSHA256 is a regular file's digest, read through one descriptor // opened without following links, streamed (OpenCode's binary is large). func FileSHA256(path string) (string, error) { fd, err := openNoLinks(path, unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NONBLOCK) if err != nil { return "", ErrPolicy } f := os.NewFile(uintptr(fd), path) defer f.Close() return ReaderSHA256(f) } // ReaderSHA256 is the digest of an open regular file, from its start. func ReaderSHA256(f *os.File) (string, error) { info, err := f.Stat() if err != nil || !info.Mode().IsRegular() { return "", ErrPolicy } h := sha256.New() if _, err := io.Copy(h, io.NewSectionReader(f, 0, info.Size())); err != nil { return "", ErrPolicy } return hex.EncodeToString(h.Sum(nil)), nil } // openCodeSessionID is an id OpenCode gives a session (ses_ and base62), // never a path. func openCodeSessionID(id string) bool { rest, ok := strings.CutPrefix(id, "ses_") if !ok || len(rest) < 8 || len(rest) > 64 { return false } return strings.Trim(rest, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") == "" } // OpenCodeSessionID reports whether id is one OpenCode gives a session. func OpenCodeSessionID(id string) bool { return openCodeSessionID(id) } // BuildOpenCodePolicy checks an OpenCode launch's inputs and certifies // them. func BuildOpenCodePolicy(in OpenCodePolicyInputs) (Policy, error) { profile, err := Profile(in.Action) if err != nil || (in.Action != "implement" && in.Action != "inspect" && in.Action != "answer") { return Policy{}, ErrPolicy } readOnly := profile.ReadOnly if OpenCodeKeyEnvs[in.Provider] == "" || OpenCodeBaseURLs[in.Provider] == "" || in.KeyEnv != OpenCodeKeyEnvs[in.Provider] || in.Model == "" || strings.ContainsAny(in.Model, " \t\n,/\"\\") || len(in.Model) > 200 || !validOpenCodeTools(in.Tools, readOnly) || len(in.EgressHosts) == 0 { return Policy{}, ErrPolicy } if in.Resume != "" && !openCodeSessionID(in.Resume) { return Policy{}, ErrPolicy } if in.ExtraCA != "" && !TestCAAllowed() { return Policy{}, ErrPolicy } for _, path := range []string{in.Home, in.Workspace} { f, err := pinDirectory(path) if err != nil { return Policy{}, ErrPolicy } f.Close() } if withinPath(in.Workspace, in.Home) || withinPath(in.Home, in.Workspace) { return Policy{}, ErrPolicy } // Exactly Equipo's configuration, rebuilt here from the provider, // model, tools and role: no other key, provider, model, MCP server, // command, plugin, instruction, agent or permission. config, err := readOpenCodeConfig(in.Home) if err != nil { return Policy{}, err } given, err := canonical(in.Config) if err != nil || !bytes.Equal(config, given) { return Policy{}, ErrPolicy } want, err := canonical(OpenCodeConfig(in.Provider, in.Model, in.Tools, readOnly)) if err != nil || !bytes.Equal(config, want) { return Policy{}, ErrPolicy } // The binary is the pinned one, inside the pinned tree. if !withinPath(in.Binary, in.Tree) || in.Binary == in.Tree { return Policy{}, ErrPolicy } if err := TreeRootSafe(in.Tree); err != nil { return Policy{}, err } tree, err := TreeSHA256(in.Tree) if err != nil || tree != in.TreeSHA256 { return Policy{}, ErrTree } binary, err := openCodeBinarySHA256(in.Binary) if err != nil || binary != in.BinarySHA256 { return Policy{}, ErrTree } m := effectiveManifest{Version: opencodePolicyVersion, Action: in.Action, Provider: in.Provider, Harness: "opencode", KeyEnv: in.KeyEnv, Argv: OpenCodeArgv(), Env: openCodeEnvFor(in), NamespaceArgs: NamespaceArguments(), Workspace: in.Workspace, RuntimeHome: in.Home, Tools: slices.Clone(in.Tools), Settings: config, Catalog: json.RawMessage(`"` + in.Model + `"`)} if in.Resume != "" { m.Catalog = json.RawMessage(`"` + in.Model + `|` + in.Resume + `"`) } m.EgressHosts = slices.Clone(in.EgressHosts) sort.Strings(m.EgressHosts) m.OuterMounts = []Mount{{Source: in.Binary, Target: OpenCodeBinary, ReadOnly: true}, {Source: in.ToolProxy, Target: "/opt/equipo-tool-proxy", ReadOnly: true}} if in.ExtraCA != "" { m.OuterMounts = append(m.OuterMounts, Mount{Source: in.ExtraCA, Target: piTestCA, ReadOnly: true}) } m.Files = []fileDigest{{Mount: m.OuterMounts[0], SHA256: binary}} for _, mount := range m.OuterMounts[1:] { f, err := piFile(mount) if err != nil { return Policy{}, err } m.Files = append(m.Files, f) } bwrap, err := piFile(Mount{Source: in.Bwrap, Target: "/opt/bwrap", ReadOnly: true}) if err != nil { return Policy{}, err } m.Files = append(m.Files, bwrap) m.Trees = []treePin{{Mount: Mount{Source: in.Tree, ReadOnly: true}, SHA256: tree}} raw, hash, err := hashJSON(m) if err != nil { return Policy{}, err } return Policy{Hash: hash, ManifestHash: hash, Manifest: raw, Mounts: m.OuterMounts, Env: m.Env, Settings: config}, nil } func openCodeManifest(p Policy) (effectiveManifest, bool) { var m effectiveManifest return m, p.ManifestHash != "" && digest(p.Manifest) == p.ManifestHash && json.Unmarshal(p.Manifest, &m) == nil && m.Version == opencodePolicyVersion } // IsOpenCode says the policy is an OpenCode launch's (BuildOpenCodePolicy). func (p Policy) IsOpenCode() bool { _, ok := openCodeManifest(p); return ok } // harnessManifest is a Pi or OpenCode policy's manifest. func harnessManifest(p Policy) (effectiveManifest, bool) { if m, ok := piManifest(p); ok { return m, true } return openCodeManifest(p) } // OpenCodeSelection is an OpenCode policy's model, and the session it // resumes ("" for a new one). func (p Policy) OpenCodeSelection() (model, resume string, ok bool) { m, ok := openCodeManifest(p) if !ok { return "", "", false } var s string if json.Unmarshal(m.Catalog, &s) != nil { return "", "", false } model, resume, _ = strings.Cut(s, "|") return model, resume, true } // OpenCodeBinaryPin is an OpenCode policy's binary: its host source and // pinned digest. The containment hashes it again through the descriptor // it mounts, so what the namespace runs is what was pinned. func (p Policy) OpenCodeBinaryPin() (source, sha string, ok bool) { m, ok := openCodeManifest(p) if !ok || len(m.Files) == 0 || m.Files[0].Mount.Target != OpenCodeBinary { return "", "", false } return m.Files[0].Mount.Source, m.Files[0].SHA256, true } // attestOpenCode holds a launch to its OpenCode policy, checked again // from disk: the argv, environment and mounts it certified, the pinned // files unchanged (the binary streamed), the config as // hashed, the selection's provider and model, the session it resumes, the // workspace, the runtime home, and a tool socket for its Equipo tools. func attestOpenCode(l Launch, argv []string) (string, error) { p := l.Policy m, ok := openCodeManifest(p) if !ok || p.Hash != p.ManifestHash || l.AttemptKey == "" || l.ToolSocket == "" || l.Workspace != m.Workspace || l.Binding.Home != m.RuntimeHome || l.Binding.Provider != "" || !l.Binding.Token || l.Binding.DedicatedHome { return "", ErrPolicy } model, resume, ok := p.OpenCodeSelection() if !ok || l.Selection.Provider != m.Provider || l.Selection.Model == "" || l.Selection.Model != model || l.ResumeSessionID != resume || !reflect.DeepEqual(argv, m.Argv) || !reflect.DeepEqual(argv, OpenCodeArgv()) || !reflect.DeepEqual(p.Env, m.Env) || !reflect.DeepEqual(p.Mounts, m.OuterMounts) || !reflect.DeepEqual(m.NamespaceArgs, NamespaceArguments()) { return "", ErrPolicy } for i, f := range m.Files { if i == 0 { sum, err := openCodeBinarySHA256(f.Mount.Source) if err != nil || sum != f.SHA256 { return "", ErrTree } continue } current, err := piFile(f.Mount) if err != nil || current.SHA256 != f.SHA256 { return "", ErrPolicy } } // The tree was held to its pin when the policy was built; only the // binary in it is mounted, and it is hashed again here and once more // through the descriptor the containment mounts. config, err := readOpenCodeConfig(m.RuntimeHome) if err != nil || !bytes.Equal(config, m.Settings) || !bytes.Equal(config, p.Settings) { return "", ErrPolicy } _, hash, err := hashJSON(struct{ Manifest, Attempt string }{p.ManifestHash, l.AttemptKey}) return hash, err } // OpenCodeArgv is an OpenCode policy's certified argv (nil for any other // policy). func (p Policy) OpenCodeArgv() []string { m, ok := openCodeManifest(p) if !ok { return nil } return slices.Clone(m.Argv) } // OpenCodeBinding is the binding of an OpenCode launch: the connection, // its prepared runtime home and the home holding its key (never // mounted). func OpenCodeBinding(local, home, keyHome string) Binding { return Binding{ID: local, Home: home, CredentialHome: keyHome, Token: true} }