返回 DeepSeek-Reasonix
plugin_package.go
根目录 / internal / installsource / plugin_package.go
1 package installsource
2
3 import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "regexp"
12 "slices"
13 "sort"
14 "strings"
15
16 "reasonix/internal/config"
17 "reasonix/internal/gitcmd"
18 "reasonix/internal/pluginpkg"
19 )
20
21 const (
22 claudeMarketplaceManifest = ".claude-plugin/marketplace.json"
23 maxMarketplacePlugins = 64
24 )
25
26 type claudeMarketplace struct {
27 Name string `json:"name"`
28 Metadata struct {
29 PluginRoot string `json:"pluginRoot"`
30 } `json:"metadata"`
31 Plugins []struct {
32 Name string `json:"name"`
33 Source json.RawMessage `json:"source"`
34 } `json:"plugins"`
35 }
36
37 type claudeMarketplaceURLSource struct {
38 Source string `json:"source"`
39 URL string `json:"url"`
40 SHA string `json:"sha"`
41 }
42
43 var fullGitSHA = regexp.MustCompile(`^[0-9a-fA-F]{40}$`)
44
45 func (t *installSourceTool) localPluginPackageAction(req request, root string) (action, []string, error) {
46 pkg, warnings, err := pluginpkg.ParseDir(root)
47 if err != nil {
48 return action{}, warnings, newErr(ErrManifestMissing, "%v", err)
49 }
50 act, err := t.pluginPackageAction(req, pkg, root)
51 return act, warnings, err
52 }
53
54 func (t *installSourceTool) planGitHubPluginPackage(ctx context.Context, req request) ([]action, []string, error) {
55 src, ok := parseGitHubRepoSource(req.Source)
56 if !ok {
57 return nil, nil, newErr(ErrUnsupportedKind, "plugin URL %q is not a GitHub repository", req.Source)
58 }
59 // Plan against the same source tree apply will install (a shallow clone
60 // via pluginSource). A manifest-only fetch cannot see conventional
61 // capability directories (skills/, commands/) or their warnings, so it
62 // under-reports the capability set — and the plan the user approves must
63 // describe exactly what apply installs.
64 root, commit, cleanup, err := t.pluginSource(ctx, req.Source, modeForPlugin(req.Mode))
65 if err != nil {
66 return nil, nil, err
67 }
68 pkg, warnings, err := pluginpkg.ParseDir(root)
69 if err == nil {
70 defer cleanup()
71 act, actionErr := t.pluginPackageAction(req, pkg, req.Source)
72 if actionErr != nil {
73 return nil, warnings, actionErr
74 }
75 act.Source = req.Source
76 // The commit joins the action and therefore the plan ID, so the approval
77 // fingerprints the exact snapshot; apply pins to it.
78 act.Commit = commit
79 return []action{act}, warnings, nil
80 }
81
82 actions, marketplaceWarnings, marketplaceErr := t.planClaudeMarketplace(ctx, req, src, root, commit)
83 warnings = append(warnings, marketplaceWarnings...)
84 if marketplaceErr != nil {
85 cleanup()
86 if errors.Is(marketplaceErr, ErrNoCompatibleCapabilities) {
87 return nil, warnings, marketplaceErr
88 }
89 return nil, warnings, newErr(ErrManifestMissing, "no plugin manifest or supported Claude marketplace found in GitHub repository %s/%s: plugin: %v; marketplace: %v", src.Owner, src.Repo, err, marketplaceErr)
90 }
91 if req.Apply {
92 // All marketplace entries come from this one immutable clone. Reusing it
93 // keeps a 12-plugin marketplace at one clone during apply and guarantees
94 // every copied plugin is the snapshot represented by act.Commit.
95 previousCleanup := actions[0].cleanup
96 actions[0].cleanup = func() {
97 if previousCleanup != nil {
98 previousCleanup()
99 }
100 cleanup()
101 }
102 return actions, warnings, nil
103 }
104 cleanup()
105 return actions, warnings, nil
106 }
107
108 func (t *installSourceTool) planClaudeMarketplace(ctx context.Context, req request, src githubRepoSource, root, commit string) ([]action, []string, error) {
109 manifestPath := filepath.Join(root, filepath.FromSlash(claudeMarketplaceManifest))
110 body, err := os.ReadFile(manifestPath)
111 if err != nil {
112 return nil, nil, err
113 }
114 var marketplace claudeMarketplace
115 if err := json.Unmarshal(body, &marketplace); err != nil {
116 return nil, nil, fmt.Errorf("parse %s: %w", claudeMarketplaceManifest, err)
117 }
118 if strings.TrimSpace(marketplace.Name) == "" {
119 return nil, nil, fmt.Errorf("%s has no marketplace name", claudeMarketplaceManifest)
120 }
121 if len(marketplace.Plugins) == 0 {
122 return nil, nil, fmt.Errorf("%s contains no plugins", claudeMarketplaceManifest)
123 }
124 if len(marketplace.Plugins) > maxMarketplacePlugins {
125 return nil, nil, fmt.Errorf("%s contains %d plugins; limit is %d", claudeMarketplaceManifest, len(marketplace.Plugins), maxMarketplacePlugins)
126 }
127
128 branch := strings.TrimSpace(src.Branch)
129 if branch == "" {
130 branch = currentPluginGitBranch(ctx, root)
131 }
132 if branch == "" {
133 branch = src.branches()[0]
134 }
135
136 selected := strings.TrimSpace(req.Name)
137 foundSelected := selected == ""
138 seen := make(map[string]bool, len(marketplace.Plugins))
139 var actions []action
140 keepActionResources := false
141 defer func() {
142 if !keepActionResources {
143 cleanupActionResources(actions)
144 }
145 }()
146 var warnings []string
147 for _, entry := range marketplace.Plugins {
148 entryName := strings.TrimSpace(entry.Name)
149 if selected != "" && entryName != selected {
150 continue
151 }
152 foundSelected = true
153 if entryName == "" {
154 warnings = append(warnings, "skipped Claude marketplace entry with an empty name")
155 continue
156 }
157 // Validate the name at plan time so a broken entry surfaces in the
158 // preview instead of failing its action mid-apply.
159 if !pluginpkg.IsValidName(entryName) {
160 if selected != "" {
161 return nil, warnings, fmt.Errorf("marketplace plugin %q is not a valid plugin name", entryName)
162 }
163 warnings = append(warnings, fmt.Sprintf("skipped Claude marketplace plugin %q: not a valid plugin name", entryName))
164 continue
165 }
166 if seen[entryName] {
167 return nil, warnings, fmt.Errorf("%s contains duplicate plugin name %q", claudeMarketplaceManifest, entryName)
168 }
169 seen[entryName] = true
170
171 var source string
172 var pluginRoot, pluginSource, actionCommit string
173 var entryCleanup func()
174 if err := json.Unmarshal(entry.Source, &source); err == nil {
175 if marketplaceSourceIsExternal(source) {
176 if selected != "" {
177 return nil, warnings, fmt.Errorf("marketplace plugin %q: external source %q must use a pinned URL object", entryName, source)
178 }
179 warnings = append(warnings, fmt.Sprintf("skipped Claude marketplace plugin %q: external source %q must use a pinned URL object", entryName, source))
180 continue
181 }
182 rel, relErr := claudeMarketplaceRelativePath(marketplace.Metadata.PluginRoot, source)
183 if relErr != nil {
184 return nil, warnings, fmt.Errorf("plugin %q: %w", entryName, relErr)
185 }
186 pluginRoot = filepath.Join(root, filepath.FromSlash(rel))
187 repoPath := joinURLPath(src.Path, rel)
188 pluginSource = fmt.Sprintf("https://github.com/%s/%s/tree/%s/%s", src.Owner, src.Repo, branch, repoPath)
189 actionCommit = commit
190 } else {
191 var pinned claudeMarketplaceURLSource
192 if objectErr := json.Unmarshal(entry.Source, &pinned); objectErr != nil || pinned.Source != "url" || !fullGitSHA.MatchString(strings.TrimSpace(pinned.SHA)) {
193 if selected != "" {
194 return nil, warnings, fmt.Errorf("marketplace plugin %q: object source requires source=url, a GitHub URL, and a full 40-character SHA", entryName)
195 }
196 warnings = append(warnings, fmt.Sprintf("skipped Claude marketplace plugin %q: object source is not a pinned GitHub URL", entryName))
197 continue
198 }
199 if _, ok := parseGitHubRepoSource(strings.TrimSpace(pinned.URL)); !ok {
200 if selected != "" {
201 return nil, warnings, fmt.Errorf("marketplace plugin %q: pinned URL %q is not a GitHub repository", entryName, pinned.URL)
202 }
203 warnings = append(warnings, fmt.Sprintf("skipped Claude marketplace plugin %q: pinned URL is not a GitHub repository", entryName))
204 continue
205 }
206 var resolvedCommit string
207 pluginRoot, resolvedCommit, entryCleanup, err = t.pluginSource(ctx, pinned.URL, "copy")
208 if err != nil {
209 return nil, warnings, fmt.Errorf("marketplace plugin %q: %w", entryName, err)
210 }
211 if !strings.EqualFold(resolvedCommit, pinned.SHA) {
212 if err := checkoutPluginCommit(ctx, pluginRoot, pinned.SHA); err != nil {
213 entryCleanup()
214 return nil, warnings, fmt.Errorf("marketplace plugin %q: %w", entryName, err)
215 }
216 }
217 pluginSource, actionCommit = strings.TrimSpace(pinned.URL), strings.ToLower(strings.TrimSpace(pinned.SHA))
218 }
219 pkg, pkgWarnings, err := pluginpkg.ParseDir(pluginRoot)
220 warnings = append(warnings, pkgWarnings...)
221 if err != nil {
222 if entryCleanup != nil {
223 entryCleanup()
224 }
225 return nil, warnings, fmt.Errorf("plugin %q: %w", entryName, err)
226 }
227 if pkg.Manifest.Name != entryName {
228 if entryCleanup != nil {
229 entryCleanup()
230 }
231 return nil, warnings, fmt.Errorf("marketplace plugin %q points to manifest named %q", entryName, pkg.Manifest.Name)
232 }
233 actionReq := req
234 actionReq.Name = ""
235 act, actionErr := t.pluginPackageAction(actionReq, pkg, pluginSource)
236 if actionErr != nil {
237 if entryCleanup != nil {
238 entryCleanup()
239 }
240 return nil, warnings, actionErr
241 }
242 act.Source = pluginSource
243 act.Commit = actionCommit
244 act.preparedRoot = pluginRoot
245 if entryCleanup != nil {
246 if req.Apply {
247 act.cleanup = entryCleanup
248 } else {
249 entryCleanup()
250 act.preparedRoot = ""
251 }
252 }
253 actions = append(actions, act)
254 }
255 if !foundSelected {
256 return nil, warnings, fmt.Errorf("%s does not contain plugin %q", claudeMarketplaceManifest, selected)
257 }
258 if len(actions) == 0 {
259 return nil, warnings, fmt.Errorf("%s contains no supported plugins", claudeMarketplaceManifest)
260 }
261 sort.Slice(actions, func(i, j int) bool { return actions[i].Name < actions[j].Name })
262 sort.Strings(warnings)
263 warnings = slices.Compact(warnings)
264 keepActionResources = true
265 return actions, warnings, nil
266 }
267
268 func claudeMarketplaceRelativePath(pluginRoot, source string) (string, error) {
269 pluginRoot = strings.TrimSpace(pluginRoot)
270 if pluginRoot == "" {
271 pluginRoot = "."
272 }
273 cleanRoot, err := cleanMarketplaceRelPath("metadata.pluginRoot", pluginRoot)
274 if err != nil {
275 return "", err
276 }
277 cleanSource, err := cleanMarketplaceRelPath("source", source)
278 if err != nil {
279 return "", err
280 }
281 rel := filepath.Clean(filepath.Join(cleanRoot, cleanSource))
282 if rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
283 return "", fmt.Errorf("source %q escapes or does not identify a plugin subdirectory", source)
284 }
285 return filepath.ToSlash(rel), nil
286 }
287
288 // cleanMarketplaceRelPath normalizes one relative-path field of a marketplace
289 // entry. Real marketplaces spell paths both as "./plugins/example" and as the
290 // bare "plugins/example", so both are accepted; absolute and drive-qualified
291 // paths are rejected before the join so they can never re-anchor the lookup
292 // outside the clone.
293 func cleanMarketplaceRelPath(label, value string) (string, error) {
294 value = strings.TrimSpace(value)
295 if value == "" {
296 return "", fmt.Errorf("%s is empty", label)
297 }
298 cleaned := filepath.Clean(filepath.FromSlash(strings.TrimPrefix(value, "./")))
299 if filepath.IsAbs(cleaned) || filepath.VolumeName(cleaned) != "" {
300 return "", fmt.Errorf("%s %q must be a relative path inside the marketplace repository", label, value)
301 }
302 return cleaned, nil
303 }
304
305 // marketplaceSourceIsExternal reports whether a string source points outside
306 // the marketplace repository (a URL or scp-like git address) rather than at a
307 // relative path inside it.
308 func marketplaceSourceIsExternal(source string) bool {
309 source = strings.TrimSpace(source)
310 return strings.Contains(source, "://") || strings.HasPrefix(source, "git@")
311 }
312
313 func currentPluginGitBranch(ctx context.Context, root string) string {
314 cmd := pluginGitCommand(ctx, "-C", root, "branch", "--show-current")
315 out, err := cmd.Output()
316 if err != nil {
317 return ""
318 }
319 return strings.TrimSpace(string(out))
320 }
321
322 // pluginSource resolves a plugin source to an on-disk tree. Both the plan and
323 // apply phases go through this single function so their views can never
324 // diverge (the approval-contract guarantee); for git sources it also reports
325 // the resolved commit SHA ("" for local directories).
326 func (t *installSourceTool) pluginSource(ctx context.Context, source, mode string) (string, string, func(), error) {
327 if t.preparePlugin != nil {
328 return t.preparePlugin(ctx, source, mode)
329 }
330 return t.preparePluginSource(ctx, source, mode)
331 }
332
333 func (t *installSourceTool) pluginPackageAction(req request, pkg pluginpkg.Package, source string) (action, error) {
334 name := strings.TrimSpace(req.Name)
335 if name == "" {
336 name = pkg.Manifest.Name
337 }
338 root := ""
339 if t.reasonixHome != "" {
340 root = pluginpkg.InstallRoot(t.reasonixHome, name)
341 }
342 skills, commands, hooks, mcp := pkg.CapabilityCounts()
343 agents := pkg.Inventory().Agents
344 if pkg.ManifestKind != "reasonix" && skills+commands+hooks+mcp+len(agents) == 0 {
345 return action{}, newErr(ErrNoCompatibleCapabilities, "plugin %q has no Reasonix-compatible capabilities; skipped: %v", name, pkg.Compatibility.Skipped)
346 }
347 agentNames := make([]string, 0, len(agents))
348 for _, agent := range agents {
349 agentNames = append(agentNames, agent.Name)
350 }
351 a := action{
352 Kind: "plugin",
353 Action: "install_plugin_package",
354 Name: name,
355 Source: source,
356 Target: root,
357 Scope: "global",
358 Mode: modeForPlugin(req.Mode),
359 ConfigPath: pluginpkg.StatePath(t.reasonixHome),
360 Skills: pkg.Manifest.Skills,
361 SkillCount: skills,
362 Agents: agentNames,
363 AgentCount: len(agentNames),
364 Commands: pkg.Manifest.Commands,
365 CommandCount: commands,
366 ManifestKind: pkg.ManifestKind,
367 HookCount: hooks,
368 ToolCount: mcp,
369 Compatibility: pkg.Compatibility.Status,
370 MappedCapabilities: append([]string(nil), pkg.Compatibility.Mapped...),
371 SkippedCapabilities: append([]pluginpkg.CompatibilityIssue(nil), pkg.Compatibility.Skipped...),
372 Version: pkg.Manifest.Version,
373 PromptCount: pkg.PromptCount(),
374 ThemeCount: pkg.ThemeCount(),
375 Runtime: runtimePlanInfo(pkg.Manifest.Runtime),
376 RiskLevel: RiskMedium,
377 RiskReasons: []string{"installs a plugin package that can add skills, commands, hooks, and MCP servers"},
378 }
379 if a.Mode == "link" {
380 a.RiskReasons = append(a.RiskReasons, "links a plugin package from a mutable local directory")
381 }
382 if hooks > 0 {
383 a.RiskLevel = RiskHigh
384 a.RiskReasons = append(a.RiskReasons, "registers shell hooks that execute during Reasonix sessions")
385 }
386 if mcp > 0 {
387 a.RiskLevel = RiskHigh
388 a.RiskReasons = append(a.RiskReasons, "adds MCP servers that can change provider-visible tool schemas")
389 }
390 if a.Runtime != nil {
391 a.RiskLevel = RiskHigh
392 a.RiskReasons = append(a.RiskReasons, "FULL TRUST: declares a runtime process ("+pluginpkg.RuntimeCommandLine(pkg.Manifest.Runtime)+") that runs inside Reasonix — it can read the full session and environment, bypass permissions, and operate this machine directly")
393 }
394 sort.Strings(a.Skills)
395 sort.Strings(a.Agents)
396 return a, nil
397 }
398
399 // runtimePlanInfo converts a manifest runtime declaration into its plan
400 // form. nil in, nil out: legacy packages carry no runtime field at all.
401 func runtimePlanInfo(rt *pluginpkg.RuntimeSpec) *RuntimePlanInfo {
402 if rt == nil {
403 return nil
404 }
405 return &RuntimePlanInfo{
406 Command: rt.Command,
407 Args: append([]string(nil), rt.Args...),
408 Intercepts: append([]string(nil), rt.Intercepts...),
409 Replaces: append([]string(nil), rt.Replaces...),
410 Capabilities: append([]string(nil), rt.Capabilities...),
411 FullTrust: true,
412 }
413 }
414
415 func modeForPlugin(mode string) string {
416 if mode == "link" {
417 return "link"
418 }
419 return "copy"
420 }
421
422 func (t *installSourceTool) applyInstallPluginPackage(ctx context.Context, req request, act *action) error {
423 if t.reasonixHome == "" {
424 return newErr(ErrSourceUnreadable, "plugin install requires a Reasonix home directory")
425 }
426 if !pluginpkg.IsValidName(act.Name) {
427 return newErr(ErrInvalidManifest, "invalid plugin name %q", act.Name)
428 }
429 target := pluginpkg.InstallRoot(t.reasonixHome, act.Name)
430 sourceRoot, commit, cleanup := act.preparedRoot, act.Commit, func() {}
431 if sourceRoot == "" {
432 var err error
433 sourceRoot, commit, cleanup, err = t.pluginSource(ctx, act.Source, act.Mode)
434 if err != nil {
435 return err
436 }
437 }
438 defer cleanup()
439 if act.Commit != "" && commit != act.Commit {
440 // The source moved between the approved plan and this resolution; pin
441 // the clone back to the approved snapshot so what installs is exactly
442 // what was reviewed.
443 if err := checkoutPluginCommit(ctx, sourceRoot, act.Commit); err != nil {
444 return newErr(ErrApprovalDenied, "plugin source changed since the approved plan (approved commit %s, found %s) and the approved snapshot could not be restored: %v; re-run without apply to review the new plan", act.Commit, commit, err)
445 }
446 }
447 pkg, warnings, err := pluginpkg.ParseDir(sourceRoot)
448 if err != nil {
449 return newErr(ErrInvalidManifest, "%v", err)
450 }
451 if pkg.ManifestKind != "reasonix" {
452 skills, commands, hooks, mcp := pkg.CapabilityCounts()
453 if skills+commands+hooks+mcp+pkg.AgentCount() == 0 {
454 return newErr(ErrInvalidManifest, "plugin %q no longer has any Reasonix-compatible capabilities", act.Name)
455 }
456 }
457 act.Warnings = append(act.Warnings, warnings...)
458 if pkg.Manifest.Name != act.Name && strings.TrimSpace(req.Name) == "" {
459 return newErr(ErrInvalidManifest, "planned plugin name %q but source now reports %q", act.Name, pkg.Manifest.Name)
460 }
461 if act.Mode == "link" {
462 if !isLinkTargetSafe(sourceRoot, t.home, t.root) {
463 return newErr(ErrUnsafeLinkTarget, "plugin source %s is outside %s and %s", sourceRoot, t.root, t.home)
464 }
465 if err := replaceSymlink(target, sourceRoot, req.Replace); err != nil {
466 return err
467 }
468 } else {
469 if err := installCopiedPlugin(pkg, sourceRoot, target, req.Replace); err != nil {
470 return err
471 }
472 }
473 installed := pluginpkg.InstalledPlugin{
474 Name: act.Name,
475 Source: act.Source,
476 Root: pluginpkg.RelativeRoot(t.reasonixHome, target),
477 Version: pkg.Manifest.Version,
478 Description: pkg.Manifest.Description,
479 ManifestKind: pkg.ManifestKind,
480 Enabled: true,
481 Commit: strings.ToLower(strings.TrimSpace(commit)),
482 }
483 if act.Mode == "link" {
484 installed.Root = sourceRoot
485 }
486 if err := pluginpkg.Upsert(t.reasonixHome, installed); err != nil {
487 return err
488 }
489 act.Target = target
490 act.ManifestKind = pkg.ManifestKind
491 act.Version = pkg.Manifest.Version
492 act.SkillCount, act.CommandCount, act.HookCount, act.ToolCount = pkg.CapabilityCounts()
493 act.AgentCount = pkg.AgentCount()
494 act.PromptCount, act.ThemeCount = pkg.PromptCount(), pkg.ThemeCount()
495 act.Runtime = runtimePlanInfo(pkg.Manifest.Runtime)
496 act.Compatibility = pkg.Compatibility.Status
497 act.MappedCapabilities = append([]string(nil), pkg.Compatibility.Mapped...)
498 act.SkippedCapabilities = append([]pluginpkg.CompatibilityIssue(nil), pkg.Compatibility.Skipped...)
499 return nil
500 }
501
502 func (t *installSourceTool) preparePluginSource(ctx context.Context, source, mode string) (string, string, func(), error) {
503 source = strings.TrimSpace(source)
504 if after, ok := strings.CutPrefix(source, "git:github.com/"); ok {
505 source = "https://github.com/" + after
506 }
507 if isURL(source) {
508 src, ok := parseGitHubRepoSource(source)
509 if !ok {
510 return "", "", func() {}, newErr(ErrUnsupportedKind, "plugin URL %q is not a GitHub repository", source)
511 }
512 tmp, err := os.MkdirTemp("", "reasonix-plugin-*")
513 if err != nil {
514 return "", "", func() {}, err
515 }
516 cloneURL := fmt.Sprintf("https://github.com/%s/%s.git", src.Owner, src.Repo)
517 args := []string{"clone", "--depth=1"}
518 if src.Branch != "" {
519 args = append(args, "--branch", src.Branch)
520 }
521 args = append(args, cloneURL, tmp)
522 cmd := pluginGitCommand(ctx, args...)
523 if out, err := cmd.CombinedOutput(); err != nil {
524 _ = os.RemoveAll(tmp)
525 return "", "", func() {}, newErr(ErrSourceUnreadable, "git clone failed: %v: %s", err, strings.TrimSpace(string(out)))
526 }
527 commit := ""
528 rev := pluginGitCommand(ctx, "-C", tmp, "rev-parse", "HEAD")
529 if out, err := rev.Output(); err == nil {
530 commit = strings.TrimSpace(string(out))
531 }
532 root, err := pluginRootFromClone(tmp, src.Path)
533 if err != nil {
534 _ = os.RemoveAll(tmp)
535 return "", "", func() {}, err
536 }
537 return root, commit, func() { _ = os.RemoveAll(tmp) }, nil
538 }
539 path := t.resolvePath(source)
540 if mode == "link" {
541 return path, "", func() {}, nil
542 }
543 return path, "", func() {}, nil
544 }
545
546 func pluginRootFromClone(cloneRoot, repoPath string) (string, error) {
547 cloneRoot = filepath.Clean(cloneRoot)
548 if repoPath == "" {
549 return cloneRoot, nil
550 }
551 if strings.Contains(repoPath, "\\") {
552 return "", newErr(ErrUnsupportedKind, "plugin repository path %q is not a safe relative path", repoPath)
553 }
554 rel := filepath.FromSlash(repoPath)
555 if !filepath.IsLocal(rel) {
556 return "", newErr(ErrUnsupportedKind, "plugin repository path %q escapes the cloned repository", repoPath)
557 }
558 root := filepath.Join(cloneRoot, rel)
559 resolvedClone, err := filepath.EvalSymlinks(cloneRoot)
560 if err != nil {
561 return "", newErr(ErrSourceUnreadable, "cannot resolve cloned plugin repository: %v", err)
562 }
563 resolvedRoot, err := filepath.EvalSymlinks(root)
564 if err != nil {
565 return "", newErr(ErrSourceUnreadable, "plugin repository path %q is not readable: %v", repoPath, err)
566 }
567 within, err := filepath.Rel(resolvedClone, resolvedRoot)
568 if err != nil || !filepath.IsLocal(within) {
569 return "", newErr(ErrUnsupportedKind, "plugin repository path %q escapes the cloned repository", repoPath)
570 }
571 return resolvedRoot, nil
572 }
573
574 // verifyCopiedCapabilities re-parses the installed copy and requires its
575 // capability counts to match the source tree the plan described. Discovery
576 // follows symlinks but copy mode can only materialize links that stay inside
577 // the package, so an unmaterializable link would otherwise silently install
578 // fewer skills/commands than the approval covered.
579 func verifyCopiedCapabilities(src pluginpkg.Package, target string) error {
580 installed, _, err := pluginpkg.ParseDir(target)
581 if err != nil {
582 return newErr(ErrInvalidManifest, "installed plugin tree failed to re-parse: %v", err)
583 }
584 ss, sc, sh, sm := src.CapabilityCounts()
585 is, ic, ih, im := installed.CapabilityCounts()
586 sa, ia := src.AgentCount(), installed.AgentCount()
587 if ss != is || sc != ic || sh != ih || sm != im || sa != ia {
588 return newErr(ErrInvalidManifest,
589 "installed copy resolves to %d skills / %d agents / %d commands / %d hooks / %d MCP servers but the approved plan counted %d/%d/%d/%d/%d — the package likely uses symlinks copy mode cannot materialize safely; retry with mode=link or fix the package layout",
590 is, ia, ic, ih, im, ss, sa, sc, sh, sm)
591 }
592 return nil
593 }
594
595 // checkoutPluginCommit pins a fresh clone to the approved commit when its HEAD
596 // has moved past it. GitHub serves full-SHA fetches, so the approved snapshot
597 // stays reachable after ordinary pushes; a history rewrite that discarded it
598 // fails here — exactly the case where the user must re-review the plan.
599 func checkoutPluginCommit(ctx context.Context, cloneRoot, commit string) error {
600 fetch := pluginGitCommand(ctx, "-C", cloneRoot, "fetch", "--depth=1", "origin", commit)
601 if out, err := fetch.CombinedOutput(); err != nil {
602 return fmt.Errorf("fetch approved commit %s: %w: %s", commit, err, strings.TrimSpace(string(out)))
603 }
604 co := pluginGitCommand(ctx, "-C", cloneRoot, "checkout", "--detach", commit)
605 if out, err := co.CombinedOutput(); err != nil {
606 return fmt.Errorf("checkout approved commit %s: %w: %s", commit, err, strings.TrimSpace(string(out)))
607 }
608 return nil
609 }
610
611 func pluginGitCommand(ctx context.Context, args ...string) *exec.Cmd {
612 // Preserve repository bytes across platforms. A user's global autocrlf
613 // setting must not rewrite JSON/scripts on Windows after the user approved
614 // the exact source commit.
615 return gitcmd.CommandWithConfig(ctx, "", []string{"core.autocrlf=false"}, args...)
616 }
617
618 // installCopiedPlugin copies sourceRoot into a staging directory next to
619 // target, verifies the staged tree resolves to the capability set the plan
620 // approved, and only then swaps it into place with a backup-protected rename.
621 // Any failure before the swap — copy error, capability mismatch — leaves an
622 // existing installation completely intact, so a bad update can never destroy
623 // the working version it was meant to replace.
624 func installCopiedPlugin(pkg pluginpkg.Package, sourceRoot, target string, replace bool) error {
625 if _, err := os.Lstat(target); err == nil && !replace {
626 return newErr(ErrAlreadyExists, "plugin package already exists at %s; retry with replace=true to update it", target)
627 }
628 if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
629 return err
630 }
631 staging, err := os.MkdirTemp(filepath.Dir(target), "."+filepath.Base(target)+".staging-")
632 if err != nil {
633 return err
634 }
635 defer os.RemoveAll(staging)
636 if err := copyDir(sourceRoot, staging); err != nil {
637 return err
638 }
639 // Fail closed when the copied tree resolves to a different capability set
640 // than the plan the user approved — e.g. a symlink copyDir could not
641 // materialize safely. A silent gap here would install less than reviewed.
642 if err := verifyCopiedCapabilities(pkg, staging); err != nil {
643 return err
644 }
645 if err := os.Chmod(staging, 0o755); err != nil { // MkdirTemp creates 0700
646 return err
647 }
648 // Swap staged tree into place. The backup rename keeps the previous
649 // install restorable until the new tree has landed; both renames stay on
650 // one filesystem (same parent dir), so each is atomic. The backup name
651 // derives from the staging dir: dot-prefixed and randomized, it can never
652 // pass IsValidName, so it cannot collide with a sibling plugin's install
653 // dir (plugin names may legally contain dots, e.g. "foo.pre-replace") and
654 // needs no pre-cleanup that could delete such a neighbor.
655 backup := staging + ".old"
656 hadOld := false
657 if _, err := os.Lstat(target); err == nil {
658 hadOld = true
659 if err := os.Rename(target, backup); err != nil {
660 return err
661 }
662 }
663 if err := os.Rename(staging, target); err != nil {
664 if hadOld {
665 _ = os.Rename(backup, target) // restore the previous install
666 }
667 return err
668 }
669 if hadOld {
670 _ = os.RemoveAll(backup)
671 }
672 return nil
673 }
674
675 func replaceSymlink(target, sourceRoot string, replace bool) error {
676 if _, err := os.Lstat(target); err == nil {
677 if !replace {
678 return newErr(ErrAlreadyExists, "plugin package already exists at %s; retry with replace=true to update it", target)
679 }
680 if err := os.RemoveAll(target); err != nil {
681 return err
682 }
683 }
684 if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil {
685 return err
686 }
687 return os.Symlink(sourceRoot, target)
688 }
689
690 func (t *installSourceTool) applyRemovePluginPackage(_ request, act *action) error {
691 installed, ok, err := pluginpkg.Remove(t.reasonixHome, act.Name)
692 if err != nil || !ok {
693 return err
694 }
695 if err := repairPluginModelRefs(act.Name); err != nil {
696 return err
697 }
698 root := pluginpkg.ResolveRoot(t.reasonixHome, installed.Root)
699 if t.onDisconnect != nil {
700 if pkg, _, err := pluginpkg.ParseDir(root); err == nil {
701 names := make([]string, 0, len(pkg.Manifest.MCPServers))
702 for name := range pkg.Manifest.MCPServers {
703 names = append(names, name)
704 }
705 sort.Strings(names)
706 for _, name := range names {
707 t.onDisconnect(name)
708 }
709 }
710 }
711 pluginsDir := pluginpkg.PluginsDir(t.reasonixHome)
712 if rel, err := filepath.Rel(pluginsDir, root); err == nil && rel != "." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) && rel != ".." {
713 if err := os.RemoveAll(root); err != nil {
714 return err
715 }
716 }
717 return nil
718 }
719
720 // repairPluginModelRefs moves user-config model refs off a removed plugin,
721 // since boot rejects an unknown default_model. Project configs are left alone:
722 // a project naming a plugin model made that choice itself.
723 func repairPluginModelRefs(pluginID string) error {
724 path := config.UserConfigPath()
725 if strings.TrimSpace(path) == "" {
726 return nil
727 }
728 if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) {
729 return nil
730 }
731 // A strict read-only probe leaves an unaffected or malformed file untouched;
732 // credentials load so the fallback is a provider the user can reach.
733 probe, err := config.LoadForEditReadOnlyStrict(path)
734 if err != nil || probe == nil || !probe.RemovePluginModelRefs(pluginID) {
735 return nil
736 }
737 if err := config.EditConfigFile(path, func(fresh *config.Config) error {
738 fresh.RemovePluginModelRefs(pluginID)
739 return nil
740 }); err != nil {
741 return fmt.Errorf("repair model refs for plugin %q: %w", pluginID, err)
742 }
743 return nil
744 }
745
745 lines GO