Files
skillshare/internal/plugin/package_config.go
T
Krishnaswamy SubramanianandWillie dabe06a297 feat(targets): support OpenCode config directory accounts (#594)
* feat(targets): support OpenCode config directory accounts

OpenCode v2 introduces support for custom configuration directories
via OPENCODE_CONFIG_DIR, storing opencode.json and agent directories.

Previously, skillshare rejected OpenCode accounts configured with a
custom config directory because OpenCode was missing config_dir and
was excluded from accountAgents in hooks and MCP services.

- Define default config_dir (~/.config/opencode) in targets.yaml
- Add OpenCode to account agents and register OPENCODE_CONFIG_DIR
  across hooks and MCP service handlers
- Route OpenCode account MCP configuration to opencode.json inside
  the account config directory

Resolves #593.

* fix(targets): add OpenCode to schemas, completions and docs

Add opencode to the targetConfig.agent enum and config_dir description
in schemas/config.schema.json so configurations containing OpenCode
account targets pass schema validation.

Include opencode in the target --agent completion scripts for Bash,
Zsh, Fish, PowerShell, and Nushell.

Update website documentation and built-in skill references to describe
OpenCode accounts and OPENCODE_CONFIG_DIR management alongside other
account agents.

* fix(targets): support plugin accounts and overlap

Add OpenCode account recognition and OPENCODE_CONFIG_DIR resolution to
the plugin service so plugin sync works for OpenCode account targets.

Introduce TargetScanPaths to resolve cross-runtime scan paths using
TargetConfig.Agent for account targets while retaining the account's
own primary directory. Update path overlap detection, doctor checks,
and LeakedSkills to warn about leaked skills for account targets.

Update localized docs (zh-Hans, zh-Hant, ja, ko) and plugin references
to document OpenCode account targets and OPENCODE_CONFIG_DIR. Update
the available targets handler test to expect OpenCode's configDir.

* fix(targets): isolate OpenCode accounts and scan paths

Reject OPENCODE_CONFIG overrides when operating on OpenCode accounts
and clear OPENCODE_CONFIG in the account execution environment so
plugin operations target the account directory.

In TargetScanPaths, remap config-root paths to the account directory
while preserving external scan paths like Codex's ~/.agents/skills.

* fix(plugins): use account target in OpenCode update probe

Pass c.Target instead of a hardcoded "opencode" when probing whether
OpenCode supports plugin updates, ensuring account-configured CLI
binaries and account environment variables are used during preview.

* test(mcp): isolate XDG_CONFIG_HOME in account test service

Isolate XDG_CONFIG_HOME to the temporary test directory in
agentAccountService to prevent runner environment variables from leaking
into TestAccountEnvOverrideDoesNotPruneDefaultHome when testing OpenCode
account shell overrides.

---------

Co-authored-by: Willie <egg358358@gmail.com>
2026-10-22 21:50:06 +08:00

374 lines
11 KiB
Go

package plugin
import (
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/gofrs/flock"
"github.com/tailscale/hujson"
)
func (s *Service) piSettingsPath(target string) (string, error) {
if s.ProjectRoot != "" {
return filepath.Join(s.ProjectRoot, ".pi", "settings.json"), nil
}
dir, err := s.piAgentDir(target)
if err != nil {
return "", err
}
return filepath.Join(dir, "settings.json"), nil
}
// piSettingsRoot is the folder above a piSettingsPath file that may be reached
// through links: the project, or the agent directory.
func (s *Service) piSettingsRoot(file string) string {
if s.ProjectRoot != "" {
return s.ProjectRoot
}
return filepath.Dir(file)
}
// piAgentDir is the agent directory of a global Pi target or account, whatever
// the project: a project's settings are read on top of the global ones.
func (s *Service) piAgentDir(target string) (string, error) {
// An account's packages live in the account's own directory, not in the one the
// environment points the CLI at.
dir := ""
if account, ok := s.account(target); ok {
dir = account.Dir
} else {
dir = os.Getenv("PI_CODING_AGENT_DIR")
}
if dir == "" {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
dir = filepath.Join(home, ".pi", "agent")
}
if !filepath.IsAbs(dir) {
return "", fmt.Errorf("PI_CODING_AGENT_DIR must be absolute")
}
return filepath.Clean(dir), nil
}
// Pi has no machine-readable list command. Read its documented settings without
// loading extensions; leave all writes to pi install/remove.
func (s *Service) piInventory(target string) ([]Installed, string, error) {
path, err := s.piSettingsPath(target)
if err != nil {
return nil, "", err
}
raw, _, entries, err := readPackageConfig(s.piSettingsRoot(path), path, "packages")
if err != nil {
return nil, "", err
}
result := []Installed{}
for _, entry := range entries {
var source string
filtered := json.Unmarshal(entry, &source) != nil
if filtered {
var object struct {
Source string `json:"source"`
}
if json.Unmarshal(entry, &object) != nil {
return nil, "", fmt.Errorf("invalid Pi package entry")
}
source = object.Source
}
if !strings.HasPrefix(source, "npm:") && !strings.HasPrefix(source, "git:") && !strings.Contains(source, "://") && !strings.HasPrefix(source, "git@") {
if strings.HasPrefix(source, "~/") {
home, e := os.UserHomeDir()
if e != nil {
return nil, "", e
}
source = filepath.Join(home, source[2:])
} else if !filepath.IsAbs(source) {
source = filepath.Join(filepath.Dir(path), source)
}
}
if !validTargetID("pi", source) {
return nil, "", fmt.Errorf("invalid Pi package source")
}
// Pi keeps installs beside its settings file; what is there says which version is installed.
scope, base := "user", filepath.Dir(path)
if s.ProjectRoot != "" {
scope = "project"
}
version := ""
if src := resolvePiSource(source, base, base, scope); src.kind != "unknown" {
version = piInstalledVersion(src.install)
}
result = append(result, Installed{ID: source, Name: logicalName(source), Version: version, Installed: true, Enabled: true, Filtered: filtered})
}
return result, hash(raw), nil
}
func logicalName(id string) string {
// An npm package name may contain dots; it names a package, not a file.
if isNpmSource(id) {
name, _ := npmSpec(id)
if name = name[strings.LastIndex(name, "/")+1:]; namePattern.MatchString(name) {
return name
}
return ""
}
name := strings.TrimPrefix(strings.TrimPrefix(id, "npm:"), "@")
name = strings.TrimSuffix(filepath.Base(name), filepath.Ext(name))
if i := strings.Index(name, "@"); i >= 0 {
name = name[:i]
}
if namePattern.MatchString(name) {
return name
}
return ""
}
func (s *Service) openCodeConfigPath(target ...string) (string, error) {
if os.Getenv("OPENCODE_CONFIG_CONTENT") != "" {
return "", fmt.Errorf("OpenCode inline overrides are not supported for plugin sync; use its standard config")
}
var dir string
if s.ProjectRoot != "" {
if os.Getenv("OPENCODE_CONFIG") != "" {
return "", fmt.Errorf("unset OPENCODE_CONFIG before project plugin sync to avoid editing a shared config")
}
if os.Getenv("OPENCODE_CONFIG_DIR") != "" {
return "", fmt.Errorf("unset OPENCODE_CONFIG_DIR before project plugin sync to avoid editing a shared config")
}
dir = s.ProjectRoot
} else if len(target) > 0 {
if account, ok := s.account(target[0]); ok {
if os.Getenv("OPENCODE_CONFIG") != "" {
return "", fmt.Errorf("unset OPENCODE_CONFIG before account plugin sync to avoid editing a shared config")
}
dir = account.Dir
}
}
if dir == "" {
if override := os.Getenv("OPENCODE_CONFIG"); override != "" {
if !filepath.IsAbs(override) {
return "", fmt.Errorf("OPENCODE_CONFIG must be absolute")
}
return override, nil
}
if override := os.Getenv("OPENCODE_CONFIG_DIR"); override != "" {
if !filepath.IsAbs(override) {
return "", fmt.Errorf("OPENCODE_CONFIG_DIR must be absolute")
}
dir = override
}
}
if dir == "" {
base := os.Getenv("XDG_CONFIG_HOME")
if base == "" {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
base = filepath.Join(home, ".config")
}
if !filepath.IsAbs(base) {
return "", fmt.Errorf("XDG_CONFIG_HOME must be absolute")
}
dir = filepath.Join(base, "opencode")
}
var found string
for _, name := range []string{"opencode.json", "opencode.jsonc"} {
path := filepath.Join(dir, name)
if _, err := os.Lstat(path); err == nil {
if found != "" {
return "", fmt.Errorf("both opencode.json and opencode.jsonc exist; consolidate before plugin sync")
}
found = path
} else if !os.IsNotExist(err) {
return "", err
}
}
if found != "" {
return found, nil
}
return filepath.Join(dir, "opencode.json"), nil
}
func openCode2(version string) bool {
key, _ := openCodeKey(version)
return key == "plugins"
}
// openCodeKey reads `opencode --version`: OpenCode 1 prints 1.x, OpenCode 2 "opencode v2.x".
func openCodeKey(version string) (string, error) {
v := ""
if fields := strings.Fields(version); len(fields) > 0 {
v = strings.TrimPrefix(fields[len(fields)-1], "v")
}
if strings.HasPrefix(v, "1.") {
return "plugin", nil
}
if strings.HasPrefix(v, "2.") {
return "plugins", nil
}
return "", fmt.Errorf("unrecognized OpenCode version; plugin config adapter supports versions 1.x and 2.x")
}
func readPackageConfig(root, path, key string) ([]byte, *hujson.Value, []json.RawMessage, error) {
if err := noSymlink(root, path); err != nil {
return nil, nil, nil, err
}
raw, err := os.ReadFile(path)
if err != nil && !os.IsNotExist(err) {
return nil, nil, nil, err
}
parse := raw
if len(parse) == 0 {
parse = []byte("{}")
}
value, err := hujson.Parse(parse)
if err != nil {
return nil, nil, nil, fmt.Errorf("invalid native config: %w", err)
}
object, ok := value.Value.(*hujson.Object)
if !ok {
return nil, nil, nil, fmt.Errorf("native config must be an object")
}
seen := map[string]bool{}
for _, member := range object.Members {
var name string
_ = json.Unmarshal(member.Name.Pack(), &name)
if seen[name] {
return nil, nil, nil, fmt.Errorf("duplicate native config key %s", name)
}
seen[name] = true
}
clone := value.Clone()
clone.Standardize()
var body map[string]json.RawMessage
if err = json.Unmarshal(clone.Pack(), &body); err != nil {
return nil, nil, nil, err
}
entries := []json.RawMessage{}
if field, ok := body[key]; ok {
if err = json.Unmarshal(field, &entries); err != nil || entries == nil {
return nil, nil, nil, fmt.Errorf("native %s must be an array", key)
}
}
return raw, &value, entries, nil
}
func (s *Service) openCodeInventory(target, version string) ([]Installed, string, error) {
key, err := openCodeKey(version)
if err != nil {
return nil, "", err
}
path, err := s.openCodeConfigPath(target)
if err != nil {
return nil, "", err
}
raw, _, entries, err := readPackageConfig(filepath.Dir(path), path, key)
if err != nil {
return nil, "", err
}
result := []Installed{}
for _, entry := range entries {
var id string
filtered := json.Unmarshal(entry, &id) != nil
if filtered {
var object struct {
Package string `json:"package"`
}
if json.Unmarshal(entry, &object) != nil || object.Package == "" {
return nil, "", fmt.Errorf("unsupported OpenCode plugin entry")
}
id = object.Package
}
if key == "plugins" && (strings.HasPrefix(id, "-") || id == "*" || strings.HasSuffix(id, ".*")) {
continue
}
if !validTargetID("opencode", id) {
return nil, "", fmt.Errorf("unsupported OpenCode plugin control entry; manage it in OpenCode")
}
result = append(result, Installed{ID: id, Name: logicalName(id), Installed: true, Enabled: true, Filtered: filtered})
}
return result, hash(raw), nil
}
func (s *Service) applyOpenCode(ctx context.Context, c Change, b Binding) error {
version, err := s.run(ctx, c.Target, "--version")
if err != nil {
return err
}
key, err := openCodeKey(string(version))
if err != nil {
return err
}
if c.Action == "update" && b.Source == "" {
if key != "plugins" || s.ProjectRoot != "" {
return fmt.Errorf("imported package updates require OpenCode v2 global scope")
}
_, err := s.run(ctx, c.Target, "plugin", "update", b.ID)
return err
}
path, err := s.openCodeConfigPath(c.Target)
if err != nil {
return err
}
if err = noSymlink(filepath.Dir(path), path); err != nil {
return err
}
if err = os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return err
}
lock := flock.New(path + ".skillshare-plugin.lock")
if err = lock.Lock(); err != nil {
return err
}
defer lock.Unlock()
raw, value, entries, err := readPackageConfig(filepath.Dir(path), path, key)
if err != nil {
return err
}
remove := c.Action == "remove" || c.Action == "uninstall"
next := []json.RawMessage{}
found := false
for _, entry := range entries {
var id string
if json.Unmarshal(entry, &id) == nil && id == b.ID {
found = true
if remove {
continue
}
}
next = append(next, entry)
}
if !remove && !found {
data, _ := json.Marshal(b.ID)
next = append(next, data)
}
if found && !remove || !found && remove {
return nil
}
data, _ := json.Marshal(next)
patch, _ := json.Marshal([]map[string]any{{"op": "add", "path": "/" + key, "value": json.RawMessage(data)}})
if err = value.Patch(patch); err != nil {
return err
}
current, err := os.ReadFile(path)
if err != nil && !os.IsNotExist(err) {
return err
}
if !bytes.Equal(current, raw) {
return fmt.Errorf("OpenCode configuration changed; preview again")
}
mode := os.FileMode(0600)
if info, err := os.Stat(path); err == nil {
mode = info.Mode().Perm()
}
return atomicNativeWrite(filepath.Dir(path), path, value.Pack(), mode)
}