Files
Rusty ShacklefordandWillie 43059a1428 fix(opencode): preserve v2 hook and plugin directory packages (#915)
* fix(opencode): preserve v2 directory packages

Stage the reviewed issue 913 source for isolated fork validation. Preserve
package directories and manifests without executing managed packages or
installing their dependencies, and include receipt and localized UI fixes.

Reviewed local source: 15ac88e2f266571b8a6dc8d777302db0f4dcae44
Exact source tree: 45ebabfe2b

Static checks and independent inspection completed. Go, integration,
dashboard, rendering, and hosted runtime validation remain pending.
This fork staging commit is not an upstream publication or merge.

* test(opencode): align schema and snapshot assertions

Check the version-aware binding schema and verify native unregister retains the unchanged managed snapshot.

* fix(opencode): resolve Windows npm native launchers

Probe recognized native Opencode executables without invoking a batch shell; exercise the default version probe on hosted Windows.

* test(opencode): normalize Windows fixture line endings

Avoid doubling carriage returns when Git checks out the npm fixture with CRLF.

* fix(opencode): keep an undetected OpenCode version from blocking other agents

Review of the v2 directory package change found that one failed
`opencode --version` probe failed the whole hooks plan, so a machine
without the binary (a second machine sharing the config, CI, a
devcontainer) could no longer sync hooks to any agent, and doctor and
the dashboard preview failed with it.

Hooks:
- A probe that fails or reports an unknown major now skips only the
  OpenCode bindings with one warning per target. Outputs already owned
  there are parked, so they are neither rewritten nor removed while the
  layout is unknown. The probe runs once per plan, list and import.
- A `package` binding on OpenCode v1 is skipped with a warning instead
  of failing the plan.
- The v2 dependency warning is reported once, and only when a package
  file is written, so a synced hook no longer keeps doctor yellow.
- `hooks import` reports an unreadable file such as a symlink as that
  package's problem; other packages and flat files stay importable.
  The package validation problem is reported once instead of twice.
- Directories under `plugins/` are listed as unmanaged only on v2.

Plugins:
- The inventory leaves `plugins/skillshare-NAME` registrations to
  hooks, so a synced v2 hook is not offered as an importable plugin.

Dashboard: the new warnings are translated in every locale, a
`hook NAME:` prefix no longer defeats translation, the native preview
translates its per-file error, and the YAML editor documents `package`.

Docs: the English pages and the built-in skill describe the behavior
above; the ja, ko, zh-Hans and zh-Hant pages now carry the same
content as the English ones. The runbook drives the CLI with mdproof
assertions instead of prose expectations.

Refs #913.

---------

Co-authored-by: Willie <egg358358@gmail.com>
2026-11-16 01:50:14 +08:00

368 lines
14 KiB
Go

package plugin
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"slices"
"strings"
"gopkg.in/yaml.v3"
)
type manifestSpec struct{ path, target string }
func inspect(root string, explicit ...string) (Candidate, error) {
c := Candidate{Targets: []string{}, Components: []string{}, TargetInfo: map[string]TargetPackage{}}
var claudeFields map[string]json.RawMessage
specs := []manifestSpec{{".codex-plugin/plugin.json", "codex"}, {".claude-plugin/plugin.json", "claude"}, {".omp-plugin/plugin.json", "omp"}, {".cursor-plugin/plugin.json", "cursor"}, {"package.json", "pi"}, {"package.json", "opencode"}, {".plugin/plugin.json", "copilot"}, {".github/plugin/plugin.json", "copilot"}, {".grok-plugin/plugin.json", "grok"}, {"kimi.plugin.json", "kimi"}, {".kimi-plugin/plugin.json", "kimi"}, {".devin-plugin/plugin.json", "devin"}, {".hermes-plugin/plugin.yaml", "hermes"}, {"plugin.json", "codex"}, {"package.json", "omp"}}
for _, spec := range specs {
data, err := os.ReadFile(filepath.Join(root, spec.path))
if os.IsNotExist(err) {
continue
}
info := TargetPackage{Manifest: spec.path, Components: []string{}}
var m map[string]json.RawMessage
if err == nil && strings.HasSuffix(spec.path, ".yaml") {
var raw map[string]any
if err = yaml.Unmarshal(data, &raw); err == nil {
data, err = json.Marshal(raw)
}
}
if err == nil {
err = json.Unmarshal(data, &m)
}
if err != nil {
info.block("plugins.problem.invalidManifest", "Invalid "+spec.path, map[string]string{"manifest": spec.path})
if _, exists := c.TargetInfo[spec.target]; !exists {
c.TargetInfo[spec.target] = info
}
continue
}
var name, desc, schema string
_ = json.Unmarshal(m["name"], &name)
_ = json.Unmarshal(m["version"], &info.Version)
_ = json.Unmarshal(m["description"], &desc)
_ = json.Unmarshal(m["$schema"], &schema)
if spec.path == "plugin.json" {
switch schema {
case "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json":
case "", "https://antigravity.google/schemas/v1/plugin.json":
spec.target = "antigravity"
default:
info.block("plugins.problem.rootSchema", "Unsupported root plugin.json schema", nil)
c.TargetInfo[spec.target] = info
continue
}
}
if spec.target == "codex" {
info.Logo = codexLogo(root, m["interface"])
}
if spec.path == "package.json" {
name = strings.ReplaceAll(strings.TrimPrefix(name, "@"), "/", "-")
if spec.target == "omp" {
if !ompExtensions(root) {
continue
}
info.Components = append(info.Components, "extensions")
} else if spec.target == "pi" {
var resources map[string]json.RawMessage
if m["pi"] != nil {
if json.Unmarshal(m["pi"], &resources) != nil || resources == nil {
info.block("plugins.problem.piObject", "package.json pi must be an object", nil)
}
} else {
var keywords []string
_ = json.Unmarshal(m["keywords"], &keywords)
if !slices.Contains(keywords, "pi-package") {
continue
}
}
for _, key := range []string{"extensions", "skills", "prompts", "themes"} {
if resources[key] != nil || (resources == nil && isDirectory(filepath.Join(root, key))) {
info.Components = append(info.Components, key)
}
}
} else {
var main string
_ = json.Unmarshal(m["main"], &main)
sdk := false
for _, key := range []string{"dependencies", "peerDependencies", "devDependencies"} {
var deps map[string]json.RawMessage
_ = json.Unmarshal(m[key], &deps)
sdk = sdk || deps["@opencode-ai/plugin"] != nil || deps["@opencode/plugin"] != nil
}
if !sdk && (len(explicit) == 0 || explicit[0] == "") && !strings.HasPrefix(filepath.ToSlash(filepath.Clean(main)), ".opencode/plugins/") {
continue
}
info.Entry, err = openCodeEntry(root, explicit...)
if err != nil {
info.openCodeV1Error = err.Error()
}
v2Err := openCodeDirectory(root)
if v2Err != nil {
info.openCodeV2Error = v2Err.Error()
}
if err != nil && v2Err != nil {
var keyed agentError
errors.As(err, &keyed)
info.block(keyed.key, err.Error(), keyed.args)
}
info.Components = append(info.Components, "extensions")
}
}
// OMP, Pi and OpenCode install by path, so a package.json name may be scoped (@owner/pkg),
// differ, or be missing; it only names the plugin when nothing else does.
npm := spec.path == "package.json"
if !namePattern.MatchString(name) && !npm {
info.block("plugins.problem.manifestName", spec.path+" requires a valid plugin name", map[string]string{"manifest": spec.path})
}
if c.Name != "" && c.Name != name && !npm {
info.block("plugins.problem.nameDiffers", "Native manifest name differs from "+c.Name, map[string]string{"name": c.Name})
}
if info.Problem == "" {
if c.Name == "" && namePattern.MatchString(name) {
c.Name, c.Description, c.Version = name, desc, info.Version
}
info.Components = manifestComponents(root, spec.target, m, info.Components)
if spec.target == "claude" {
claudeFields = m
}
}
// The first native manifest wins; explicit invalid manifests remain errors. Codex is the
// exception: it installs from a portable root plugin.json ahead of .codex-plugin/plugin.json,
// and reports 1.0.0 when that manifest has no version.
native, exists := c.TargetInfo[spec.target]
if !exists || spec.path == "plugin.json" && spec.target == "codex" && info.Problem == "" {
c.TargetInfo[spec.target] = info
}
if spec.path == "plugin.json" && spec.target == "codex" {
for _, target := range []string{"cursor", "copilot", "omp"} {
if _, exists := c.TargetInfo[target]; !exists {
c.TargetInfo[target] = info
}
}
if codex := c.TargetInfo["codex"]; codex.Manifest == "plugin.json" {
// .codex-plugin/plugin.json still overlays the portable manifest, so keep its logo.
if codex.Logo == "" {
codex.Logo = native.Logo
}
if codex.Version == "" {
codex.Version = "1.0.0"
}
c.TargetInfo["codex"] = codex
}
}
}
// Codex reads a Claude manifest when none of its own comes first, but only the fields it
// understands, so Claude's other components (agents, for example) are not offered to it.
if claude, ok := c.TargetInfo["claude"]; ok && claude.Problem == "" && claudeFields != nil {
if codexUsesClaudeManifest(root) {
fields := map[string]json.RawMessage{}
for _, key := range []string{"skills", "commands", "hooks", "mcpServers", "apps"} {
if raw, ok := claudeFields[key]; ok {
fields[key] = raw
}
}
// A package with nothing Codex reads, such as agents only, is not offered to it.
if components := manifestComponents(root, "codex", fields, []string{}); len(components) > 0 {
c.TargetInfo["codex"] = TargetPackage{Manifest: claude.Manifest, Version: claude.Version, Logo: codexLogo(root, claudeFields["interface"]), Components: components}
}
}
}
if info, ok := c.TargetInfo["claude"]; ok && info.Problem == "" {
for _, target := range []string{"copilot", "grok", "antigravity-cli", "omp"} {
if _, exists := c.TargetInfo[target]; !exists {
c.TargetInfo[target] = info
}
}
}
// omp loads a Claude plugin's content and, from package.json, its own extension modules. Its
// install records the version it finds itself, never the one in .omp-plugin/plugin.json.
if info, ok := c.TargetInfo["omp"]; ok && info.Problem == "" {
info.Components = slices.Clone(info.Components)
if claude, ok := c.TargetInfo["claude"]; ok && claude.Problem == "" {
for _, component := range claude.Components {
if !slices.Contains(info.Components, component) {
info.Components = append(info.Components, component)
}
}
slices.Sort(info.Components)
}
info.Version = ompInstallVersion(root)
if c.Name != "" && !validOMPName(c.Name) {
info.block("plugins.problem.ompName", "OMP plugin names use only ASCII letters, digits, hyphens and dots, up to 64 characters", nil)
} else if ompExtensions(root) && !slices.Contains(info.Components, "extensions") {
info.Components = append(info.Components, "extensions")
slices.Sort(info.Components)
}
c.TargetInfo["omp"] = info
}
if info, ok := c.TargetInfo["antigravity"]; ok {
c.TargetInfo["antigravity-cli"] = info
}
c.collectTargets()
if c.Name == "" {
return c, fmt.Errorf("no valid supported plugin manifest found; choose a plugin or marketplace directory")
}
return c, nil
}
// claudeCatalogCandidate describes a Claude plugin that has no plugin.json: its catalog entry
// names it, and its components come from that entry and the default folders.
// ponytail: Claude only; other clients that read Claude plugins may still require the manifest.
func claudeCatalogCandidate(dir, name string, fields map[string]json.RawMessage) Candidate {
var desc, version string
_ = json.Unmarshal(fields["description"], &desc)
_ = json.Unmarshal(fields["version"], &version)
info := TargetPackage{Manifest: ".claude-plugin/marketplace.json", Version: version, Components: manifestComponents(dir, "claude", fields, []string{})}
c := Candidate{Name: name, Description: desc, Version: version, Targets: []string{}, Components: info.Components, TargetInfo: map[string]TargetPackage{}}
if len(info.Components) == 0 {
c.block("plugins.problem.noManifest", name+": no plugin.json and no components found", nil)
return c
}
c.TargetInfo["claude"] = info
c.Targets = []string{"claude"}
return c
}
// claudeEntryFields are the parts of a Claude catalog entry that define the plugin. With a
// plugin.json they are merged into it, so several entries can share one folder and differ here.
func claudeEntryFields(fields map[string]json.RawMessage) map[string]json.RawMessage {
entry := map[string]json.RawMessage{}
for _, key := range []string{"version", "description", "strict", "skills", "commands", "agents", "hooks", "mcpServers", "lspServers"} {
if raw, ok := fields[key]; ok {
entry[key] = raw
}
}
return entry
}
func isDirectory(path string) bool { info, err := os.Stat(path); return err == nil && info.IsDir() }
// codexUsesClaudeManifest follows Codex 0.166 (find_plugin_manifest_path): a root plugin.json
// with an Agent Plugins schema comes first, then .codex-plugin/plugin.json, then
// .claude-plugin/plugin.json. A location that is present but linked or not a regular file ends
// the search, so a later manifest never stands in for it. An unrelated or malformed root
// plugin.json is ignored, but an unsupported Agent Plugins schema is not.
func codexUsesClaudeManifest(root string) bool {
path := filepath.Join(root, "plugin.json")
if info, err := os.Lstat(path); !os.IsNotExist(err) {
if err != nil || !info.Mode().IsRegular() {
return false
}
data, err := os.ReadFile(path)
if err != nil {
return false
}
var fields map[string]json.RawMessage
var schema string
if json.Unmarshal(data, &fields) == nil {
_ = json.Unmarshal(fields["$schema"], &schema)
}
if strings.HasPrefix(schema, "https://agent-plugins.org/schemas/") {
return false
}
}
for _, dir := range []string{".codex-plugin", ".claude-plugin"} {
info, err := os.Lstat(filepath.Join(root, dir))
if os.IsNotExist(err) {
continue
}
if err != nil || !info.IsDir() {
return false
}
if info, err = os.Lstat(filepath.Join(root, dir, "plugin.json")); os.IsNotExist(err) {
continue
}
return err == nil && info.Mode().IsRegular() && dir == ".claude-plugin"
}
return false
}
func manifestComponents(root, target string, m map[string]json.RawMessage, components []string) []string {
if target == "pi" || target == "opencode" {
return components
}
for _, key := range []string{"rules", "themes", "contextFileName", "skills", "commands", "agents", "hooks", "mcpServers", "lspServers", "apps", "sessionStart", "systemPromptPath", "provides_hooks"} {
if raw, ok := m[key]; ok && string(raw) != "{}" && string(raw) != "[]" && string(raw) != "null" {
kind := key
switch key {
case "sessionStart", "provides_hooks":
kind = "hooks"
case "contextFileName", "systemPromptPath":
kind = "instructions"
}
if !slices.Contains(components, kind) {
components = append(components, kind)
}
}
}
entries := []struct{ path, kind string }{{"skills", "skills"}, {"agents", "agents"}, {"commands", "commands"}, {"hooks/hooks.json", "hooks"}, {".mcp.json", "mcpServers"}}
if target == "antigravity" {
entries = []struct{ path, kind string }{{"skills", "skills"}, {"agents", "agents"}, {"rules", "rules"}, {"hooks.json", "hooks"}, {"mcp_config.json", "mcpServers"}}
}
if target == "kimi" {
entries = []struct{ path, kind string }{{"skills", "skills"}, {"agents", "agents"}, {"commands", "commands"}}
}
if target == "hermes" {
entries = nil
}
var schema string
_ = json.Unmarshal(m["$schema"], &schema)
if schema == "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json" {
entries = []struct{ path, kind string }{{"skills", "skills"}, {"mcp.json", "mcpServers"}}
} else if target == "codex" {
entries = []struct{ path, kind string }{{"skills", "skills"}, {".mcp.json", "mcpServers"}, {".app.json", "apps"}}
}
for _, entry := range entries {
if _, err := os.Stat(filepath.Join(root, entry.path)); err == nil && !slices.Contains(components, entry.kind) {
components = append(components, entry.kind)
}
}
// Claude loads a root SKILL.md as the plugin's single skill when nothing else names skills.
if _, err := os.Stat(filepath.Join(root, "SKILL.md")); err == nil && target == "claude" && !slices.Contains(components, "skills") {
components = append(components, "skills")
}
slices.Sort(components)
return components
}
const maxLogo = 1 << 20
var logoTypes = map[string]string{".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".svg": "image/svg+xml"}
// codexLogo returns interface.logo of a Codex manifest as a data: URI, "" when it is absent, not
// an image, too large, or outside the plugin. The path is opened through os.Root, so it cannot leave root.
func codexLogo(root string, raw json.RawMessage) string {
var ui struct {
Logo string `json:"logo"`
}
if json.Unmarshal(raw, &ui) != nil || ui.Logo == "" {
return ""
}
mime, ok := logoTypes[strings.ToLower(filepath.Ext(ui.Logo))]
if !ok {
return ""
}
r, err := os.OpenRoot(root)
if err != nil {
return ""
}
defer r.Close()
f, err := r.Open(filepath.FromSlash(strings.TrimPrefix(ui.Logo, "./")))
if err != nil {
return ""
}
defer f.Close()
data, err := io.ReadAll(io.LimitReader(f, maxLogo+1))
if err != nil || len(data) > maxLogo {
return ""
}
return "data:" + mime + ";base64," + base64.StdEncoding.EncodeToString(data)
}