oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package provider
2
3import (
4 "bytes"
5 "crypto/sha256"
6 "encoding/hex"
7 "encoding/json"
8 "io"
9 "os"
10 "path/filepath"
11 "reflect"
12 "slices"
13 "sort"
14 "strings"
15
16 "golang.org/x/sys/unix"
17)
18
19// The OpenCode harness's effective policy (connectors spec §3 and §4.2,
20// slice S5), built and attested like Pi's: no account lease, every input
21// exact. OpenCode v2 runs as `opencode acp`, its Agent Client Protocol
22// mode over stdio (probe OC-P2 found it, so the in-namespace bridge of
23// §4.2 is not built): the runner already owns the namespace's stdio.
24// OpenCode loads only the configuration the runner wrote into the
25// attempt's runtime home, hashed here: project configuration, Claude
26// Code compatibility, the model catalogue fetch, update checks and the
27// free models are off by environment, and the configuration turns off
28// every model call that is not the step's own (title, summary, automatic
29// compaction), names the one provider and model, Equipo's MCP server,
30// and the role's permissions. The key is not in it: it reaches the
31// namespace as KeyEnv through the secret pipe.
32
33const opencodePolicyVersion = "opencode-v1"
34
35// Paths inside an OpenCode namespace. The runtime home is /home/runner:
36// OpenCode's configuration, data (its session database) and state are
37// under it, by the XDG variables the policy sets.
38const (
39 OpenCodeBinary = "/opt/opencode"
40 OpenCodeConfigDir = "/home/runner/.config"
41 OpenCodeDataDir = "/home/runner/.local/share"
42 OpenCodeStateDir = "/home/runner/.local/state"
43 OpenCodeCacheDir = "/home/runner/.cache"
44 // OpenCodeProviderID is the provider's id in OpenCode's
45 // configuration: Equipo's own, never a built-in catalogue provider's
46 // (OpenCode's catalogue has an "opencode-go" of its own).
47 OpenCodeProviderID = "equipo"
48 // OpenCodeProviderPackage is the provider implementation OpenCode
49 // uses: bundled in the pinned binary (probe OC-P1 saw no package
50 // fetch), so no npm package is installed for it.
51 OpenCodeProviderPackage = "@opencode/ai/providers/openai-compatible"
52)
53
54// OpenCodeKeyEnvs are the variables an OpenCode launch may receive its
55// key in, one per provider behind OpenCode.
56var OpenCodeKeyEnvs = map[string]string{"opencode-go": "OPENCODE_GO_API_KEY"}
57
58// OpenCodeBaseURLs are the OpenAI-compatible base URLs of the providers
59// behind OpenCode (the provider table's upstream and API path).
60var OpenCodeBaseURLs = map[string]string{"opencode-go": "https://opencode.ai/inference/go/openai/v1"}
61
62// openCodeEnv are the switches every OpenCode launch sets (§3: update
63// checks, telemetry and catalogue fetches off by configuration): the
64// configuration only from the runtime home, no project configuration,
65// no Claude Code compatibility (CLAUDE.md, .claude skills), no models.dev
66// catalogue fetch, no update check, no free models (the built-in
67// opencode provider), and no file watcher.
68var openCodeEnv = map[string]string{
69 "XDG_CONFIG_HOME": OpenCodeConfigDir,
70 "XDG_DATA_HOME": OpenCodeDataDir,
71 "XDG_STATE_HOME": OpenCodeStateDir,
72 "XDG_CACHE_HOME": OpenCodeCacheDir,
73 "OPENCODE_DISABLE_PROJECT_CONFIG": "1",
74 "OPENCODE_DISABLE_CLAUDE_CODE": "1",
75 "OPENCODE_DISABLE_MODELS_FETCH": "1",
76 "OPENCODE_DISABLE_AUTOUPDATE": "1",
77 "OPENCODE_DISABLE_FREE_MODELS": "1",
78 "OPENCODE_DISABLE_FILEWATCHER": "1",
79}
80
81// OpenCodeEnvSwitches are the variables and values openCodeEnv sets, for
82// the containment's own check of an OpenCode launch's environment.
83func OpenCodeEnvSwitches() map[string]string {
84 out := make(map[string]string, len(openCodeEnv))
85 for k, v := range openCodeEnv {
86 out[k] = v
87 }
88 return out
89}
90
91// OpenCode's permission actions (its v2 permissions list).
92var (
93 openCodeReadTools = []string{"read", "glob", "grep"}
94 openCodeWriteTools = []string{"edit", "shell"}
95 // openCodeDenied are the actions no Equipo role allows: they end every
96 // list, after the role's allows, so the last match for them is deny.
97 openCodeDenied = []string{"subagent", "skill", "question", "webfetch", "websearch", "execute", "external_directory", "experimental_image_generate"}
98)
99
100// OpenCodeTools are the tools a role pins: Review and a question read
101// only (read, glob, grep); Engineering also edits and runs commands
102// inside the namespace; then the step's own Equipo tools, each named as
103// OpenCode names an MCP tool (equipo_<tool>).
104func OpenCodeTools(action string, equipo []string) []string {
105 tools := slices.Clone(openCodeReadTools)
106 if action == "implement" {
107 tools = append(tools, openCodeWriteTools...)
108 }
109 for _, name := range equipo {
110 tools = append(tools, "equipo_"+name)
111 }
112 return tools
113}
114
115type openCodeRule struct {
116 Action string `json:"action"`
117 Resource string `json:"resource"`
118 Effect string `json:"effect"`
119}
120
121// openCodePermissions is the role's permissions list. OpenCode applies
122// the last matching rule, and asks when none matches, so the list starts
123// with a deny of everything (nothing is ever asked or allowed unless
124// named), then allows the role's tools, then denies, last, what no role
125// may do, and for a read-only role edit and shell explicitly.
126func openCodePermissions(tools []string, readOnly bool) []openCodeRule {
127 rules := []openCodeRule{{"*", "*", "deny"}}
128 for _, t := range tools {
129 rules = append(rules, openCodeRule{t, "*", "allow"})
130 }
131 denied := slices.Clone(openCodeDenied)
132 if readOnly {
133 denied = append(denied, openCodeWriteTools...)
134 }
135 for _, a := range denied {
136 rules = append(rules, openCodeRule{a, "*", "deny"})
137 }
138 return rules
139}
140
141// OpenCodeConfig is opencode.json for one launch: updates and sharing
142// off, the one
143// provider (Equipo's id, the bundled OpenAI-compatible package, the base
144// URL from the provider table, the key by its variable, never the key)
145// and its one model, the title and summary agents off and automatic
146// compaction off (each would be a model call whose usage OpenCode does
147// not report in the turn's), Equipo's MCP server through the tool proxy
148// on the attempt's socket, and the role's permissions.
149func OpenCodeConfig(provider, model string, tools []string, readOnly bool) json.RawMessage {
150 raw, _ := json.Marshal(map[string]any{
151 "update": "disable",
152 // Sessions are never shared (2.2.7's share setting; its sharing
153 // service is gone, the setting is pinned regardless).
154 "share": "disabled",
155 "model": OpenCodeProviderID + "/" + model,
156 "agents": map[string]any{"title": map[string]bool{"disabled": true}, "summary": map[string]bool{"disabled": true}},
157 "compaction": map[string]bool{"auto": false},
158 "providers": map[string]any{OpenCodeProviderID: map[string]any{
159 "name": provider,
160 "package": OpenCodeProviderPackage,
161 "env": []string{OpenCodeKeyEnvs[provider]},
162 "settings": map[string]string{"baseURL": OpenCodeBaseURLs[provider]},
163 "models": map[string]any{model: map[string]string{"name": model}},
164 }},
165 "mcp": map[string]any{"equipo": map[string]any{"type": "local", "command": []string{"/opt/equipo-tool-proxy", "--socket", "/tool/equipo.sock"}}},
166 "permissions": openCodePermissions(tools, readOnly),
167 })
168 return raw
169}
170
171// OpenCodeModel is the model reference OpenCode reports for a launch's
172// model (its session's model option).
173func OpenCodeModel(model string) string { return OpenCodeProviderID + "/" + model }
174
175// OpenCodePolicyInputs are one OpenCode launch's inputs. Binary, Tree,
176// Bwrap and ToolProxy are host paths (Binary inside Tree); Home is the
177// attempt's runtime home (under the scratch root's homes), whose config
178// directory holds Config as WriteOpenCodeConfig wrote it.
179type OpenCodePolicyInputs struct {
180 Binary, BinarySHA256, Tree, TreeSHA256 string
181 Bwrap, ToolProxy string
182 Home, Workspace, Action string
183 Provider, Model, KeyEnv string
184 Tools, EgressHosts []string
185 Resume string
186 Config json.RawMessage
187 // ExtraCA is a test build's certificate authority for its fake
188 // provider (TestCAAllowed); a release build refuses one.
189 ExtraCA string
190}
191
192// OpenCodeArgv is OpenCode's exact argv inside the namespace: its Agent
193// Client Protocol mode on stdio.
194func OpenCodeArgv() []string { return []string{OpenCodeBinary, "acp"} }
195
196func openCodeEnvFor(in OpenCodePolicyInputs) map[string]string {
197 env := OpenCodeEnvSwitches()
198 env["LANG"] = "C.UTF-8"
199 if in.ExtraCA != "" {
200 env["NODE_EXTRA_CA_CERTS"] = piTestCA
201 }
202 return env
203}
204
205// openCodeConfigDir is where opencode.json is in the runtime home.
206func openCodeConfigDir(home string) string { return filepath.Join(home, ".config", "opencode") }
207
208// WriteOpenCodeConfig writes opencode.json into the runtime home, 0600,
209// with the data, state and cache directories OpenCode uses, as the
210// policy will hash it.
211func WriteOpenCodeConfig(in OpenCodePolicyInputs) error {
212 for _, d := range []string{".config", ".config/opencode", ".local", ".local/share", ".local/state", ".cache"} {
213 if err := os.Mkdir(filepath.Join(in.Home, d), 0700); err != nil && !os.IsExist(err) {
214 return err
215 }
216 }
217 dir, err := pinDirectory(openCodeConfigDir(in.Home))
218 if err != nil {
219 return err
220 }
221 defer dir.Close()
222 c, err := canonical(in.Config)
223 if err != nil {
224 return err
225 }
226 return atomicPrivate(dir, "opencode.json", c)
227}
228
229// readOpenCodeConfig reads opencode.json back from the home, and refuses
230// any other file in its configuration directory (a second config file
231// there, opencode.jsonc, would be read too).
232func readOpenCodeConfig(home string) (json.RawMessage, error) {
233 dir, err := pinDirectory(openCodeConfigDir(home))
234 if err != nil {
235 return nil, ErrPolicy
236 }
237 defer dir.Close()
238 names, err := dir.Readdirnames(-1)
239 if err != nil || len(names) != 1 || names[0] != "opencode.json" {
240 return nil, ErrPolicy
241 }
242 raw, err := readPrivate(dir, "opencode.json")
243 if err != nil {
244 return nil, ErrPolicy
245 }
246 return canonical(raw)
247}
248
249// validOpenCodeTools: names only, each once; OpenCode's own tools and
250// Equipo's MCP tools; no edit or shell in a read-only role.
251func validOpenCodeTools(tools []string, readOnly bool) bool {
252 if len(tools) == 0 {
253 return false
254 }
255 seen := map[string]bool{}
256 for _, t := range tools {
257 name, mcp := strings.CutPrefix(t, "equipo_")
258 switch {
259 case seen[t]:
260 return false
261 case mcp:
262 if name == "" || strings.Trim(name, "abcdefghijklmnopqrstuvwxyz_") != "" {
263 return false
264 }
265 case slices.Contains(openCodeReadTools, t):
266 case slices.Contains(openCodeWriteTools, t):
267 if readOnly {
268 return false
269 }
270 default:
271 return false
272 }
273 seen[t] = true
274 }
275 return true
276}
277
278// OpenDirectoryNoLinks opens a directory, refusing a symbolic link in
279// any component of its path.
280func OpenDirectoryNoLinks(path string) (*os.File, error) { return pinDirectory(path) }
281
282// sealedBinary reports whether a binary is as the seal left it: a
283// regular file root or this user owns, with one name, that nobody may
284// write (security round finding 2).
285func sealedBinary(info os.FileInfo) bool {
286 return info.Mode().IsRegular() && ownedHere(info) && singleLink(info) && info.Mode().Perm()&0222 == 0
287}
288
289// SealedBinarySHA256 is an OpenCode binary's digest, read through f (a
290// descriptor opened on it), once it is held to its seal: sealed, and
291// every directory above path safe (TreeRootSafe).
292func SealedBinarySHA256(f *os.File, path string) (string, error) {
293 info, err := f.Stat()
294 if err != nil || !sealedBinary(info) || TreeRootSafe(filepath.Dir(path)) != nil {
295 return "", ErrTree
296 }
297 return ReaderSHA256(f)
298}
299
300// openCodeBinarySHA256 opens the binary without following links and
301// holds it to its seal and its digest.
302func openCodeBinarySHA256(path string) (string, error) {
303 fd, err := openNoLinks(path, unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NONBLOCK)
304 if err != nil {
305 return "", ErrTree
306 }
307 f := os.NewFile(uintptr(fd), path)
308 defer f.Close()
309 return SealedBinarySHA256(f, path)
310}
311
312// FileSHA256 is a regular file's digest, read through one descriptor
313// opened without following links, streamed (OpenCode's binary is large).
314func FileSHA256(path string) (string, error) {
315 fd, err := openNoLinks(path, unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NONBLOCK)
316 if err != nil {
317 return "", ErrPolicy
318 }
319 f := os.NewFile(uintptr(fd), path)
320 defer f.Close()
321 return ReaderSHA256(f)
322}
323
324// ReaderSHA256 is the digest of an open regular file, from its start.
325func ReaderSHA256(f *os.File) (string, error) {
326 info, err := f.Stat()
327 if err != nil || !info.Mode().IsRegular() {
328 return "", ErrPolicy
329 }
330 h := sha256.New()
331 if _, err := io.Copy(h, io.NewSectionReader(f, 0, info.Size())); err != nil {
332 return "", ErrPolicy
333 }
334 return hex.EncodeToString(h.Sum(nil)), nil
335}
336
337// openCodeSessionID is an id OpenCode gives a session (ses_ and base62),
338// never a path.
339func openCodeSessionID(id string) bool {
340 rest, ok := strings.CutPrefix(id, "ses_")
341 if !ok || len(rest) < 8 || len(rest) > 64 {
342 return false
343 }
344 return strings.Trim(rest, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") == ""
345}
346
347// OpenCodeSessionID reports whether id is one OpenCode gives a session.
348func OpenCodeSessionID(id string) bool { return openCodeSessionID(id) }
349
350// BuildOpenCodePolicy checks an OpenCode launch's inputs and certifies
351// them.
352func BuildOpenCodePolicy(in OpenCodePolicyInputs) (Policy, error) {
353 profile, err := Profile(in.Action)
354 if err != nil || (in.Action != "implement" && in.Action != "inspect" && in.Action != "answer") {
355 return Policy{}, ErrPolicy
356 }
357 readOnly := profile.ReadOnly
358 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 {
359 return Policy{}, ErrPolicy
360 }
361 if in.Resume != "" && !openCodeSessionID(in.Resume) {
362 return Policy{}, ErrPolicy
363 }
364 if in.ExtraCA != "" && !TestCAAllowed() {
365 return Policy{}, ErrPolicy
366 }
367 for _, path := range []string{in.Home, in.Workspace} {
368 f, err := pinDirectory(path)
369 if err != nil {
370 return Policy{}, ErrPolicy
371 }
372 f.Close()
373 }
374 if withinPath(in.Workspace, in.Home) || withinPath(in.Home, in.Workspace) {
375 return Policy{}, ErrPolicy
376 }
377 // Exactly Equipo's configuration, rebuilt here from the provider,
378 // model, tools and role: no other key, provider, model, MCP server,
379 // command, plugin, instruction, agent or permission.
380 config, err := readOpenCodeConfig(in.Home)
381 if err != nil {
382 return Policy{}, err
383 }
384 given, err := canonical(in.Config)
385 if err != nil || !bytes.Equal(config, given) {
386 return Policy{}, ErrPolicy
387 }
388 want, err := canonical(OpenCodeConfig(in.Provider, in.Model, in.Tools, readOnly))
389 if err != nil || !bytes.Equal(config, want) {
390 return Policy{}, ErrPolicy
391 }
392 // The binary is the pinned one, inside the pinned tree.
393 if !withinPath(in.Binary, in.Tree) || in.Binary == in.Tree {
394 return Policy{}, ErrPolicy
395 }
396 if err := TreeRootSafe(in.Tree); err != nil {
397 return Policy{}, err
398 }
399 tree, err := TreeSHA256(in.Tree)
400 if err != nil || tree != in.TreeSHA256 {
401 return Policy{}, ErrTree
402 }
403 binary, err := openCodeBinarySHA256(in.Binary)
404 if err != nil || binary != in.BinarySHA256 {
405 return Policy{}, ErrTree
406 }
407 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 + `"`)}
408 if in.Resume != "" {
409 m.Catalog = json.RawMessage(`"` + in.Model + `|` + in.Resume + `"`)
410 }
411 m.EgressHosts = slices.Clone(in.EgressHosts)
412 sort.Strings(m.EgressHosts)
413 m.OuterMounts = []Mount{{Source: in.Binary, Target: OpenCodeBinary, ReadOnly: true}, {Source: in.ToolProxy, Target: "/opt/equipo-tool-proxy", ReadOnly: true}}
414 if in.ExtraCA != "" {
415 m.OuterMounts = append(m.OuterMounts, Mount{Source: in.ExtraCA, Target: piTestCA, ReadOnly: true})
416 }
417 m.Files = []fileDigest{{Mount: m.OuterMounts[0], SHA256: binary}}
418 for _, mount := range m.OuterMounts[1:] {
419 f, err := piFile(mount)
420 if err != nil {
421 return Policy{}, err
422 }
423 m.Files = append(m.Files, f)
424 }
425 bwrap, err := piFile(Mount{Source: in.Bwrap, Target: "/opt/bwrap", ReadOnly: true})
426 if err != nil {
427 return Policy{}, err
428 }
429 m.Files = append(m.Files, bwrap)
430 m.Trees = []treePin{{Mount: Mount{Source: in.Tree, ReadOnly: true}, SHA256: tree}}
431 raw, hash, err := hashJSON(m)
432 if err != nil {
433 return Policy{}, err
434 }
435 return Policy{Hash: hash, ManifestHash: hash, Manifest: raw, Mounts: m.OuterMounts, Env: m.Env, Settings: config}, nil
436}
437
438func openCodeManifest(p Policy) (effectiveManifest, bool) {
439 var m effectiveManifest
440 return m, p.ManifestHash != "" && digest(p.Manifest) == p.ManifestHash && json.Unmarshal(p.Manifest, &m) == nil && m.Version == opencodePolicyVersion
441}
442
443// IsOpenCode says the policy is an OpenCode launch's (BuildOpenCodePolicy).
444func (p Policy) IsOpenCode() bool { _, ok := openCodeManifest(p); return ok }
445
446// harnessManifest is a Pi or OpenCode policy's manifest.
447func harnessManifest(p Policy) (effectiveManifest, bool) {
448 if m, ok := piManifest(p); ok {
449 return m, true
450 }
451 return openCodeManifest(p)
452}
453
454// OpenCodeSelection is an OpenCode policy's model, and the session it
455// resumes ("" for a new one).
456func (p Policy) OpenCodeSelection() (model, resume string, ok bool) {
457 m, ok := openCodeManifest(p)
458 if !ok {
459 return "", "", false
460 }
461 var s string
462 if json.Unmarshal(m.Catalog, &s) != nil {
463 return "", "", false
464 }
465 model, resume, _ = strings.Cut(s, "|")
466 return model, resume, true
467}
468
469// OpenCodeBinaryPin is an OpenCode policy's binary: its host source and
470// pinned digest. The containment hashes it again through the descriptor
471// it mounts, so what the namespace runs is what was pinned.
472func (p Policy) OpenCodeBinaryPin() (source, sha string, ok bool) {
473 m, ok := openCodeManifest(p)
474 if !ok || len(m.Files) == 0 || m.Files[0].Mount.Target != OpenCodeBinary {
475 return "", "", false
476 }
477 return m.Files[0].Mount.Source, m.Files[0].SHA256, true
478}
479
480// attestOpenCode holds a launch to its OpenCode policy, checked again
481// from disk: the argv, environment and mounts it certified, the pinned
482// files unchanged (the binary streamed), the config as
483// hashed, the selection's provider and model, the session it resumes, the
484// workspace, the runtime home, and a tool socket for its Equipo tools.
485func attestOpenCode(l Launch, argv []string) (string, error) {
486 p := l.Policy
487 m, ok := openCodeManifest(p)
488 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 {
489 return "", ErrPolicy
490 }
491 model, resume, ok := p.OpenCodeSelection()
492 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()) {
493 return "", ErrPolicy
494 }
495 for i, f := range m.Files {
496 if i == 0 {
497 sum, err := openCodeBinarySHA256(f.Mount.Source)
498 if err != nil || sum != f.SHA256 {
499 return "", ErrTree
500 }
501 continue
502 }
503 current, err := piFile(f.Mount)
504 if err != nil || current.SHA256 != f.SHA256 {
505 return "", ErrPolicy
506 }
507 }
508 // The tree was held to its pin when the policy was built; only the
509 // binary in it is mounted, and it is hashed again here and once more
510 // through the descriptor the containment mounts.
511 config, err := readOpenCodeConfig(m.RuntimeHome)
512 if err != nil || !bytes.Equal(config, m.Settings) || !bytes.Equal(config, p.Settings) {
513 return "", ErrPolicy
514 }
515 _, hash, err := hashJSON(struct{ Manifest, Attempt string }{p.ManifestHash, l.AttemptKey})
516 return hash, err
517}
518
519// OpenCodeArgv is an OpenCode policy's certified argv (nil for any other
520// policy).
521func (p Policy) OpenCodeArgv() []string {
522 m, ok := openCodeManifest(p)
523 if !ok {
524 return nil
525 }
526 return slices.Clone(m.Argv)
527}
528
529// OpenCodeBinding is the binding of an OpenCode launch: the connection,
530// its prepared runtime home and the home holding its key (never
531// mounted).
532func OpenCodeBinding(local, home, keyHome string) Binding {
533 return Binding{ID: local, Home: home, CredentialHome: keyHome, Token: true}
534}
535