package service import ( "context" "fmt" "os" "path/filepath" "strings" "infinite-canvas/backend/internal/model" "infinite-canvas/backend/internal/protocol" ) type protocolRegistryContextKey struct{} func withProtocolRegistry(ctx context.Context, registry *protocol.Registry) context.Context { return context.WithValue(ctx, protocolRegistryContextKey{}, registry) } func declarativeProtocolAdapterForContext(ctx context.Context, id string) (protocol.Adapter, bool) { registry, _ := ctx.Value(protocolRegistryContextKey{}).(*protocol.Registry) if registry == nil { registry = protocol.Builtins() } adapter, ok := registry.Resolve(strings.TrimSpace(id)) if !ok || adapter.Metadata().Execution != "declarative" { return nil, false } return adapter, true } func agentProtocolAdapterForContext(ctx context.Context, id string) (protocol.AgentAdapter, bool) { registry, _ := ctx.Value(protocolRegistryContextKey{}).(*protocol.Registry) if registry == nil { registry = protocol.Builtins() } adapter, ok := registry.Resolve(strings.TrimSpace(id)) if !ok || adapter.Metadata().Execution != "declarative" { return nil, false } agentAdapter, ok := adapter.(protocol.AgentAdapter) return agentAdapter, ok } type PluginProviderCatalogItem struct { ID string `json:"id"` Version string `json:"version"` Name string `json:"name"` Vendor string `json:"vendor"` Categories []protocol.Capability `json:"categories"` Scopes []protocol.Surface `json:"scopes"` Create string `json:"create,omitempty"` Poll string `json:"poll,omitempty"` ContentType string `json:"contentType,omitempty"` BaseURL string `json:"baseUrl,omitempty"` Enabled bool `json:"enabled"` UnavailableReason string `json:"unavailableReason,omitempty"` Workflows []protocol.ManifestWorkflow `json:"workflows,omitempty"` } // PluginProviderCatalog projects provider and workflow contributions from the // unified plugin registry for channel and creation settings. func (s *Service) PluginProviderCatalog(scope, capability string, includeUnavailable bool) []PluginProviderCatalogItem { wantScope := protocol.Surface(strings.TrimSpace(scope)) wantCapability := protocol.Capability(strings.TrimSpace(capability)) items := make([]PluginProviderCatalogItem, 0) for _, plugin := range s.Plugins() { for _, provider := range plugin.Manifest.Contributes.Providers { if !containsPluginSurface(provider.Scopes, wantScope) || (wantCapability != "" && !containsPluginCapability(provider.Capabilities, wantCapability)) { continue } item := PluginProviderCatalogItem{ID: provider.ID, Version: plugin.Manifest.Version, Name: provider.Label, Vendor: plugin.Manifest.Author, Categories: provider.Capabilities, Scopes: provider.Scopes, BaseURL: provider.BaseURL, Enabled: plugin.Status == "enabled", UnavailableReason: plugin.Error, Workflows: workflowsForProvider(plugin.Manifest.Contributes.Workflows, provider.ID)} item.Create = operationSummary(provider.Create) if provider.Poll != nil { item.Poll = operationSummary(*provider.Poll) } item.ContentType = provider.Create.ContentType if includeUnavailable || item.Enabled { items = append(items, item) } } } return items } func containsPluginSurface(items []protocol.Surface, want protocol.Surface) bool { for _, item := range items { if item == want { return true } } return false } func containsPluginCapability(items []protocol.Capability, want protocol.Capability) bool { for _, item := range items { if item == want { return true } } return false } func workflowsForProvider(items []protocol.ManifestWorkflow, providerID string) []protocol.ManifestWorkflow { result := make([]protocol.ManifestWorkflow, 0) for _, item := range items { if item.ProviderID == providerID { result = append(result, item) } } return result } func operationSummary(operation protocol.ManifestOperation) string { path := strings.ReplaceAll(operation.Path, "{{model}}", "{model}") path = strings.ReplaceAll(path, "{{taskId}}", "{task_id}") return strings.ToUpper(operation.Method) + " " + path } func (s *Service) protocolRegistry() *protocol.Registry { if s.pluginRuntime != nil { if registry := s.pluginRuntime.registrySnapshot(); registry != nil { return registry } } return protocol.Builtins() } func (s *Service) protocolMetadata(id string) (protocol.Metadata, bool) { adapter, ok := s.protocolRegistry().Resolve(strings.TrimSpace(id)) if !ok { return protocol.Metadata{}, false } return adapter.Metadata(), true } func (s *Service) channelProtocolMetadata(id string) (protocol.Metadata, bool) { return s.protocolMetadata(id) } func (s *Service) canonicalProtocolID(id string) (string, bool) { adapter, ok := s.protocolRegistry().Resolve(strings.TrimSpace(id)) if !ok { return "", false } return adapter.Metadata().ID, true } func (s *Service) protocolIsSelectable(id string) bool { metadata, ok := s.channelProtocolMetadata(id) return ok && metadata.Enabled && metadata.UnavailableReason == "" } func (s *Service) Plugins() []PluginView { if s.pluginRuntime == nil { return []PluginView{} } return s.pluginRuntime.list() } // PluginsForUser keeps the plugin center response aligned with the public // feature switch. Administrators must still be able to inspect and recover // bundled plugins even when ordinary users cannot see them. func (s *Service) PluginsForUser(actor *model.User) ([]PluginView, error) { items := s.Plugins() if actor != nil && actor.Role == model.UserRoleAdmin { return items, nil } visible, err := s.FeatureEnabled(FeatureSystemPlugins) if err != nil { return nil, err } if visible { return items, nil } filtered := make([]PluginView, 0, len(items)) for _, item := range items { if item.Source != "bundled" { filtered = append(filtered, item) } } return filtered, nil } func (s *Service) InstallPlugin(data []byte, fileName string) (PluginView, error) { if s.pluginRuntime == nil { return PluginView{}, fmt.Errorf("插件运行时未初始化") } return s.pluginRuntime.install(data, fileName) } func (s *Service) PluginPackage(id string) ([]byte, string, error) { if s.pluginRuntime == nil { return nil, "", fmt.Errorf("插件运行时未初始化") } s.pluginRuntime.mu.RLock() record, ok := s.pluginRuntime.plugins[strings.TrimSpace(id)] s.pluginRuntime.mu.RUnlock() if !ok { return nil, "", fmt.Errorf("插件 %q 不存在", id) } if record.PackagePath == "" { return nil, "", fmt.Errorf("插件 %q 没有可下载的包文件", id) } data, err := os.ReadFile(filepath.Join(s.pluginRuntime.packageDir, filepath.Base(record.PackagePath))) if err != nil { return nil, "", fmt.Errorf("读取插件包失败:%w", err) } return data, record.FileName, nil } func (s *Service) SetPluginEnabled(id string, enabled bool) (PluginView, error) { if s.pluginRuntime == nil { return PluginView{}, fmt.Errorf("插件运行时未初始化") } return s.pluginRuntime.setEnabled(id, enabled) } func (s *Service) UninstallPlugin(id string) error { if s.pluginRuntime == nil { return fmt.Errorf("插件运行时未初始化") } return s.pluginRuntime.uninstall(id) }