diff --git a/cmd/skillshare/collect_agents.go b/cmd/skillshare/collect_agents.go index 2fc10efee..84c94d6ce 100644 --- a/cmd/skillshare/collect_agents.go +++ b/cmd/skillshare/collect_agents.go @@ -27,6 +27,12 @@ func collectLocalAgents(targets map[string]string, source string, warn bool) []s return allLocalAgents } +// errCollectTransformedAgents refuses to collect from a target whose files are +// extension output: pulling them back would overwrite the source format. +func errCollectTransformedAgents(target, ext string) error { + return fmt.Errorf("target '%s' converts agents with extension %q; collecting would overwrite source agents with converted files", target, ext) +} + func agentDisplayItem(a sync.LocalAgentInfo) collectDisplayItem { return collectDisplayItem{Name: a.Name, TargetName: a.TargetName, Path: a.Path} } @@ -64,13 +70,17 @@ func selectCollectAgentTargets(cfg *config.Config, targetName string, collectAll if agentPath == "" { return nil, fmt.Errorf("target '%s' does not support agents", targetName) } + if ext := target.AgentsConfig().Extension; ext != "" { + return nil, errCollectTransformedAgents(targetName, ext) + } return map[string]string{targetName: agentPath}, nil } targets := make(map[string]string) for name := range cfg.Targets { - agentPath := resolveAgentTargetPath(cfg.Targets[name], builtinAgents, name) - if agentPath == "" { + tc := cfg.Targets[name] + agentPath := resolveAgentTargetPath(tc, builtinAgents, name) + if agentPath == "" || tc.AgentsConfig().Extension != "" { continue } targets[name] = agentPath @@ -134,6 +144,9 @@ func selectCollectProjectAgentTargets(projCfg *config.ProjectConfig, projectRoot if agentPath == "" { return nil, fmt.Errorf("target '%s' does not support agents in project config", targetName) } + if ext := entry.AgentsConfig().Extension; ext != "" { + return nil, errCollectTransformedAgents(targetName, ext) + } return map[string]string{targetName: agentPath}, nil } return nil, fmt.Errorf("target '%s' not found in project config", targetName) @@ -142,7 +155,7 @@ func selectCollectProjectAgentTargets(projCfg *config.ProjectConfig, projectRoot targets := make(map[string]string) for _, entry := range projCfg.Targets { agentPath := resolveProjectAgentTargetPath(entry, builtinAgents, projectRoot) - if agentPath == "" { + if agentPath == "" || entry.AgentsConfig().Extension != "" { continue } targets[entry.Name] = agentPath diff --git a/cmd/skillshare/sync_agents.go b/cmd/skillshare/sync_agents.go index 50334d827..ef0a53a2e 100644 --- a/cmd/skillshare/sync_agents.go +++ b/cmd/skillshare/sync_agents.go @@ -108,7 +108,15 @@ func syncAgentsGlobal(cfg *config.Config, dryRun, force, jsonOutput bool, start continue } filtered = sync.FilterAgentsByTarget(filtered, name) - stats, targetErr := syncAgentTarget(name, agentPath, ac.Mode, filtered, agentsSource, dryRun, force, jsonOutput, "") + spec, specErr := resolveExtension(ac.Extension, globalExtensionsDir()) + if specErr != nil { + if !jsonOutput { + ui.Error("%s: %v", name, specErr) + } + syncErr = fmt.Errorf("some agent targets failed to sync") + continue + } + stats, targetErr := syncAgentTarget(name, agentPath, ac.Mode, spec, filtered, agentsSource, dryRun, force, jsonOutput, "") if targetErr != nil { syncErr = fmt.Errorf("some agent targets failed to sync") } @@ -242,7 +250,15 @@ func syncAgentsProject(projectRoot string, dryRun, force, jsonOutput bool, start continue } filtered = sync.FilterAgentsByTarget(filtered, entry.Name) - stats, targetErr := syncAgentTarget(entry.Name, agentPath, ac.Mode, filtered, agentsSource, dryRun, force, jsonOutput, projectRoot) + spec, specErr := resolveExtension(ac.Extension, projectExtensionsDir(projectRoot)) + if specErr != nil { + if !jsonOutput { + ui.Error("%s: %v", entry.Name, specErr) + } + syncErr = fmt.Errorf("some agent targets failed to sync") + continue + } + stats, targetErr := syncAgentTarget(entry.Name, agentPath, ac.Mode, spec, filtered, agentsSource, dryRun, force, jsonOutput, projectRoot) if targetErr != nil { syncErr = fmt.Errorf("some agent targets failed to sync") } @@ -273,24 +289,37 @@ func syncAgentsProject(projectRoot string, dryRun, force, jsonOutput bool, start // syncAgentTarget syncs agents to a single target directory. // Shared by both global and project sync paths. -func syncAgentTarget(name, agentPath, modeOverride string, agents []resource.DiscoveredResource, agentsSource string, dryRun, force, jsonOutput bool, projectRoot string) (agentSyncStats, error) { +// A non-nil spec transforms each agent instead of linking or copying it. +func syncAgentTarget(name, agentPath, modeOverride string, spec *sync.ExtensionSpec, agents []resource.DiscoveredResource, agentsSource string, dryRun, force, jsonOutput bool, projectRoot string) (agentSyncStats, error) { mode := modeOverride if mode == "" { mode = "merge" } - result, err := sync.SyncAgents(agents, agentsSource, agentPath, mode, dryRun, force, projectRoot) + var result *sync.AgentSyncResult + var err error + outputExt := "" + if spec != nil { + result, err = sync.SyncAgentsTransform(agents, agentsSource, agentPath, mode, spec, dryRun, force) + outputExt = spec.OutputExt + } else { + result, err = sync.SyncAgents(agents, agentsSource, agentPath, mode, dryRun, force, projectRoot) + } if err != nil { if !jsonOutput { ui.Error("%s: agent sync failed: %v", name, err) } - return agentSyncStats{}, err + // A transform returns partial results when only some agents failed; + // the rest still count and orphans still get pruned. + if result == nil { + return agentSyncStats{}, err + } } var pruned []string switch mode { case "copy": - pruned, _ = sync.PruneOrphanAgentCopies(agentPath, agents, dryRun) + pruned, _ = sync.PruneOrphanAgentCopies(agentPath, agents, outputExt, dryRun) case "merge": pruned, _ = sync.PruneOrphanAgentLinks(agentPath, agents, dryRun) } @@ -306,7 +335,7 @@ func syncAgentTarget(name, agentPath, modeOverride string, agents []resource.Dis reportAgentSyncResult(name, mode, stats, dryRun) } - return stats, nil + return stats, err } // reportAgentSyncResult prints per-target agent sync status. diff --git a/extensions/opencode-agents/convert.js b/extensions/opencode-agents/convert.js new file mode 100644 index 000000000..fe0b7e810 --- /dev/null +++ b/extensions/opencode-agents/convert.js @@ -0,0 +1,63 @@ +#!/usr/bin/env node +// Markdown subagent (Claude style) → OpenCode agent (https://opencode.ai/docs/agents/). +// +// Only conversions that need no guessing: +// - keys OpenCode does not document are dropped (name, Claude-only fields, targets) +// - `mode` defaults to subagent; OpenCode's own default (all) would list a +// helper agent as a primary agent +// - a `model` that is not provider/model-id is dropped, so OpenCode uses its default +// - `tools`, `disallowedTools` and `permissionMode` fail the conversion: they +// restrict a Claude agent, and dropping them would let the OpenCode agent use +// every tool + +// Frontmatter keys passed through unchanged. Add OpenCode keys here as needed. +const KEEP = ["description", "mode", "model", "temperature", "top_p", "steps", "permission", "hidden", "color", "prompt"]; + +let input = ""; +process.stdin.setEncoding("utf8"); +process.stdin.on("data", (chunk) => (input += chunk)); +process.stdin.on("end", () => { + try { + process.stdout.write(convert(input)); + } catch (err) { + process.stderr.write(`opencode-agents: ${err.message}\n`); + process.exit(1); + } +}); + +function convert(text) { + const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---[ \t]*\r?\n?/); + const body = match ? text.slice(match[0].length) : text; + const entries = parseEntries(match ? match[1] : ""); + const has = (key) => entries.some((e) => e.key === key); + + const restriction = ["tools", "disallowedTools", "permissionMode"].find(has); + if (restriction) { + throw new Error( + `'${restriction}' limits which tools a Claude agent may use and has no safe OpenCode equivalent. ` + + "Keep a separate OpenCode variant with `targets: [opencode]` and `permission:`, " + + "and add `targets:` to this agent so it skips opencode." + ); + } + if (!has("description")) { + throw new Error("missing required frontmatter 'description'"); + } + + const lines = entries + .filter((e) => KEEP.includes(e.key) && !(e.key === "model" && !e.value.includes("/"))) + .flatMap((e) => e.lines); + if (!has("mode")) lines.push("mode: subagent"); + return `---\n${lines.join("\n")}\n---\n${body}`; +} + +// parseEntries groups frontmatter lines by top-level key; indented lines +// (nested maps such as permission, or lists) stay with the key above them. +function parseEntries(text) { + const entries = []; + for (const line of text.split(/\r?\n/)) { + const m = line.match(/^([A-Za-z0-9_-]+)\s*:\s*(.*)$/); + if (m) entries.push({ key: m[1], value: m[2].trim(), lines: [line] }); + else if (entries.length) entries[entries.length - 1].lines.push(line); + } + return entries; +} diff --git a/extensions/opencode-agents/extension.yaml b/extensions/opencode-agents/extension.yaml new file mode 100644 index 000000000..85922cfe4 --- /dev/null +++ b/extensions/opencode-agents/extension.yaml @@ -0,0 +1,2 @@ +run: ["node", "convert.js"] +description: "Markdown subagent (Claude style) → OpenCode agent" diff --git a/internal/config/config.go b/internal/config/config.go index 547b9c645..5e1ddcc38 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -67,11 +67,22 @@ type ResourceTargetConfig struct { TargetNaming string `yaml:"target_naming,omitempty"` Include []string `yaml:"include,omitempty"` Exclude []string `yaml:"exclude,omitempty"` + // Extension transforms each agent file during sync (agents only; implies copy). + Extension string `yaml:"extension,omitempty"` } // IsEmpty reports whether all fields are zero-valued. func (r ResourceTargetConfig) IsEmpty() bool { - return r.Path == "" && r.Mode == "" && r.TargetNaming == "" && len(r.Include) == 0 && len(r.Exclude) == 0 + return r.Path == "" && r.Mode == "" && r.TargetNaming == "" && len(r.Include) == 0 && len(r.Exclude) == 0 && r.Extension == "" +} + +// withExtensionMode defaults an unset mode to copy when an extension is set, +// so every reader of an agents config sees the mode sync actually uses. +func (r ResourceTargetConfig) withExtensionMode() ResourceTargetConfig { + if r.Extension != "" && r.Mode == "" { + r.Mode = "copy" + } + return r } // TargetConfig holds configuration for a single target. @@ -114,7 +125,7 @@ func (tc *TargetConfig) SkillsConfig() ResourceTargetConfig { // AgentsConfig returns the agents configuration, or an empty value if not set. func (tc *TargetConfig) AgentsConfig() ResourceTargetConfig { if tc.Agents != nil { - return *tc.Agents + return tc.Agents.withExtensionMode() } return ResourceTargetConfig{} } diff --git a/internal/config/project.go b/internal/config/project.go index b14889557..a8b077ae9 100644 --- a/internal/config/project.go +++ b/internal/config/project.go @@ -160,7 +160,7 @@ func (t *ProjectTargetEntry) SkillsConfig() ResourceTargetConfig { // AgentsConfig returns the agents configuration, or an empty value if not set. func (t *ProjectTargetEntry) AgentsConfig() ResourceTargetConfig { if t.Agents != nil { - return *t.Agents + return t.Agents.withExtensionMode() } return ResourceTargetConfig{} } @@ -536,10 +536,11 @@ func ResolveProjectTargets(projectRoot string, cfg *ProjectConfig) (map[string]T absAgentPath = filepath.Join(projectRoot, filepath.FromSlash(agentPath)) } tc.Agents = &ResourceTargetConfig{ - Path: absAgentPath, - Mode: ac.Mode, - Include: append([]string(nil), ac.Include...), - Exclude: append([]string(nil), ac.Exclude...), + Path: absAgentPath, + Mode: ac.Mode, + Include: append([]string(nil), ac.Include...), + Exclude: append([]string(nil), ac.Exclude...), + Extension: ac.Extension, } } diff --git a/internal/config/schema_test.go b/internal/config/schema_test.go index 99b682724..30fe33ea2 100644 --- a/internal/config/schema_test.go +++ b/internal/config/schema_test.go @@ -182,7 +182,7 @@ func TestSchemaFiles_ValidJSON(t *testing.T) { } } -func TestSchema_ExtraTargetsAllowExtension(t *testing.T) { +func TestSchema_ExtrasAndAgentsAllowExtension(t *testing.T) { root := findRepoRoot(t) for _, file := range []string{"schemas/config.schema.json", "schemas/project-config.schema.json"} { data, err := os.ReadFile(filepath.Join(root, file)) @@ -199,8 +199,8 @@ func TestSchema_ExtraTargetsAllowExtension(t *testing.T) { if !owners["extraTargetConfig"] { t.Errorf("%s: extraTargetConfig missing 'extension' property", file) } - if owners["agents"] { - t.Errorf("%s: agents block must not expose 'extension' (agent extensions are unsupported)", file) + if !owners["agents"] { + t.Errorf("%s: agents block missing 'extension' property", file) } } } diff --git a/internal/install/extension_install.go b/internal/install/extension_install.go index 089b24215..57ab51fa1 100644 --- a/internal/install/extension_install.go +++ b/internal/install/extension_install.go @@ -20,6 +20,7 @@ type BuiltinExtension struct { var BuiltinExtensions = []BuiltinExtension{ {Name: "codex-agents", Description: "Convert Markdown subagents (Claude format) into Codex CLI TOML agents"}, {Name: "gemini-commands", Description: "Convert Markdown slash-commands (Claude/Cursor format) into Gemini CLI TOML commands"}, + {Name: "opencode-agents", Description: "Convert Markdown subagents (Claude format) into OpenCode agents"}, } // IsBuiltinExtension reports whether name is a known bundled extension. It diff --git a/internal/server/handler_collect.go b/internal/server/handler_collect.go index 500ea3056..623977b56 100644 --- a/internal/server/handler_collect.go +++ b/internal/server/handler_collect.go @@ -97,7 +97,8 @@ func (s *Server) handleCollectScan(w http.ResponseWriter, r *http.Request) { continue } agentPath := resolveAgentPath(target, builtinAgents, name, s.IsProjectMode()) - if agentPath == "" || agentsSource == "" { + // Extension targets hold converted output, never agents to collect. + if agentPath == "" || agentsSource == "" || target.AgentsConfig().Extension != "" { continue } localAgents, err := ssync.FindLocalAgents(agentPath, agentsSource) diff --git a/internal/server/handler_sync.go b/internal/server/handler_sync.go index e23336047..676da521a 100644 --- a/internal/server/handler_sync.go +++ b/internal/server/handler_sync.go @@ -245,11 +245,26 @@ func (s *Server) syncResources(start time.Time, dryRun, force bool, kind string) } filteredAgents = ssync.FilterAgentsByTarget(filteredAgents, name) - agentResult, err := ssync.SyncAgents(filteredAgents, agentsSource, agentPath, agentMode, dryRun, force, s.projectRoot) + spec, err := s.resolveExtensionSpec(ac.Extension) if err != nil { warnings = append(warnings, "agent sync failed for "+name+": "+err.Error()) continue } + var agentResult *ssync.AgentSyncResult + outputExt := "" + if spec != nil { + agentResult, err = ssync.SyncAgentsTransform(filteredAgents, agentsSource, agentPath, agentMode, spec, dryRun, force) + outputExt = spec.OutputExt + } else { + agentResult, err = ssync.SyncAgents(filteredAgents, agentsSource, agentPath, agentMode, dryRun, force, s.projectRoot) + } + if err != nil { + warnings = append(warnings, "agent sync failed for "+name+": "+err.Error()) + // A transform returns partial results when only some agents failed. + if agentResult == nil { + continue + } + } // Prune orphan agents even when the source is empty so uninstall-all // matches skills and clears previously synced target entries. @@ -257,7 +272,7 @@ func (s *Server) syncResources(start time.Time, dryRun, force bool, kind string) if agentMode == "merge" { pruned, _ = ssync.PruneOrphanAgentLinks(agentPath, filteredAgents, dryRun) } else if agentMode == "copy" { - pruned, _ = ssync.PruneOrphanAgentCopies(agentPath, filteredAgents, dryRun) + pruned, _ = ssync.PruneOrphanAgentCopies(agentPath, filteredAgents, outputExt, dryRun) } // Find or create result entry for this target diff --git a/internal/server/handler_targets.go b/internal/server/handler_targets.go index e8f202376..ee5e0624f 100644 --- a/internal/server/handler_targets.go +++ b/internal/server/handler_targets.go @@ -31,6 +31,7 @@ type targetItem struct { CollisionCount int `json:"collisionCount,omitempty"` AgentPath string `json:"agentPath,omitempty"` AgentMode string `json:"agentMode,omitempty"` + AgentExtension string `json:"agentExtension,omitempty"` AgentInclude []string `json:"agentInclude,omitempty"` AgentExclude []string `json:"agentExclude,omitempty"` AgentLinkedCount *int `json:"agentLinkedCount,omitempty"` @@ -168,6 +169,7 @@ func (s *Server) handleListTargets(w http.ResponseWriter, r *http.Request) { if agentSummary != nil { item.AgentPath = agentSummary.Path item.AgentMode = agentSummary.Mode + item.AgentExtension = agentSummary.Extension item.AgentInclude = agentSummary.Include item.AgentExclude = agentSummary.Exclude item.AgentLinkedCount = intPtr(agentSummary.ManagedCount) @@ -327,19 +329,27 @@ func (s *Server) handleUpdateTarget(w http.ResponseWriter, r *http.Request) { } var body struct { - Include *[]string `json:"include"` // null = no change, [] = clear - Exclude *[]string `json:"exclude"` - Mode *string `json:"mode"` - TargetNaming *string `json:"target_naming"` - AgentMode *string `json:"agent_mode"` - AgentInclude *[]string `json:"agent_include"` - AgentExclude *[]string `json:"agent_exclude"` + Include *[]string `json:"include"` // null = no change, [] = clear + Exclude *[]string `json:"exclude"` + Mode *string `json:"mode"` + TargetNaming *string `json:"target_naming"` + AgentMode *string `json:"agent_mode"` + AgentInclude *[]string `json:"agent_include"` + AgentExclude *[]string `json:"agent_exclude"` + AgentExtension *string `json:"agent_extension"` // "" = clear } if err := json.NewDecoder(r.Body).Decode(&body); err != nil { writeError(w, http.StatusBadRequest, "invalid JSON body") return } + // An extension converts each agent, so it implies copy mode. Reject a + // conflicting mode sent in this same call, as extras targets do. + if body.AgentExtension != nil && *body.AgentExtension != "" && body.AgentMode != nil && *body.AgentMode != "copy" { + writeError(w, http.StatusBadRequest, "agent extension requires copy mode, but agent_mode "+*body.AgentMode+" was set") + return + } + target.EnsureSkills() // Validate patterns @@ -386,6 +396,13 @@ func (s *Server) handleUpdateTarget(w http.ResponseWriter, r *http.Request) { } } + if body.AgentExtension != nil { + if *body.AgentExtension != "" { + target.EnsureAgents().Mode = "copy" + } + target.EnsureAgents().Extension = *body.AgentExtension + } + if body.AgentInclude != nil { if _, err := ssync.FilterSkills(nil, *body.AgentInclude, nil); err != nil { writeError(w, http.StatusBadRequest, "invalid agent include pattern: "+err.Error()) @@ -429,6 +446,13 @@ func (s *Server) handleUpdateTarget(w http.ResponseWriter, r *http.Request) { if body.AgentExclude != nil { s.projectCfg.Targets[i].EnsureAgents().Exclude = *body.AgentExclude } + if body.AgentExtension != nil { + ag := s.projectCfg.Targets[i].EnsureAgents() + if *body.AgentExtension != "" { + ag.Mode = "copy" + } + ag.Extension = *body.AgentExtension + } break } } @@ -440,7 +464,7 @@ func (s *Server) handleUpdateTarget(w http.ResponseWriter, r *http.Request) { } hasFilter := body.Include != nil || body.Exclude != nil || body.AgentInclude != nil || body.AgentExclude != nil - hasSetting := body.Mode != nil || body.TargetNaming != nil || body.AgentMode != nil + hasSetting := body.Mode != nil || body.TargetNaming != nil || body.AgentMode != nil || body.AgentExtension != nil action := "filter" if hasSetting && hasFilter { action = "settings+filter" diff --git a/internal/server/handler_targets_test.go b/internal/server/handler_targets_test.go index 4bd84d784..31b5cd949 100644 --- a/internal/server/handler_targets_test.go +++ b/internal/server/handler_targets_test.go @@ -378,3 +378,62 @@ func TestHandleUpdateTarget_AgentExclude_InvalidPattern(t *testing.T) { t.Errorf("expected 400 for invalid agent exclude pattern, got %d", rr.Code) } } + +func patchTarget(t *testing.T, s *Server, body string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodPatch, "/api/targets/claude", strings.NewReader(body)) + rr := httptest.NewRecorder() + s.handler.ServeHTTP(rr, req) + return rr +} + +func TestHandleUpdateTarget_AgentExtension_ForcesCopy(t *testing.T) { + tgtPath := filepath.Join(t.TempDir(), "claude-skills") + s, _ := newTestServerWithTargets(t, map[string]string{"claude": tgtPath}) + + if rr := patchTarget(t, s, `{"agent_mode":"merge"}`); rr.Code != http.StatusOK { + t.Fatalf("PATCH mode expected 200, got %d: %s", rr.Code, rr.Body.String()) + } + if rr := patchTarget(t, s, `{"agent_extension":"opencode-agents"}`); rr.Code != http.StatusOK { + t.Fatalf("PATCH extension expected 200, got %d: %s", rr.Code, rr.Body.String()) + } + + diskCfg, err := config.Load() + if err != nil { + t.Fatal(err) + } + tgt := diskCfg.Targets["claude"] + if tgt.Agents == nil || tgt.Agents.Extension != "opencode-agents" || tgt.Agents.Mode != "copy" { + t.Errorf("disk agents = %+v, want extension opencode-agents in copy mode", tgt.Agents) + } +} + +func TestHandleUpdateTarget_AgentExtension_RejectsConflictingMode(t *testing.T) { + tgtPath := filepath.Join(t.TempDir(), "claude-skills") + s, _ := newTestServerWithTargets(t, map[string]string{"claude": tgtPath}) + + patchTarget(t, s, `{"agent_mode":"merge"}`) // agents block now exists and is shared + rr := patchTarget(t, s, `{"agent_extension":"opencode-agents","agent_mode":"symlink"}`) + if rr.Code != http.StatusBadRequest { + t.Fatalf("expected 400, got %d: %s", rr.Code, rr.Body.String()) + } + memTgt := s.cfg.Targets["claude"] + if mode := memTgt.AgentsConfig().Mode; mode == "symlink" { + t.Error("a rejected request must not change the agent mode") + } +} + +func TestHandleUpdateTarget_AgentExtension_Clear(t *testing.T) { + tgtPath := filepath.Join(t.TempDir(), "claude-skills") + s, _ := newTestServerWithTargets(t, map[string]string{"claude": tgtPath}) + + patchTarget(t, s, `{"agent_extension":"opencode-agents"}`) + if rr := patchTarget(t, s, `{"agent_extension":""}`); rr.Code != http.StatusOK { + t.Fatalf("expected 200, got %d: %s", rr.Code, rr.Body.String()) + } + + memTgt := s.cfg.Targets["claude"] + if ext := memTgt.AgentsConfig().Extension; ext != "" { + t.Errorf("extension = %q, want cleared", ext) + } +} diff --git a/internal/sync/agent_sync.go b/internal/sync/agent_sync.go index c1337403b..5120bfc37 100644 --- a/internal/sync/agent_sync.go +++ b/internal/sync/agent_sync.go @@ -1,6 +1,7 @@ package sync import ( + "bytes" "errors" "fmt" "os" @@ -275,6 +276,80 @@ func syncAgentsCopy(agents []resource.DiscoveredResource, targetDir string, dryR return result, nil } +// SyncAgentsTransform pipes each agent through spec and writes the output into +// targetDir, renamed per spec.OutputExt. Like copy mode, the target is owned by +// skillshare, so differing files are overwritten. A failing agent is reported in +// the returned error without stopping the others. +func SyncAgentsTransform(agents []resource.DiscoveredResource, sourceDir, targetDir, mode string, spec *ExtensionSpec, dryRun, force bool) (*AgentSyncResult, error) { + if _, err := ResolveExtensionMode(mode); err != nil { + return nil, err + } + result := &AgentSyncResult{} + var errs []error + + // A symlink-mode leftover points the whole target at the source; writing + // through it would overwrite source agents. + if !dryRun && utils.IsSymlinkOrJunction(targetDir) { + if absLink, err := utils.ResolveLinkTarget(targetDir); err == nil && linkResolvesToSource(absLink, sourceDir) { + if err := os.Remove(targetDir); err != nil { + return nil, fmt.Errorf("failed to remove directory symlink: %w", err) + } + } + } + + for _, agent := range agents { + name := ApplyOutputExt(agent.FlatName, spec.OutputExt) + // A preview must never execute extension code, so dry-run can't know + // whether the output would change. + if dryRun { + result.Linked = append(result.Linked, name) + continue + } + + tgtFile := filepath.Join(targetDir, name) + // Merge-mode leftovers link to the source; drop the link, never write through it. + if info, err := os.Lstat(tgtFile); err == nil && info.Mode()&os.ModeSymlink != 0 { + if err := os.Remove(tgtFile); err != nil { + errs = append(errs, fmt.Errorf("%s: remove symlink: %w", agent.FlatName, err)) + continue + } + } + existing, readErr := os.ReadFile(tgtFile) + out, err := runExtension(spec, agent.AbsPath, map[string]string{ + "SS_SRC_PATH": agent.AbsPath, + "SS_REL_PATH": agent.RelPath, + "SS_TARGET_DIR": targetDir, + "SS_MODE": "sync", + }) + if err != nil { + // Keeping the old output would leave an unconverted agent active. + if readErr == nil { + os.Remove(tgtFile) + } + errs = append(errs, fmt.Errorf("%s: %w", agent.FlatName, err)) + continue + } + if readErr == nil && bytes.Equal(existing, out) && !force { + result.Linked = append(result.Linked, name) + continue + } + if err := os.MkdirAll(targetDir, 0755); err != nil { + return nil, fmt.Errorf("failed to create agent target directory: %w", err) + } + if err := os.WriteFile(tgtFile, out, 0644); err != nil { + errs = append(errs, fmt.Errorf("%s: write target: %w", agent.FlatName, err)) + continue + } + if readErr == nil { + result.Updated = append(result.Updated, name) + } else { + result.Linked = append(result.Linked, name) + } + } + + return result, errors.Join(errs...) +} + // SyncAgentsToTarget creates file symlinks in targetDir for each discovered agent. // Uses merge semantics. Kept for backward compatibility; prefer SyncAgents(). func SyncAgentsToTarget(agents []resource.DiscoveredResource, targetDir string, dryRun, force bool) (*AgentSyncResult, error) { @@ -327,8 +402,10 @@ func PruneOrphanAgentLinks(targetDir string, agents []resource.DiscoveredResourc } // PruneOrphanAgentCopies removes copied .md files in targetDir that don't -// correspond to any discovered agent. For copy mode only. -func PruneOrphanAgentCopies(targetDir string, agents []resource.DiscoveredResource, dryRun bool) (removed []string, _ error) { +// correspond to any discovered agent. For copy mode only. outputExt is the +// extension a transform renames outputs to ("" keeps .md); files with it are +// pruned too, and a stale .md copy of a transformed agent counts as an orphan. +func PruneOrphanAgentCopies(targetDir string, agents []resource.DiscoveredResource, outputExt string, dryRun bool) (removed []string, _ error) { entries, err := os.ReadDir(targetDir) if err != nil { if os.IsNotExist(err) { @@ -339,13 +416,18 @@ func PruneOrphanAgentCopies(targetDir string, agents []resource.DiscoveredResour expected := make(map[string]bool, len(agents)) for _, a := range agents { - expected[a.FlatName] = true + expected[ApplyOutputExt(a.FlatName, outputExt)] = true + } + outSuffix := "" + if outputExt != "" { + outSuffix = "." + strings.ToLower(outputExt) } for _, entry := range entries { name := entry.Name() + lower := strings.ToLower(name) - if !strings.HasSuffix(strings.ToLower(name), ".md") { + if !strings.HasSuffix(lower, ".md") && (outSuffix == "" || !strings.HasSuffix(lower, outSuffix)) { continue } diff --git a/internal/sync/agent_sync_test.go b/internal/sync/agent_sync_test.go index 5754a785a..f3051a4dd 100644 --- a/internal/sync/agent_sync_test.go +++ b/internal/sync/agent_sync_test.go @@ -477,7 +477,7 @@ func TestPruneOrphanAgentCopies(t *testing.T) { {FlatName: "active.md"}, } - removed, err := PruneOrphanAgentCopies(targetDir, agents, false) + removed, err := PruneOrphanAgentCopies(targetDir, agents, "", false) if err != nil { t.Fatalf("PruneOrphanAgentCopies: %v", err) } @@ -768,3 +768,88 @@ func TestPullAgents_DryRun(t *testing.T) { t.Error("file should not exist in dry-run") } } + +// agentTransformFixture creates source agent tutor.md and returns it with an +// uppercasing spec, so any write-through to the source is visible. +func agentTransformFixture(t *testing.T) (string, []resource.DiscoveredResource, *ExtensionSpec) { + t.Helper() + sourceDir := t.TempDir() + src := filepath.Join(sourceDir, "tutor.md") + if err := os.WriteFile(src, []byte("body"), 0644); err != nil { + t.Fatal(err) + } + agents := []resource.DiscoveredResource{{FlatName: "tutor.md", RelPath: "tutor.md", AbsPath: src}} + spec := &ExtensionSpec{Run: []string{"tr", "a-z", "A-Z"}, Dir: sourceDir, Name: "upper"} + return sourceDir, agents, spec +} + +func assertSourceUntouched(t *testing.T, sourceDir string) { + t.Helper() + data, err := os.ReadFile(filepath.Join(sourceDir, "tutor.md")) + if err != nil { + t.Fatal(err) + } + if string(data) != "body" { + t.Errorf("source agent overwritten: %q", data) + } +} + +func TestSyncAgentsTransform_ReplacesLeftoverFileSymlink(t *testing.T) { + sourceDir, agents, spec := agentTransformFixture(t) + targetDir := t.TempDir() + // Left over from merge mode. + if err := os.Symlink(agents[0].AbsPath, filepath.Join(targetDir, "tutor.md")); err != nil { + t.Fatal(err) + } + + if _, err := SyncAgentsTransform(agents, sourceDir, targetDir, "", spec, false, false); err != nil { + t.Fatal(err) + } + assertSourceUntouched(t, sourceDir) +} + +func TestSyncAgentsTransform_ReplacesLeftoverDirSymlink(t *testing.T) { + sourceDir, agents, spec := agentTransformFixture(t) + targetDir := filepath.Join(t.TempDir(), "agents") + // Left over from symlink mode. + if err := os.Symlink(sourceDir, targetDir); err != nil { + t.Fatal(err) + } + + if _, err := SyncAgentsTransform(agents, sourceDir, targetDir, "", spec, false, false); err != nil { + t.Fatal(err) + } + assertSourceUntouched(t, sourceDir) +} + +func TestSyncAgentsTransform_FailureRemovesStaleOutput(t *testing.T) { + sourceDir, agents, _ := agentTransformFixture(t) + targetDir := t.TempDir() + stale := filepath.Join(targetDir, "tutor.md") + if err := os.WriteFile(stale, []byte("unconverted"), 0644); err != nil { + t.Fatal(err) + } + failing := &ExtensionSpec{Run: []string{"false"}, Dir: sourceDir, Name: "fail"} + + if _, err := SyncAgentsTransform(agents, sourceDir, targetDir, "", failing, false, false); err == nil { + t.Fatal("expected conversion error") + } + if _, err := os.Lstat(stale); !os.IsNotExist(err) { + t.Error("an agent that fails to convert must not keep its old output") + } +} + +func TestPruneOrphanAgentCopies_PrunesTransformedOrphans(t *testing.T) { + targetDir := t.TempDir() + orphan := filepath.Join(targetDir, "gone.toml") + if err := os.WriteFile(orphan, []byte("x"), 0644); err != nil { + t.Fatal(err) + } + + if _, err := PruneOrphanAgentCopies(targetDir, nil, "toml", false); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(orphan); !os.IsNotExist(err) { + t.Error("orphan gone.toml should be pruned") + } +} diff --git a/internal/sync/extension_test.go b/internal/sync/extension_test.go index 365b4790d..8524c5ee1 100644 --- a/internal/sync/extension_test.go +++ b/internal/sync/extension_test.go @@ -531,12 +531,71 @@ func TestBundledCodexAgentExtension_RequiresNameAndBody(t *testing.T) { } } +func TestBundledOpencodeAgentExtension_ConvertsClaudeAgent(t *testing.T) { + out, err := runBundledExtension(t, "opencode-agents", "---\nname: code-reviewer\ndescription: Reviews code\nmodel: sonnet\ncolor: blue\n---\nReview carefully.\n") + if err != nil { + t.Fatalf("opencode-agents convert failed: %v\n%s", err, out) + } + // name and a non provider/model-id model are dropped; mode defaults to subagent. + want := "---\ndescription: Reviews code\ncolor: blue\nmode: subagent\n---\nReview carefully.\n" + if out != want { + t.Errorf("output =\n%s\nwant\n%s", out, want) + } +} + +func TestBundledOpencodeAgentExtension_KeepsOpencodeFields(t *testing.T) { + input := "---\ndescription: d\nmode: primary\nmodel: anthropic/claude-sonnet-4-5\npermission:\n edit: deny\n---\nbody\n" + out, err := runBundledExtension(t, "opencode-agents", input) + if err != nil { + t.Fatalf("opencode-agents convert failed: %v\n%s", err, out) + } + if out != input { + t.Errorf("output =\n%s\nwant unchanged\n%s", out, input) + } +} + +func TestBundledOpencodeAgentExtension_RejectsClaudeTools(t *testing.T) { + out, err := runBundledExtension(t, "opencode-agents", "---\ndescription: d\ntools: Read, Bash(git log)\n---\nbody\n") + if err == nil { + t.Fatalf("expected tools to fail, got success:\n%s", out) + } + if !strings.Contains(out, "'tools'") { + t.Fatalf("expected error naming 'tools', got:\n%s", out) + } +} + +func TestBundledOpencodeAgentExtension_RejectsClaudeToolRestrictions(t *testing.T) { + for _, field := range []string{"disallowedTools: Bash", "permissionMode: plan"} { + out, err := runBundledExtension(t, "opencode-agents", "---\ndescription: d\n"+field+"\n---\nbody\n") + if err == nil { + t.Errorf("%s: expected failure, got success:\n%s", field, out) + } + } +} + +func TestBundledOpencodeAgentExtension_RequiresDescription(t *testing.T) { + out, err := runBundledExtension(t, "opencode-agents", "# Reviewer\nbody\n") + if err == nil { + t.Fatalf("expected missing description to fail, got success:\n%s", out) + } + if !strings.Contains(out, "missing required frontmatter 'description'") { + t.Fatalf("expected missing description error, got:\n%s", out) + } +} + func runBundledCodexAgentExtension(t *testing.T, input string) (string, error) { + t.Helper() + return runBundledExtension(t, "codex-agents", input) +} + +// runBundledExtension runs extensions//convert.js over input and returns +// its combined output. +func runBundledExtension(t *testing.T, name, input string) (string, error) { t.Helper() node := requireNode(t) root := testRepoRoot(t) - cmd := exec.Command(node, filepath.Join(root, "extensions", "codex-agents", "convert.js")) + cmd := exec.Command(node, filepath.Join(root, "extensions", name, "convert.js")) cmd.Env = append(os.Environ(), "SS_REL_PATH=reviewer.md") cmd.Stdin = strings.NewReader(input) diff --git a/internal/targetsummary/agents.go b/internal/targetsummary/agents.go index 411525109..5b7a42ed0 100644 --- a/internal/targetsummary/agents.go +++ b/internal/targetsummary/agents.go @@ -19,6 +19,7 @@ type AgentSummary struct { DisplayPath string Path string Mode string + Extension string Include []string Exclude []string ManagedCount int @@ -81,7 +82,7 @@ func (b *Builder) GlobalTarget(name string, tc config.TargetConfig) (*AgentSumma return nil, nil } - return b.buildSummary(name, config.ExpandPath(displayPath), displayPath, ac.Mode, ac.Include, ac.Exclude) + return b.buildSummary(name, config.ExpandPath(displayPath), displayPath, ac) } // ProjectTarget returns the effective agents summary for a project target. @@ -99,10 +100,11 @@ func (b *Builder) ProjectTarget(entry config.ProjectTargetEntry) (*AgentSummary, return nil, nil } - return b.buildSummary(entry.Name, resolveProjectPath(b.projectRoot, displayPath), displayPath, ac.Mode, ac.Include, ac.Exclude) + return b.buildSummary(entry.Name, resolveProjectPath(b.projectRoot, displayPath), displayPath, ac) } -func (b *Builder) buildSummary(targetName, path, displayPath, mode string, include, exclude []string) (*AgentSummary, error) { +func (b *Builder) buildSummary(targetName, path, displayPath string, ac config.ResourceTargetConfig) (*AgentSummary, error) { + mode, include, exclude := ac.Mode, ac.Include, ac.Exclude if mode == "" { mode = defaultAgentMode } @@ -111,6 +113,7 @@ func (b *Builder) buildSummary(targetName, path, displayPath, mode string, inclu Path: path, DisplayPath: displayPath, Mode: mode, + Extension: ac.Extension, Include: append([]string(nil), include...), Exclude: append([]string(nil), exclude...), } @@ -128,7 +131,10 @@ func (b *Builder) buildSummary(targetName, path, displayPath, mode string, inclu summary.ExpectedCount = len(expectedAgents) } summary.ManagedCount = countManagedAgents(path, mode, b.sourcePath, summary.ExpectedCount) - summary.LocalCount = countLocalAgents(path, b.sourcePath) + // Extension output is managed, not local, even when it keeps the .md name. + if ac.Extension == "" { + summary.LocalCount = countLocalAgents(path, b.sourcePath) + } return summary, nil } diff --git a/schemas/config.schema.json b/schemas/config.schema.json index 366158f89..e72031340 100644 --- a/schemas/config.schema.json +++ b/schemas/config.schema.json @@ -185,7 +185,8 @@ "properties": { "mode": { "type": "string", "enum": ["merge", "symlink", "copy"] }, "include": { "type": "array", "items": { "type": "string" } }, - "exclude": { "type": "array", "items": { "type": "string" } } + "exclude": { "type": "array", "items": { "type": "string" } }, + "extension": { "type": "string", "description": "Convert each agent through an extension before writing it to this target (copy mode; an unset mode becomes copy). A bare name resolves under the extensions directory; a path (containing a separator or starting with '.') is used directly.", "examples": ["opencode-agents", "codex-agents"] } } } } @@ -262,7 +263,8 @@ "path": { "type": "string" }, "mode": { "type": "string", "enum": ["merge", "symlink", "copy"] }, "include": { "type": "array", "items": { "type": "string" } }, - "exclude": { "type": "array", "items": { "type": "string" } } + "exclude": { "type": "array", "items": { "type": "string" } }, + "extension": { "type": "string", "description": "Convert each agent through an extension before writing it to this target (copy mode; an unset mode becomes copy). A bare name resolves under the extensions directory; a path (containing a separator or starting with '.') is used directly.", "examples": ["opencode-agents", "codex-agents"] } } } } diff --git a/schemas/project-config.schema.json b/schemas/project-config.schema.json index 4fa73a317..f8dadc337 100644 --- a/schemas/project-config.schema.json +++ b/schemas/project-config.schema.json @@ -236,7 +236,8 @@ "path": { "type": "string" }, "mode": { "type": "string", "enum": ["merge", "symlink", "copy"] }, "include": { "type": "array", "items": { "type": "string" } }, - "exclude": { "type": "array", "items": { "type": "string" } } + "exclude": { "type": "array", "items": { "type": "string" } }, + "extension": { "type": "string", "description": "Convert each agent through an extension before writing it to this target (copy mode; an unset mode becomes copy). A bare name resolves under the extensions directory; a path (containing a separator or starting with '.') is used directly.", "examples": ["opencode-agents", "codex-agents"] } } } } diff --git a/tests/integration/sync_agent_extension_test.go b/tests/integration/sync_agent_extension_test.go new file mode 100644 index 000000000..cbe0c041f --- /dev/null +++ b/tests/integration/sync_agent_extension_test.go @@ -0,0 +1,184 @@ +//go:build !online + +package integration + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "skillshare/internal/testutil" +) + +// writeAgentExtension installs a directory-form extension into the global +// extensions dir and returns its name. +func writeAgentExtension(t *testing.T, sb *testutil.Sandbox, name, manifest string) string { + t.Helper() + extDir := filepath.Join(sb.Home, ".config", "skillshare", "extensions", name) + if err := os.MkdirAll(extDir, 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(extDir, "extension.yaml"), []byte(manifest), 0644); err != nil { + t.Fatal(err) + } + return name +} + +func agentExtensionConfig(sb *testutil.Sandbox, agentsPath, extra string) string { + return `source: ` + sb.SourcePath + ` +targets: + claude: + skills: + path: ` + sb.CreateTarget("claude") + ` + agents: + path: ` + agentsPath + ` +` + extra +} + +func TestSync_AgentsExtension_TransformsAndRenames(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + + createAgentSource(t, sb, map[string]string{"tutor.md": "body"}) + agentsPath := createAgentTarget(t, sb, "codex") + ext := writeAgentExtension(t, sb, "upper2toml", "run: [\"tr\", \"a-z\", \"A-Z\"]\noutput_ext: toml\n") + sb.WriteConfig(agentExtensionConfig(sb, agentsPath, " extension: "+ext+"\n")) + + sb.RunCLI("sync", "agents").AssertSuccess(t) + + out, err := os.ReadFile(filepath.Join(agentsPath, "tutor.toml")) + if err != nil { + t.Fatalf("expected tutor.toml: %v", err) + } + if string(out) != "BODY" { + t.Errorf("output = %q, want BODY", string(out)) + } +} + +func TestSync_AgentsExtension_RejectsMergeMode(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + + createAgentSource(t, sb, map[string]string{"tutor.md": "body"}) + agentsPath := createAgentTarget(t, sb, "codex") + ext := writeAgentExtension(t, sb, "id", "run: [\"cat\"]\n") + sb.WriteConfig(agentExtensionConfig(sb, agentsPath, " mode: merge\n extension: "+ext+"\n")) + + result := sb.RunCLI("sync", "agents") + if result.ExitCode == 0 { + t.Fatal("expected non-zero exit for extension + merge mode") + } +} + +func TestSync_AgentsExtension_PrunesByOutputName(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + + createAgentSource(t, sb, map[string]string{"tutor.md": "body"}) + agentsPath := createAgentTarget(t, sb, "codex") + // A plain copy left over from before the extension was configured. + if err := os.WriteFile(filepath.Join(agentsPath, "tutor.md"), []byte("body"), 0644); err != nil { + t.Fatal(err) + } + ext := writeAgentExtension(t, sb, "upper2toml", "run: [\"tr\", \"a-z\", \"A-Z\"]\noutput_ext: toml\n") + sb.WriteConfig(agentExtensionConfig(sb, agentsPath, " extension: "+ext+"\n")) + + sb.RunCLI("sync", "agents").AssertSuccess(t) + + if _, err := os.Stat(filepath.Join(agentsPath, "tutor.md")); !os.IsNotExist(err) { + t.Error("stale tutor.md copy should be pruned once the target emits tutor.toml") + } +} + +func TestCollect_AgentsExtension_NeverPullsTransformedOutput(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + + agentsSource := createAgentSource(t, sb, map[string]string{"tutor.md": "body"}) + agentsPath := createAgentTarget(t, sb, "codex") + // Output keeps .md, so without a guard collect would see it as a local agent. + ext := writeAgentExtension(t, sb, "upper", "run: [\"tr\", \"a-z\", \"A-Z\"]\n") + sb.WriteConfig(agentExtensionConfig(sb, agentsPath, " extension: "+ext+"\n")) + sb.RunCLI("sync", "agents").AssertSuccess(t) + + sb.RunCLI("collect", "agents", "--all", "--force") + + src, err := os.ReadFile(filepath.Join(agentsSource, "tutor.md")) + if err != nil { + t.Fatal(err) + } + if string(src) != "body" { + t.Errorf("source overwritten by transformed output: %q", string(src)) + } +} + +func TestCollect_AgentsExtension_NamedTargetRefused(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + + createAgentSource(t, sb, map[string]string{"tutor.md": "body"}) + agentsPath := createAgentTarget(t, sb, "codex") + ext := writeAgentExtension(t, sb, "upper", "run: [\"tr\", \"a-z\", \"A-Z\"]\n") + sb.WriteConfig(agentExtensionConfig(sb, agentsPath, " extension: "+ext+"\n")) + + result := sb.RunCLI("collect", "agents", "claude") + result.AssertFailure(t) + result.AssertAnyOutputContains(t, "extension") +} + +// opencodeAgentsExtension returns the bundled opencode-agents extension path, +// skipping when node is unavailable. +func opencodeAgentsExtension(t *testing.T) string { + t.Helper() + if _, err := exec.LookPath("node"); err != nil { + t.Skip("node not available") + } + path, err := filepath.Abs(filepath.Join("..", "..", "extensions", "opencode-agents")) + if err != nil { + t.Fatal(err) + } + return path +} + +func TestSync_AgentsExtension_OpencodeRejectsClaudeTools(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + + createAgentSource(t, sb, map[string]string{"a.md": "---\ndescription: d\ntools: Read, Bash(git log)\n---\nbody\n"}) + agentsPath := createAgentTarget(t, sb, "opencode") + sb.WriteConfig(agentExtensionConfig(sb, agentsPath, " extension: "+opencodeAgentsExtension(t)+"\n")) + + result := sb.RunCLI("sync", "agents") + result.AssertFailure(t) + if !strings.Contains(result.Output(), "tools") { + t.Errorf("error should name the tools field, got: %s", result.Output()) + } + if _, err := os.Stat(filepath.Join(agentsPath, "a.md")); !os.IsNotExist(err) { + t.Error("an agent whose tools can't be mapped must not be written") + } +} + +func TestSync_AgentsExtension_PartialFailureStillPrunes(t *testing.T) { + sb := testutil.NewSandbox(t) + defer sb.Cleanup() + + createAgentSource(t, sb, map[string]string{"good.md": "ok", "bad.md": "FAIL"}) + agentsPath := createAgentTarget(t, sb, "codex") + orphan := filepath.Join(agentsPath, "gone.md") + if err := os.WriteFile(orphan, []byte("old"), 0644); err != nil { + t.Fatal(err) + } + ext := writeAgentExtension(t, sb, "picky", "run: [\"sh\", \"-c\", \"grep -q FAIL \\\"$SS_SRC_PATH\\\" && exit 1; cat\"]\n") + sb.WriteConfig(agentExtensionConfig(sb, agentsPath, " extension: "+ext+"\n")) + + sb.RunCLI("sync", "agents").AssertFailure(t) + + if _, err := os.Stat(filepath.Join(agentsPath, "good.md")); err != nil { + t.Errorf("good.md should still sync: %v", err) + } + if _, err := os.Stat(orphan); !os.IsNotExist(err) { + t.Error("orphans should be pruned even when one agent fails") + } +}