package plugin import ( "context" "errors" "fmt" "sort" "strings" "sync" "time" "github.com/Nwflower/reims-go/internal/downloader" "github.com/Nwflower/reims-go/internal/i18n" ) // Activator runs when a plugin transitions to active; all side effects must be // attached to scope so they are cleanly rolled back on failure or disable. type Activator func(ctx context.Context, scope *Scope) error // InUseChecker checks whether a plugin (e.g. a guest driver or runtime provider) // is currently referenced by any VM. Returning a non-nil error is treated as // "in use" (fail-closed, §4.1). type InUseChecker func(pluginID string) (inUse bool, reason string, err error) // PluginDef defines a compiled-in builtin or external/bundled plugin registered // in the unified Registry (§3.1, §4.1). type PluginDef struct { Manifest Manifest Source SourceKind Trust TrustLevel InstallDir string EntryPath string EntryHash string LogPath string Removable bool Activate Activator // Desired controls whether Reconcile wants this plugin active. Desired bool // ApprovedPermissions records permissions explicitly approved by the user. ApprovedPermissions []string // NeedsApproval indicates high-risk permissions or community L3 awaiting approval. NeedsApproval bool // System marks a builtin that Reims-Go cannot work without: it is always // desired and cannot be disabled or removed. System bool } type serviceRecord struct { pluginID string version string instance any } type pluginEntry struct { def PluginDef state State errMsg string degradedReason string consecutiveErrs int scope *Scope updatedAt time.Time } // CommandHandler handles command.invoke requests. type CommandHandler func(ctx context.Context, args map[string]any) (any, error) // DiagnosticsCollector gathers diagnostic info for a VM (empty name = host-level). type DiagnosticsCollector func(ctx context.Context, vmName string) (DiagnosticsEntry, error) // RegisteredCommand binds a command contribution to its executable handler. type RegisteredCommand struct { Contribution CommandContribution Handler CommandHandler } // RegisteredDiagnostics binds a diagnostics contribution to its collector. type RegisteredDiagnostics struct { Contribution DiagnosticsContribution Collector DiagnosticsCollector } // RegisteredDownloader binds a downloader contribution to its provider. type RegisteredDownloader struct { Contribution DownloaderContribution Provider downloader.Provider } // Registry is the unified extension-point and lifecycle kernel for both // compiled-in builtins and external/bundled plugins. type Registry struct { reconcileMu sync.Mutex // serializes Reconcile passes mu sync.RWMutex entries map[string]*pluginEntry services map[string]serviceRecord // serviceName -> record inUseChecker InUseChecker busyChecker InUseChecker onChange []func() logger func(source, line string) localeFn func() i18n.Locale // Extension point tables. themes map[string]ThemeContribution activeThemeID string uiScripts map[string]UIScriptContribution locales map[string][]LocaleContribution inputFilters []InputFilterContribution vmTemplates []VMTemplateContribution runtimeSources []RuntimeSourceContribution runtimeKinds map[string]RuntimeKindContribution guestDrivers map[string]any // holds driver.Driver without circular imports downloaders map[string]RegisteredDownloader hooks *HookBus commands map[string]RegisteredCommand menus []MenuContribution vmCards []VMCardContribution settingsPages []SettingsPageContribution statusItems []StatusItemContribution panels []PanelContribution views []ViewContribution imageSources []ImageSourceContribution diagnostics []RegisteredDiagnostics } // NewRegistry creates an initialized plugin registry. func NewRegistry(logger func(source, line string)) *Registry { r := &Registry{ entries: make(map[string]*pluginEntry), services: make(map[string]serviceRecord), logger: logger, themes: make(map[string]ThemeContribution), uiScripts: make(map[string]UIScriptContribution), locales: make(map[string][]LocaleContribution), runtimeKinds: make(map[string]RuntimeKindContribution), guestDrivers: make(map[string]any), downloaders: make(map[string]RegisteredDownloader), commands: make(map[string]RegisteredCommand), } r.hooks = NewHookBus(r) return r } // Hooks returns the registry's hook dispatch bus. func (r *Registry) Hooks() *HookBus { return r.hooks } // SetInUseChecker installs the guard that prevents removing plugins whose // drivers still own VMs. Disabling is guarded by SetBusyChecker instead: // a disabled plugin keeps its VMs on disk, shown as driver_unavailable. func (r *Registry) SetInUseChecker(fn InUseChecker) { r.mu.Lock() r.inUseChecker = fn r.mu.Unlock() } // SetBusyChecker installs the guard that prevents disabling a plugin while // work it owns is live (for guest drivers: a VM that is not stopped). func (r *Registry) SetBusyChecker(fn InUseChecker) { r.mu.Lock() r.busyChecker = fn r.mu.Unlock() } // OnChange subscribes to registry state or extension-point changes. func (r *Registry) OnChange(fn func()) func() { if fn == nil { return func() {} } r.mu.Lock() r.onChange = append(r.onChange, fn) idx := len(r.onChange) - 1 r.mu.Unlock() return func() { r.mu.Lock() if idx < len(r.onChange) { r.onChange[idx] = nil } r.mu.Unlock() } } func (r *Registry) notifyChange() { r.mu.RLock() cbs := append([]func(){}, r.onChange...) r.mu.RUnlock() for _, cb := range cbs { if cb != nil { safeInvoke(cb) } } } func (r *Registry) logf(source, format string, args ...any) { if r.logger != nil { r.logger(source, fmt.Sprintf(format, args...)) } } // SetLocaleProvider configures how Registry resolves the active host locale. func (r *Registry) SetLocaleProvider(fn func() i18n.Locale) { r.mu.Lock() r.localeFn = fn r.mu.Unlock() } func (r *Registry) currentLocale() i18n.Locale { r.mu.RLock() fn := r.localeFn r.mu.RUnlock() if fn != nil { return i18n.EffectiveLocale(fn()) } return i18n.Detect() } // Register adds or updates a plugin definition. Call Reconcile to apply activation changes. func (r *Registry) Register(def PluginDef) error { if strings.TrimSpace(def.Manifest.ID) == "" { return errors.New("plugin manifest missing id") } if def.Manifest.Version == "" { def.Manifest.Version = "0.0.0" } if def.System { def.Desired = true } var oldScope *Scope r.mu.Lock() if existing, ok := r.entries[def.Manifest.ID]; ok { // If upgrading an already-active plugin, tear down the old scope so // Reconcile activates the new definition cleanly. if existing.scope != nil && (existing.def.Manifest.Version != def.Manifest.Version || existing.def.InstallDir != def.InstallDir || existing.def.EntryHash != def.EntryHash) { oldScope = existing.scope existing.scope = nil existing.state = StateOff } existing.def = def existing.updatedAt = time.Now() } else { r.entries[def.Manifest.ID] = &pluginEntry{ def: def, state: StateOff, updatedAt: time.Now(), } } r.mu.Unlock() if oldScope != nil { oldScope.Dispose() } return nil } // Unregister disposes and removes a plugin from the registry if not in use. func (r *Registry) Unregister(ctx context.Context, id string) error { if err := r.checkNotInUse(id); err != nil { return err } r.mu.Lock() e, ok := r.entries[id] if !ok { r.mu.Unlock() return nil } e.def.Desired = false r.mu.Unlock() r.Reconcile(ctx) r.mu.Lock() delete(r.entries, id) r.mu.Unlock() r.notifyChange() return nil } // SetDesired enables or disables a plugin and reconciles dependencies. func (r *Registry) SetDesired(ctx context.Context, id string, enabled bool) error { if !enabled { r.mu.RLock() e, ok := r.entries[id] system := ok && e.def.System r.mu.RUnlock() if system { return fmt.Errorf("plugin %q is part of Reims-Go core and cannot be disabled", id) } if err := r.checkNotBusy(id); err != nil { return err } } r.mu.Lock() e, ok := r.entries[id] if !ok { r.mu.Unlock() return fmt.Errorf("plugin %q not found", id) } if enabled && e.def.NeedsApproval { r.mu.Unlock() return fmt.Errorf("plugin %q requires permission approval before enabling", id) } e.def.Desired = enabled if enabled { // Allow retrying a previously failed plugin on explicit re-enable. if e.state == StateFailed { e.state = StateOff } e.errMsg = "" e.degradedReason = "" e.consecutiveErrs = 0 } r.mu.Unlock() r.Reconcile(ctx) return nil } func (r *Registry) checkNotInUse(id string) error { r.mu.RLock() checker := r.inUseChecker r.mu.RUnlock() if checker == nil { return nil } inUse, reason, err := checker(id) if err != nil { // Fail-closed: query failure is treated as in-use. return fmt.Errorf("cannot verify whether plugin %q is in use (treated as in use): %w", id, err) } if inUse { if reason == "" { reason = "referenced by existing VMs" } return fmt.Errorf("plugin %q is in use and cannot be removed: %s", id, reason) } return nil } func (r *Registry) checkNotBusy(id string) error { r.mu.RLock() checker := r.busyChecker r.mu.RUnlock() if checker == nil { return nil } busy, reason, err := checker(id) if err != nil { // Fail-closed like checkNotInUse: an unknown VM state blocks disabling. return fmt.Errorf("cannot verify whether plugin %q has running VMs (treated as running): %w", id, err) } if busy { if reason == "" { reason = "a VM is running" } return fmt.Errorf("plugin %q cannot be disabled while its VMs run; stop them first: %s", id, reason) } return nil } // Reconcile brings active plugins into convergence with desired state and // service dependency graph using close-then-open fixed-point iteration. func (r *Registry) Reconcile(ctx context.Context) { if ctx == nil { ctx = context.Background() } r.reconcileMu.Lock() defer r.reconcileMu.Unlock() // Dispose leaves first (plugins that no other active plugin depends on) so // dependent consumers always unload before their service providers. for { var toDispose []*pluginEntry r.mu.RLock() requiredBy := make(map[string][]*pluginEntry) scheduled := make(map[string]bool) var allDue []*pluginEntry for id, e := range r.entries { if e.scope == nil { continue } if !e.def.Desired || !r.requirementsSatisfiedLocked(e.def.Manifest.Requires) { allDue = append(allDue, e) scheduled[id] = true } for _, req := range e.def.Manifest.Requires { if req.Optional { continue } if svc, ok := r.services[req.Service]; ok && svc.pluginID != id { requiredBy[svc.pluginID] = append(requiredBy[svc.pluginID], e) } } } // A provider scheduled to close still publishes its service. Include // its required consumers before selecting leaves, even when their // requirements are currently satisfied. for i := 0; i < len(allDue); i++ { for _, consumer := range requiredBy[allDue[i].def.Manifest.ID] { id := consumer.def.Manifest.ID if !scheduled[id] { scheduled[id] = true allDue = append(allDue, consumer) } } } for _, e := range allDue { if len(requiredBy[e.def.Manifest.ID]) == 0 { toDispose = append(toDispose, e) } } // Break cycles if every due plugin is mutually depended upon. if len(toDispose) == 0 && len(allDue) > 0 { toDispose = allDue } r.mu.RUnlock() if len(toDispose) == 0 { break } // Deterministic reverse-ID order within the same topological wave. sort.Slice(toDispose, func(i, j int) bool { return toDispose[i].def.Manifest.ID > toDispose[j].def.Manifest.ID }) for _, e := range toDispose { r.disposeEntry(e) } } // Activate desired plugins whose pluginApi and required services are satisfied. for { var candidates []*pluginEntry r.mu.RLock() for _, e := range r.entries { if !e.def.Desired || e.scope != nil || e.state == StateFailed { continue } if e.def.NeedsApproval { continue } if r.requirementsSatisfiedLocked(e.def.Manifest.Requires) { candidates = append(candidates, e) } } r.mu.RUnlock() if len(candidates) == 0 { break } // Builtins activate before external plugins; tie-break by ID. sort.Slice(candidates, func(i, j int) bool { bi := candidates[i].def.Source == SourceBuiltin bj := candidates[j].def.Source == SourceBuiltin if bi != bj { return bi } return candidates[i].def.Manifest.ID < candidates[j].def.Manifest.ID }) progressed := false for _, e := range candidates { if r.activateEntry(ctx, e) { progressed = true } } if !progressed { break } } // Mark desired plugins still waiting on unmet dependencies as pending. r.mu.Lock() for _, e := range r.entries { if e.def.Desired && e.scope == nil && e.state != StateFailed { if !e.def.NeedsApproval && !r.requirementsSatisfiedLocked(e.def.Manifest.Requires) { e.state = StatePending } else if !e.def.Desired { e.state = StateOff } } } r.mu.Unlock() r.notifyChange() } func (r *Registry) requirementsSatisfiedLocked(reqs []ServiceRequirement) bool { for _, req := range reqs { if req.Optional { continue } svc, ok := r.services[req.Service] if !ok { return false } if req.Version != "" && !MatchesRange(svc.version, req.Version) { return false } } return true } func (r *Registry) disposeEntry(e *pluginEntry) { r.mu.Lock() sc := e.scope e.scope = nil if e.state != StateFailed { if e.def.Desired { e.state = StatePending } else { e.state = StateOff e.errMsg = "" e.degradedReason = "" } } e.updatedAt = time.Now() r.mu.Unlock() if sc != nil { sc.Dispose() } } func (r *Registry) activateEntry(ctx context.Context, e *pluginEntry) bool { id := e.def.Manifest.ID // Check pluginApi compatibility before activating (§4.1). if reqAPI := strings.TrimSpace(e.def.Manifest.Engines.PluginAPI); reqAPI != "" { if !MatchesRange(PluginAPIVersion, reqAPI) { r.mu.Lock() e.state = StateFailed e.errMsg = fmt.Sprintf("incompatible pluginApi: requires %s, host provides %s", reqAPI, PluginAPIVersion) e.updatedAt = time.Now() r.mu.Unlock() r.logf("plugin", "%s failed: %s", id, e.errMsg) return false } } sc := newScope(id, r) var activateErr error func() { defer func() { if rec := recover(); rec != nil { activateErr = fmt.Errorf("panic during activation: %v", rec) } }() // Auto-register declarative L1 contributions from manifest. r.registerManifestContributions(sc, e.def.Manifest) if e.def.Activate != nil { activateErr = e.def.Activate(ctx, sc) } }() if activateErr != nil { // Roll back everything registered so far in LIFO order (§4.1). sc.Dispose() r.mu.Lock() e.state = StateFailed e.errMsg = activateErr.Error() e.scope = nil e.updatedAt = time.Now() r.mu.Unlock() r.logf("plugin", "%s activation failed (rolled back): %v", id, activateErr) return false } r.mu.Lock() e.scope = sc e.state = StateActive e.errMsg = "" e.degradedReason = "" e.consecutiveErrs = 0 e.updatedAt = time.Now() r.mu.Unlock() return true } func (r *Registry) registerManifestContributions(sc *Scope, m Manifest) { pid := m.ID for _, th := range m.Contributes.Themes { th.PluginID = pid r.RegisterTheme(sc, th) } for _, us := range m.Contributes.UIScripts { us.PluginID = pid r.RegisterUIScript(sc, us) } for _, lc := range m.Contributes.Locales { lc.PluginID = pid r.RegisterLocale(sc, lc) } for _, flt := range m.Contributes.InputFilters { flt.PluginID = pid r.RegisterInputFilter(sc, flt) } for _, tpl := range m.Contributes.VMTemplates { tpl.PluginID = pid r.RegisterVMTemplate(sc, tpl) } for _, rs := range m.Contributes.RuntimeSources { rs.PluginID = pid r.RegisterRuntimeSource(sc, rs) } for _, rk := range m.Contributes.RuntimeKinds { rk.PluginID = pid r.RegisterRuntimeKind(sc, rk) } for _, menu := range m.Contributes.Menus { menu.PluginID = pid r.RegisterMenu(sc, menu) } for _, card := range m.Contributes.VMCards { card.PluginID = pid r.RegisterVMCard(sc, card) } for _, sp := range m.Contributes.SettingsPages { sp.PluginID = pid r.RegisterSettingsPage(sc, sp) } for _, si := range m.Contributes.StatusItems { si.PluginID = pid r.RegisterStatusItem(sc, si) } for _, pnl := range m.Contributes.Panels { pnl.PluginID = pid r.RegisterPanel(sc, pnl) } for _, view := range m.Contributes.Views { view.PluginID = pid r.RegisterView(sc, view) } for _, src := range m.Contributes.ImageSources { src.PluginID = pid r.RegisterImageSource(sc, src) } // Register L1 declarative rule hooks on the hook bus. if len(m.Contributes.RuleHooks) > 0 { rules := append([]RuleHook(nil), m.Contributes.RuleHooks...) r.registerRuleHooks(sc, pid, rules) } // Register declarative services declared in external Manifest.Provides. for _, pr := range m.Provides { if pr.Service == "" { continue } if _, exists := r.LookupService(pr.Service); !exists { ver := pr.Version if ver == "" { ver = m.Version } sc.Provide(pr.Service, ver, pid) } } } // PluginHasPermission reports whether pluginID declares perm. func (r *Registry) PluginHasPermission(pluginID, perm string) bool { r.mu.RLock() defer r.mu.RUnlock() e, ok := r.entries[pluginID] if !ok { return false } for _, p := range e.def.Manifest.Permissions { if p == perm { return true } } return false } // MarkDegraded marks an active plugin as degraded with a reason. func (r *Registry) MarkDegraded(pluginID, reason string) { r.mu.Lock() if e, ok := r.entries[pluginID]; ok && (e.state == StateActive || e.state == StateDegraded) { e.state = StateDegraded e.degradedReason = reason e.updatedAt = time.Now() } r.mu.Unlock() r.notifyChange() } // MarkFailed marks a plugin as failed and disposes its scope. func (r *Registry) MarkFailed(pluginID, reason string) { r.mu.Lock() e, ok := r.entries[pluginID] if !ok { r.mu.Unlock() return } sc := e.scope e.scope = nil e.state = StateFailed e.errMsg = reason e.updatedAt = time.Now() r.mu.Unlock() if sc != nil { sc.Dispose() } r.notifyChange() } // RecordHookOutcome updates consecutive failure tracking and degrades the plugin on threshold. func (r *Registry) RecordHookOutcome(pluginID string, err error) { const degradeThreshold = 3 r.mu.Lock() e, ok := r.entries[pluginID] if !ok { r.mu.Unlock() return } if err == nil { e.consecutiveErrs = 0 r.mu.Unlock() return } e.consecutiveErrs++ shouldNotify := false if e.consecutiveErrs >= degradeThreshold && e.state == StateActive { e.state = StateDegraded e.degradedReason = fmt.Sprintf("consecutive hook failures (%d): %v", e.consecutiveErrs, err) e.updatedAt = time.Now() shouldNotify = true } r.mu.Unlock() if shouldNotify { r.logf("plugin", "%s degraded: %s", pluginID, err.Error()) r.notifyChange() } } // DisposeAll shuts down every active plugin in reverse dependency order. func (r *Registry) DisposeAll() { r.mu.Lock() for _, e := range r.entries { e.def.Desired = false } r.mu.Unlock() r.Reconcile(context.Background()) } // --- Service lookup --- func (r *Registry) provideService(pluginID, name, version string, svc any) { r.mu.Lock() r.services[name] = serviceRecord{pluginID: pluginID, version: version, instance: svc} r.mu.Unlock() } func (r *Registry) unprovideService(pluginID, name string) { r.mu.Lock() if cur, ok := r.services[name]; ok && cur.pluginID == pluginID { delete(r.services, name) } r.mu.Unlock() } // LookupService returns a currently provided service instance. func (r *Registry) LookupService(name string) (any, bool) { r.mu.RLock() rec, ok := r.services[name] r.mu.RUnlock() if !ok { return nil, false } return rec.instance, true } // --- Extension point registration (all reversible via Scope.OnDispose) --- func (r *Registry) RegisterTheme(sc *Scope, th ThemeContribution) { if th.ID == "" { return } th.PluginID = sc.PluginID() r.mu.Lock() r.themes[th.ID] = th r.mu.Unlock() sc.OnDispose(func() { r.mu.Lock() if cur, ok := r.themes[th.ID]; ok && cur.PluginID == sc.PluginID() { delete(r.themes, th.ID) if r.activeThemeID == th.ID { r.activeThemeID = "" } } r.mu.Unlock() }) } func (r *Registry) SetActiveTheme(themeID string) error { r.mu.Lock() defer r.mu.Unlock() if themeID == "" || themeID == "builtin.theme.default" { r.activeThemeID = "" return nil } if _, ok := r.themes[themeID]; !ok { return fmt.Errorf("theme %q not registered", themeID) } r.activeThemeID = themeID return nil } func (r *Registry) ActiveTheme() *ThemeContribution { r.mu.RLock() defer r.mu.RUnlock() if r.activeThemeID == "" { return nil } th, ok := r.themes[r.activeThemeID] if !ok { return nil } cp := th return &cp } func (r *Registry) Themes() []ThemeContribution { r.mu.RLock() defer r.mu.RUnlock() out := make([]ThemeContribution, 0, len(r.themes)) for _, th := range r.themes { out = append(out, th) } sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID }) return out } // PluginOwnsTheme reports whether pluginID declares or currently registers // themeID. Works even when external plugins are not activated (e.g. safe mode). func (r *Registry) PluginOwnsTheme(pluginID, themeID string) bool { if pluginID == "" || themeID == "" { return false } r.mu.RLock() defer r.mu.RUnlock() if th, ok := r.themes[themeID]; ok && th.PluginID == pluginID { return true } if e, ok := r.entries[pluginID]; ok { for _, th := range e.def.Manifest.Contributes.Themes { if th.ID == themeID { return true } } } return false } // ThemeOwner returns the plugin ID that registers or declares themeID, or "". func (r *Registry) ThemeOwner(themeID string) string { if themeID == "" { return "" } r.mu.RLock() defer r.mu.RUnlock() if th, ok := r.themes[themeID]; ok && th.PluginID != "" { return th.PluginID } for pid, e := range r.entries { for _, th := range e.def.Manifest.Contributes.Themes { if th.ID == themeID { return pid } } } return "" } func (r *Registry) RegisterUIScript(sc *Scope, us UIScriptContribution) { if us.ID == "" { return } us.PluginID = sc.PluginID() r.mu.Lock() r.uiScripts[us.ID] = us r.mu.Unlock() sc.OnDispose(func() { r.mu.Lock() if cur, ok := r.uiScripts[us.ID]; ok && cur.PluginID == sc.PluginID() { delete(r.uiScripts, us.ID) } r.mu.Unlock() }) } func (r *Registry) UIScripts() []UIScriptContribution { r.mu.RLock() defer r.mu.RUnlock() out := make([]UIScriptContribution, 0, len(r.uiScripts)) for _, s := range r.uiScripts { out = append(out, s) } sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID }) return out } func (r *Registry) RegisterLocale(sc *Scope, lc LocaleContribution) { canon, ok := i18n.ParseLocale(lc.Locale) if !ok { return } lc.Locale = string(canon) if lc.Fallback != "" { if fb, ok := i18n.ParseLocale(lc.Fallback); ok { lc.Fallback = string(fb) } else { lc.Fallback = "" } } lc.PluginID = sc.PluginID() r.mu.Lock() if ent := r.entries[lc.PluginID]; ent != nil { lc.TrustRank = localeTrustRank(ent.def.Source, ent.def.Trust) } r.locales[lc.Locale] = append(r.locales[lc.Locale], lc) r.mu.Unlock() sc.OnDispose(func() { r.mu.Lock() list := r.locales[lc.Locale] kept := list[:0] for _, item := range list { if item.PluginID != sc.PluginID() { kept = append(kept, item) } } if len(kept) == 0 { delete(r.locales, lc.Locale) } else { r.locales[lc.Locale] = kept } r.mu.Unlock() }) } // Locales returns a deterministic snapshot of all active locale contributions. func (r *Registry) Locales() []LocaleContribution { r.mu.RLock() defer r.mu.RUnlock() var out []LocaleContribution for _, list := range r.locales { out = append(out, list...) } sort.Slice(out, func(i, j int) bool { if out[i].Locale != out[j].Locale { return out[i].Locale < out[j].Locale } if out[i].TrustRank != out[j].TrustRank { return out[i].TrustRank < out[j].TrustRank } if out[i].Priority != out[j].Priority { return out[i].Priority < out[j].Priority } return out[i].PluginID < out[j].PluginID }) return out } // ManifestOf returns the parsed Manifest of a registered plugin if present. func (r *Registry) ManifestOf(id string) (Manifest, bool) { r.mu.RLock() defer r.mu.RUnlock() ent, ok := r.entries[id] if !ok || ent == nil { return Manifest{}, false } return ent.def.Manifest, true } func (r *Registry) RegisterInputFilter(sc *Scope, flt InputFilterContribution) { if flt.Event == "" || flt.Transform == "" { return } flt.PluginID = sc.PluginID() r.mu.Lock() r.inputFilters = append(r.inputFilters, flt) r.mu.Unlock() sc.OnDispose(func() { r.mu.Lock() kept := r.inputFilters[:0] for _, item := range r.inputFilters { if !(item.PluginID == sc.PluginID() && item.ID == flt.ID) { kept = append(kept, item) } } r.inputFilters = kept r.mu.Unlock() }) } func (r *Registry) InputFilters() []InputFilterContribution { r.mu.RLock() defer r.mu.RUnlock() out := make([]InputFilterContribution, len(r.inputFilters)) copy(out, r.inputFilters) return out } func (r *Registry) RegisterVMTemplate(sc *Scope, tpl VMTemplateContribution) { if tpl.ID == "" { return } tpl.PluginID = sc.PluginID() r.mu.Lock() r.vmTemplates = append(r.vmTemplates, tpl) r.mu.Unlock() sc.OnDispose(func() { r.mu.Lock() kept := r.vmTemplates[:0] for _, item := range r.vmTemplates { if !(item.PluginID == sc.PluginID() && item.ID == tpl.ID) { kept = append(kept, item) } } r.vmTemplates = kept r.mu.Unlock() }) } func (r *Registry) VMTemplates() []VMTemplateContribution { r.mu.RLock() defer r.mu.RUnlock() out := make([]VMTemplateContribution, len(r.vmTemplates)) copy(out, r.vmTemplates) return out } func (r *Registry) RegisterRuntimeSource(sc *Scope, rs RuntimeSourceContribution) { if rs.ID == "" || rs.IndexURL == "" { return } rs.PluginID = sc.PluginID() r.mu.Lock() r.runtimeSources = append(r.runtimeSources, rs) r.mu.Unlock() sc.OnDispose(func() { r.mu.Lock() kept := r.runtimeSources[:0] for _, item := range r.runtimeSources { if !(item.PluginID == sc.PluginID() && item.ID == rs.ID) { kept = append(kept, item) } } r.runtimeSources = kept r.mu.Unlock() }) } func (r *Registry) RuntimeSources() []RuntimeSourceContribution { r.mu.RLock() defer r.mu.RUnlock() out := make([]RuntimeSourceContribution, len(r.runtimeSources)) copy(out, r.runtimeSources) return out } func (r *Registry) RegisterRuntimeKind(sc *Scope, rk RuntimeKindContribution) { if rk.Kind == "" { return } rk.PluginID = sc.PluginID() r.mu.Lock() r.runtimeKinds[rk.Kind] = rk r.mu.Unlock() sc.OnDispose(func() { r.mu.Lock() if cur, ok := r.runtimeKinds[rk.Kind]; ok && cur.PluginID == sc.PluginID() { delete(r.runtimeKinds, rk.Kind) } r.mu.Unlock() }) } func (r *Registry) RuntimeKinds() []RuntimeKindContribution { r.mu.RLock() defer r.mu.RUnlock() out := make([]RuntimeKindContribution, 0, len(r.runtimeKinds)) for _, rk := range r.runtimeKinds { out = append(out, rk) } sort.Slice(out, func(i, j int) bool { return out[i].Kind < out[j].Kind }) return out } func (r *Registry) RegisterGuestDriver(sc *Scope, driverID string, drv any) { if driverID == "" || drv == nil { return } r.mu.Lock() r.guestDrivers[driverID] = drv r.mu.Unlock() sc.OnDispose(func() { r.mu.Lock() delete(r.guestDrivers, driverID) r.mu.Unlock() }) } func (r *Registry) GuestDriver(driverID string) (any, bool) { r.mu.RLock() drv, ok := r.guestDrivers[driverID] r.mu.RUnlock() return drv, ok } func (r *Registry) GuestDrivers() map[string]any { r.mu.RLock() defer r.mu.RUnlock() out := make(map[string]any, len(r.guestDrivers)) for k, v := range r.guestDrivers { out[k] = v } return out } // RegisterDownloader registers a pluggable file/region downloader scoped to sc. func (r *Registry) RegisterDownloader(sc *Scope, contrib DownloaderContribution, provider downloader.Provider) { if contrib.ID == "" || provider == nil { return } contrib.PluginID = sc.PluginID() key := sc.PluginID() + ":" + contrib.ID r.mu.Lock() r.downloaders[key] = RegisteredDownloader{Contribution: contrib, Provider: provider} r.mu.Unlock() sc.OnDispose(func() { r.mu.Lock() delete(r.downloaders, key) r.mu.Unlock() }) } // Downloaders returns all currently active downloader contributions ordered by // descending priority. func (r *Registry) Downloaders() []DownloaderContribution { r.mu.RLock() defer r.mu.RUnlock() out := make([]DownloaderContribution, 0, len(r.downloaders)) for _, d := range r.downloaders { out = append(out, d.Contribution) } sort.Slice(out, func(i, j int) bool { if out[i].Priority != out[j].Priority { return out[i].Priority > out[j].Priority } return out[i].ID < out[j].ID }) return out } // ActiveDownloader returns the highest-priority active downloader provider. func (r *Registry) ActiveDownloader() (DownloaderContribution, downloader.Provider, bool) { r.mu.RLock() defer r.mu.RUnlock() var ( best RegisteredDownloader found bool ) for _, d := range r.downloaders { if !found || d.Contribution.Priority > best.Contribution.Priority || (d.Contribution.Priority == best.Contribution.Priority && d.Contribution.ID < best.Contribution.ID) { best = d found = true } } if !found { return DownloaderContribution{}, nil, false } return best.Contribution, best.Provider, true } // DeclaredDriverIDs returns all guest driver IDs declared in pluginID's manifest // without invoking inUseChecker (safe to call from SetInUseChecker). func (r *Registry) DeclaredDriverIDs(pluginID string) []string { r.mu.RLock() defer r.mu.RUnlock() e := r.entries[pluginID] if e == nil { return nil } var out []string for _, gd := range e.def.Manifest.Contributes.GuestDrivers { if gd.ID != "" { out = append(out, gd.ID) } } return out } // DeclaredVMRoots returns VM root declarations from every registered plugin, // including disabled ones, so their VMs remain visible as driver_unavailable. func (r *Registry) DeclaredVMRoots() map[string][]string { r.mu.RLock() defer r.mu.RUnlock() out := map[string][]string{} seen := map[string]bool{} for _, e := range r.entries { for _, gd := range e.def.Manifest.Contributes.GuestDrivers { for _, root := range gd.VMRoots { root = strings.TrimSpace(root) key := gd.ID + "\x00" + root if gd.ID == "" || root == "" || seen[key] { continue } seen[key] = true out[gd.ID] = append(out[gd.ID], root) } } } return out } func (r *Registry) RegisterCommand(sc *Scope, contrib CommandContribution, handler CommandHandler) { if contrib.ID == "" || handler == nil { return } contrib.PluginID = sc.PluginID() key := sc.PluginID() + ":" + contrib.ID r.mu.Lock() r.commands[key] = RegisteredCommand{Contribution: contrib, Handler: handler} r.mu.Unlock() sc.OnDispose(func() { r.mu.Lock() delete(r.commands, key) r.mu.Unlock() }) } func (r *Registry) Commands() []CommandContribution { r.mu.RLock() defer r.mu.RUnlock() out := make([]CommandContribution, 0, len(r.commands)) for _, c := range r.commands { out = append(out, c.Contribution) } sort.Slice(out, func(i, j int) bool { if out[i].PluginID != out[j].PluginID { return out[i].PluginID < out[j].PluginID } return out[i].ID < out[j].ID }) return out } // InvokeCommand executes a registered plugin command with the §4.3 30s timeout. func (r *Registry) InvokeCommand(ctx context.Context, pluginID, commandID string, args map[string]any) (any, error) { r.mu.RLock() cmd, ok := r.commands[pluginID+":"+commandID] r.mu.RUnlock() if !ok { return nil, fmt.Errorf("command %q not found on plugin %q", commandID, pluginID) } callCtx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() return cmd.Handler(callCtx, args) } func (r *Registry) RegisterMenu(sc *Scope, m MenuContribution) { if !IsDeclaredSlot(m.Slot) { return } m.PluginID = sc.PluginID() r.mu.Lock() count := 0 for _, existing := range r.menus { if existing.Slot == m.Slot { count++ } } if count >= DeclaredUISlots[m.Slot] { r.mu.Unlock() return } r.menus = append(r.menus, m) r.mu.Unlock() sc.OnDispose(func() { r.mu.Lock() kept := r.menus[:0] for _, item := range r.menus { if !(item.PluginID == sc.PluginID() && item.ID == m.ID) { kept = append(kept, item) } } r.menus = kept r.mu.Unlock() }) } func (r *Registry) Menus(slot string) []MenuContribution { r.mu.RLock() defer r.mu.RUnlock() var out []MenuContribution for _, m := range r.menus { if slot == "" || m.Slot == slot { out = append(out, m) } } return out } func (r *Registry) RegisterVMCard(sc *Scope, c VMCardContribution) { c.PluginID = sc.PluginID() r.mu.Lock() if len(r.vmCards) >= DeclaredUISlots["vm.card"] { r.mu.Unlock() return } r.vmCards = append(r.vmCards, c) r.mu.Unlock() sc.OnDispose(func() { r.mu.Lock() kept := r.vmCards[:0] for _, item := range r.vmCards { if !(item.PluginID == sc.PluginID() && item.ID == c.ID) { kept = append(kept, item) } } r.vmCards = kept r.mu.Unlock() }) } func (r *Registry) VMCards() []VMCardContribution { r.mu.RLock() defer r.mu.RUnlock() out := make([]VMCardContribution, len(r.vmCards)) copy(out, r.vmCards) return out } func (r *Registry) RegisterSettingsPage(sc *Scope, sp SettingsPageContribution) { sp.PluginID = sc.PluginID() r.mu.Lock() if len(r.settingsPages) >= DeclaredUISlots["settings.plugin"] { r.mu.Unlock() return } r.settingsPages = append(r.settingsPages, sp) r.mu.Unlock() sc.OnDispose(func() { r.mu.Lock() kept := r.settingsPages[:0] for _, item := range r.settingsPages { if !(item.PluginID == sc.PluginID() && item.ID == sp.ID) { kept = append(kept, item) } } r.settingsPages = kept r.mu.Unlock() }) } func (r *Registry) SettingsPages() []SettingsPageContribution { r.mu.RLock() defer r.mu.RUnlock() out := make([]SettingsPageContribution, len(r.settingsPages)) copy(out, r.settingsPages) return out } func (r *Registry) RegisterStatusItem(sc *Scope, si StatusItemContribution) { if si.Slot == "" { si.Slot = "statusbar.right" } if !IsDeclaredSlot(si.Slot) { return } si.PluginID = sc.PluginID() r.mu.Lock() if len(r.statusItems) >= DeclaredUISlots[si.Slot] { r.mu.Unlock() return } r.statusItems = append(r.statusItems, si) r.mu.Unlock() sc.OnDispose(func() { r.mu.Lock() kept := r.statusItems[:0] for _, item := range r.statusItems { if !(item.PluginID == sc.PluginID() && item.ID == si.ID) { kept = append(kept, item) } } r.statusItems = kept r.mu.Unlock() }) } func (r *Registry) StatusItems() []StatusItemContribution { r.mu.RLock() defer r.mu.RUnlock() out := make([]StatusItemContribution, len(r.statusItems)) copy(out, r.statusItems) return out } func (r *Registry) RegisterPanel(sc *Scope, p PanelContribution) { if !IsDeclaredSlot(p.Slot) { return } p.PluginID = sc.PluginID() r.mu.Lock() count := 0 for _, existing := range r.panels { if existing.Slot == p.Slot { count++ } } if count >= DeclaredUISlots[p.Slot] { r.mu.Unlock() return } r.panels = append(r.panels, p) r.mu.Unlock() sc.OnDispose(func() { r.mu.Lock() kept := r.panels[:0] for _, item := range r.panels { if !(item.PluginID == sc.PluginID() && item.ID == p.ID) { kept = append(kept, item) } } r.panels = kept r.mu.Unlock() }) } func (r *Registry) Panels(slot string) []PanelContribution { r.mu.RLock() defer r.mu.RUnlock() var out []PanelContribution for _, p := range r.panels { if slot == "" || p.Slot == slot { out = append(out, p) } } return out } func (r *Registry) RegisterView(sc *Scope, view ViewContribution) { view.ID = strings.TrimSpace(view.ID) if view.ID == "" { return } location, ok := ViewLocationCatalog[view.Location] if !ok { return } view.PluginID = sc.PluginID() r.mu.Lock() count := 0 for _, existing := range r.views { if existing.PluginID != view.PluginID { continue } if existing.ID == view.ID { r.mu.Unlock() return } if existing.Location == view.Location { count++ } } if location.PerPlugin > 0 && count >= location.PerPlugin { r.mu.Unlock() return } r.views = append(r.views, view) r.mu.Unlock() sc.OnDispose(func() { r.mu.Lock() kept := r.views[:0] for _, item := range r.views { if !(item.PluginID == sc.PluginID() && item.ID == view.ID) { kept = append(kept, item) } } r.views = kept r.mu.Unlock() }) } func (r *Registry) Views(location string) []ViewContribution { r.mu.RLock() out := make([]ViewContribution, 0, len(r.views)) for _, view := range r.views { if location == "" || view.Location == location { out = append(out, view) } } r.mu.RUnlock() sort.SliceStable(out, func(i, j int) bool { if out[i].Order != out[j].Order { return out[i].Order < out[j].Order } if out[i].PluginID != out[j].PluginID { return out[i].PluginID < out[j].PluginID } return out[i].ID < out[j].ID }) return out } func (r *Registry) View(pluginID, viewID string) (ViewContribution, bool) { r.mu.RLock() defer r.mu.RUnlock() for _, view := range r.views { if view.PluginID == pluginID && view.ID == viewID { return view, true } } return ViewContribution{}, false } func (r *Registry) RegisterImageSource(sc *Scope, src ImageSourceContribution) { src.ID = strings.TrimSpace(src.ID) if src.ID == "" { return } src.PluginID = sc.PluginID() r.mu.Lock() replaced := false for i, existing := range r.imageSources { if existing.PluginID == src.PluginID && existing.ID == src.ID { r.imageSources[i] = src replaced = true break } } if !replaced { r.imageSources = append(r.imageSources, src) } r.mu.Unlock() sc.OnDispose(func() { r.mu.Lock() kept := r.imageSources[:0] for _, item := range r.imageSources { if !(item.PluginID == sc.PluginID() && item.ID == src.ID) { kept = append(kept, item) } } r.imageSources = kept r.mu.Unlock() }) } func (r *Registry) ImageSources() []ImageSourceContribution { r.mu.RLock() out := make([]ImageSourceContribution, len(r.imageSources)) copy(out, r.imageSources) r.mu.RUnlock() sort.SliceStable(out, func(i, j int) bool { if out[i].Order != out[j].Order { return out[i].Order < out[j].Order } ni := strings.TrimSpace(out[i].Native) != "" nj := strings.TrimSpace(out[j].Native) != "" if ni != nj { return ni } if out[i].PluginID != out[j].PluginID { return out[i].PluginID < out[j].PluginID } return out[i].ID < out[j].ID }) return out } func (r *Registry) RegisterDiagnostics(sc *Scope, contrib DiagnosticsContribution, collector DiagnosticsCollector) { if collector == nil { return } contrib.PluginID = sc.PluginID() r.mu.Lock() r.diagnostics = append(r.diagnostics, RegisteredDiagnostics{Contribution: contrib, Collector: collector}) r.mu.Unlock() sc.OnDispose(func() { r.mu.Lock() kept := r.diagnostics[:0] for _, item := range r.diagnostics { if !(item.Contribution.PluginID == sc.PluginID() && item.Contribution.ID == contrib.ID) { kept = append(kept, item) } } r.diagnostics = kept r.mu.Unlock() }) } // CollectDiagnostics invokes all registered diagnostics collectors, skipping // failing ones and applying redactFn to every output field (§4.2, §7.1). func (r *Registry) CollectDiagnostics(ctx context.Context, vmName string, redactFn func(string) string) []DiagnosticsEntry { r.mu.RLock() list := append([]RegisteredDiagnostics(nil), r.diagnostics...) r.mu.RUnlock() if len(list) == 0 { return nil } if redactFn == nil { redactFn = func(s string) string { return s } } var out []DiagnosticsEntry for _, item := range list { callCtx, cancel := context.WithTimeout(ctx, 2*time.Second) entry, err := item.Collector(callCtx, vmName) cancel() if err != nil { continue } entry.PluginID = item.Contribution.PluginID if entry.Title == "" { entry.Title = item.Contribution.Title.Get(string(r.currentLocale())) } entry.Text = redactFn(entry.Text) if len(entry.Data) > 0 { entry.Data = redactMap(entry.Data, redactFn) } out = append(out, entry) } return out } func redactMap(m map[string]any, redactFn func(string) string) map[string]any { out := make(map[string]any, len(m)) for k, v := range m { switch val := v.(type) { case string: out[k] = redactFn(val) case map[string]any: out[k] = redactMap(val, redactFn) default: out[k] = v } } return out } // --- Introspection --- // ActivePluginIDs returns a set of all currently active or degraded plugin IDs. func (r *Registry) ActivePluginIDs() map[string]bool { r.mu.RLock() defer r.mu.RUnlock() out := make(map[string]bool, len(r.entries)) for id, e := range r.entries { if e.scope != nil { out[id] = true } } return out } // IsActive reports whether pluginID currently has an active scope. func (r *Registry) IsActive(pluginID string) bool { r.mu.RLock() e, ok := r.entries[pluginID] active := ok && e.scope != nil r.mu.RUnlock() return active } // StateOf returns the current lifecycle state of pluginID. func (r *Registry) StateOf(pluginID string) State { r.mu.RLock() e, ok := r.entries[pluginID] st := StateOff if ok { st = e.state } r.mu.RUnlock() return st } // Info returns the read-only PluginInfo view for pluginID. func (r *Registry) Info(pluginID string) (PluginInfo, bool) { r.mu.RLock() e, ok := r.entries[pluginID] checker := r.inUseChecker if !ok { r.mu.RUnlock() return PluginInfo{}, false } info := r.entryToInfoLocked(e) r.mu.RUnlock() // System plugins can't be disabled or removed, so "in use" means nothing // for them, and the check can be costly (driver VM listing). if checker != nil && !info.System { if inUse, _, err := checker(pluginID); err != nil || inUse { info.InUse = true } } return info, true } // List returns PluginInfo for all registered plugins (builtins first, then sorted by ID). func (r *Registry) List() []PluginInfo { r.mu.RLock() checker := r.inUseChecker out := make([]PluginInfo, 0, len(r.entries)) for _, e := range r.entries { out = append(out, r.entryToInfoLocked(e)) } r.mu.RUnlock() if checker != nil { for i := range out { if out[i].System { continue } if inUse, _, err := checker(out[i].ID); err != nil || inUse { out[i].InUse = true } } } sort.Slice(out, func(i, j int) bool { bi := out[i].Source == SourceBuiltin bj := out[j].Source == SourceBuiltin if bi != bj { return bi } return out[i].ID < out[j].ID }) return out } // ListVisible is List without system plugins. A system plugin is part of the // host itself (always on, nothing to configure), so plugin lists shown to // users leave it out; Info still returns it by ID. func (r *Registry) ListVisible() []PluginInfo { all := r.List() out := all[:0] for _, p := range all { if !p.System { out = append(out, p) } } return out } func (r *Registry) entryToInfoLocked(e *pluginEntry) PluginInfo { m := e.def.Manifest perms := make([]PermissionSpec, 0, len(m.Permissions)) for _, p := range m.Permissions { perms = append(perms, PermissionSpec{Name: p, Level: ClassifyPermission(p)}) } reqs := make([]string, 0, len(m.Requires)) for _, rq := range m.Requires { reqs = append(reqs, rq.Service) } provs := make([]string, 0, len(m.Provides)) for _, pr := range m.Provides { provs = append(provs, pr.Service) } tier := m.InferTier(e.def.Source == SourceBuiltin) var locales []string for _, lc := range m.Contributes.Locales { // Same canonical tag the resolved locale packs use (e.g. ja_jp → ja-JP). if canon, ok := i18n.ParseLocale(lc.Locale); ok { locales = append(locales, string(canon)) } } return PluginInfo{ ID: m.ID, Version: m.Version, Name: m.Name, Description: m.Description, Publisher: m.Publisher, License: m.License, Homepage: m.Homepage, Source: e.def.Source, Trust: e.def.Trust, Tier: tier, State: e.state, Enabled: e.def.Desired, Removable: e.def.Removable, System: e.def.System, Error: e.errMsg, DegradedReason: e.degradedReason, Permissions: perms, ApprovedPermissions: append([]string(nil), e.def.ApprovedPermissions...), NeedsApproval: e.def.NeedsApproval, Risks: ManifestRisks(m, tier), Locales: locales, Requires: reqs, Provides: provs, Settings: m.Settings, InstallDir: e.def.InstallDir, EntryHash: e.def.EntryHash, EntryPath: e.def.EntryPath, LogPath: e.def.LogPath, UpdatedAt: e.updatedAt, } }