services

package
v2.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 2, 2026 License: AGPL-3.0 Imports: 86 Imported by: 0

Documentation

Overview

services/plugin_event_service.go Host-side implementation of PluginEventService for AI Studio (control instance). This server is registered on the go-plugin broker and called by plugins to publish events and subscribe to event streams.

Index

Constants

View Source
const (
	// Default branding storage path
	DefaultBrandingStoragePath = "./data/branding"

	// File size limits
	MaxLogoSize    = 2 * 1024 * 1024 // 2MB
	MaxFaviconSize = 100 * 1024      // 100KB

	// Allowed file extensions
	LogoFileName    = "logo"
	FaviconFileName = "favicon"
)
View Source
const (
	PendingBaselinePush    = "push"     // the namespace's recorded last push
	PendingBaselineEdgeAck = "edge_ack" // an in-sync edge's ack; no push recorded (pre-upgrade database)
	PendingBaselineNone    = "none"     // nothing to measure from
)

Baseline values: what Since was taken from.

View Source
const (
	PendingChangeCreated = "created"
	PendingChangeUpdated = "updated"
	PendingChangeDeleted = "deleted"
)
View Source
const (
	// MaxKVKeyLength is the maximum length for a plugin data key
	MaxKVKeyLength = 255
	// MaxKVValueSize is the maximum size for a plugin data value (5MB)
	MaxKVValueSize = 5 * 1024 * 1024
)
View Source
const (
	DashboardSection = "dashboard"
	NonceLength      = 32
	NonceTTL         = 60 * time.Second
)
View Source
const (
	// LLM events
	TopicLLMCreated = "system.llm.created"
	TopicLLMUpdated = "system.llm.updated"
	TopicLLMDeleted = "system.llm.deleted"

	// App events
	TopicAppCreated                = "system.app.created"
	TopicAppUpdated                = "system.app.updated"
	TopicAppDeleted                = "system.app.deleted"
	TopicAppApproved               = "system.app.approved"
	TopicAppPluginResourcesChanged = "system.app.plugin_resources.changed"

	// Datasource events
	TopicDatasourceCreated = "system.datasource.created"
	TopicDatasourceUpdated = "system.datasource.updated"
	TopicDatasourceDeleted = "system.datasource.deleted"

	// User events
	TopicUserCreated = "system.user.created"
	TopicUserUpdated = "system.user.updated"
	TopicUserDeleted = "system.user.deleted"

	// Group events
	TopicGroupCreated = "system.group.created"
	TopicGroupUpdated = "system.group.updated"
	TopicGroupDeleted = "system.group.deleted"

	// Tool events
	TopicToolCreated = "system.tool.created"
	TopicToolUpdated = "system.tool.updated"
	TopicToolDeleted = "system.tool.deleted"

	// Filter events
	TopicFilterCreated = "system.filter.created"
	TopicFilterUpdated = "system.filter.updated"
	TopicFilterDeleted = "system.filter.deleted"

	// Plugin events
	TopicPluginCreated = "system.plugin.created"
	TopicPluginUpdated = "system.plugin.updated"
	TopicPluginDeleted = "system.plugin.deleted"

	// ModelPrice events
	TopicModelPriceCreated = "system.model_price.created"
	TopicModelPriceUpdated = "system.model_price.updated"
	TopicModelPriceDeleted = "system.model_price.deleted"

	// ModelRouter events
	TopicModelRouterCreated = "system.model_router.created"
	TopicModelRouterUpdated = "system.model_router.updated"
	TopicModelRouterDeleted = "system.model_router.deleted"

	// SemanticRouter events
	TopicSemanticRouterCreated = "system.semantic_router.created"
	TopicSemanticRouterUpdated = "system.semantic_router.updated"
	TopicSemanticRouterDeleted = "system.semantic_router.deleted"

	// Embedder events. The payload object is the embedder with its key
	// redacted.
	TopicEmbedderCreated = "system.embedder.created"
	TopicEmbedderUpdated = "system.embedder.updated"
	TopicEmbedderDeleted = "system.embedder.deleted"

	// Governed metadata events (Enterprise). Payload object: {object_type, object_id, values, validation_status, source}
	TopicGovernedMetadataUpdated = "system.governed_metadata.updated"
	TopicGovernedMetadataDeleted = "system.governed_metadata.deleted"
)

System event topics for CRUD operations

View Source
const (
	// TelemetryURL is the hardcoded endpoint for sending telemetry data
	TelemetryURL = "https://telemetry.tyk.technology"
	// TelemetryPeriod is the hardcoded interval for collecting telemetry
	TelemetryPeriod = time.Hour
)
View Source
const AppGovernanceFlagsKey = "governance_flags"

AppGovernanceFlagsKey is the App metadata key holding governance flags raised by plugins (an asset catalog marking an App "ownerless" or "review_lapsed", say).

View Source
const AppInactiveMessage = "app is inactive"

AppInactiveMessage is the refusal for an App whose live switch is off. The control plane sends it as the error message of a rejected token validation, which is how a microgateway tells an inactive App from an unknown token.

View Source
const DefaultPluginPagePermission = "plugins:execute"

DefaultPluginPagePermission is what an admin plugin page requires when neither its manifest nor its plugin is known: plugin pages call plugin RPCs. With the plugin known the default is the plugin's own base read permission ("plugin:<key>:read"), which plugins:execute implies.

View Source
const REDACTED_VALUE = "[redacted]"

REDACTED_VALUE is the value used to redact sensitive fields in API responses This matches the value used by secrets.FilterSensitiveFields() for consistency

View Source
const RedactedEmbedderKey = "[redacted]"

RedactedEmbedderKey is what a client sends back for an embedder key it was shown redacted; it keeps the stored key.

Variables

View Source
var (
	// Allowed MIME types and extensions for logos
	AllowedLogoTypes = map[string]string{
		"image/png":     ".png",
		"image/jpeg":    ".jpg",
		"image/svg+xml": ".svg",
	}

	// Allowed MIME types and extensions for favicons
	AllowedFaviconTypes = map[string]string{
		"image/x-icon":             ".ico",
		"image/vnd.microsoft.icon": ".ico",
		"image/png":                ".png",
	}

	ErrFileTooLarge      = errors.New("file size exceeds maximum allowed")
	ErrInvalidFileType   = errors.New("invalid file type")
	ErrStoragePathNotSet = errors.New("branding storage path not configured")
)
View Source
var (
	ErrInvalidColor    = errors.New("invalid hex color format (expected #RRGGBB)")
	ErrAppTitleTooLong = errors.New("app title exceeds maximum length (50 characters)")
	ErrUnauthorized    = errors.New("only admin users can modify branding settings")
)
View Source
var (
	// ErrEmbedderNotFound is returned for an unknown embedder id.
	ErrEmbedderNotFound = errors.New("embedder not found")
	// ErrEmbedderInvalid is returned for an embedder that fails validation.
	ErrEmbedderInvalid = models.ErrEmbedderInvalid
)
View Source
var (
	// ErrHostIdentityInvalid is returned for an identity without a subject
	// or email.
	ErrHostIdentityInvalid = errors.New("host identity needs a subject and an email")
	// ErrHostIdentityConflict is returned when the identity's email belongs
	// to a Studio user already linked to a different host subject.
	ErrHostIdentityConflict = errors.New("email already belongs to a user linked to another host identity")
	// ErrHostUserDisabled is returned for a user an administrator disabled
	// in Studio.
	ErrHostUserDisabled = errors.New("account is disabled")
)
View Source
var (
	// ErrUpgradeNotFromMarketplace: the plugin has no marketplace entry to upgrade from.
	ErrUpgradeNotFromMarketplace = errors.New("plugin is not linked to a marketplace entry")
	// ErrUpgradeVersionNotFound: the requested version is not published for this plugin.
	ErrUpgradeVersionNotFound = errors.New("version not found in the marketplace for this plugin")
	// ErrUpgradeSameVersion: the plugin already runs the requested artifact.
	ErrUpgradeSameVersion = errors.New("plugin is already on this version")
	// ErrUpgradeDowngradeNotAllowed: an older version was requested without allow_downgrade.
	ErrUpgradeDowngradeNotAllowed = errors.New("target version is older than the installed version")
	// ErrUpgradeManifestMismatch: the artifact is a different plugin from the one installed.
	ErrUpgradeManifestMismatch = errors.New("target artifact is a different plugin")
	// ErrUpgradeEnterpriseOnly: the target version needs the Enterprise edition.
	ErrUpgradeEnterpriseOnly = errors.New("target version requires the Enterprise edition")
	// ErrUpgradePluginNotFound: there is no such installed plugin.
	ErrUpgradePluginNotFound = errors.New("plugin not found")
	// ErrUpgradeTargetUnavailable: the target artifact could not be pulled,
	// verified or started. Nothing was changed.
	ErrUpgradeTargetUnavailable = errors.New("the target version could not be loaded")
)

Upgrade errors the API maps to distinct responses.

View Source
var (
	ErrScheduleNotFound      = errors.New("schedule not found")
	ErrScheduleAlreadyExists = errors.New("schedule with this ID already exists")
	ErrInvalidCronExpression = errors.New("invalid cron expression")
	ErrInvalidTimezone       = errors.New("invalid timezone")
	ErrScheduleUnauthorized  = errors.New("unauthorized to manage this schedule")
)
View Source
var (
	LoginFailedError      = errors.New("login failed")
	EmailNotVerifiedError = errors.New("email not verified")
	UserDisabledError     = errors.New("account disabled")
)
View Source
var ERRPrivacyScoreMismatch = errors.New("Datasources have higher privacy requirements than the selected LLMs")
View Source
var ErrAppInactive = errors.New(AppInactiveMessage)

ErrAppInactive marks a GetCredentialBySecret error for a credential whose App is switched off. The gateway answers 403 "app is inactive", as it does when it finds the inactive App itself. Wrap it with %w.

View Source
var ErrBudgetCheckUnavailable = errors.New("budget check unavailable")

ErrBudgetCheckUnavailable marks a CheckBudget error that is not a budget decision: the check itself could not run (for example the store was busy). The request is still refused, but the gateway answers 503 rather than a 403 "Budget limit exceeded" that would send the client looking at a budget with room to spare. Wrap it with %w.

View Source
var ErrCredentialCheckUnavailable = errors.New("credential check unavailable")

ErrCredentialCheckUnavailable marks a GetCredentialBySecret error that is not a verdict on the credential: it could not be checked (the microgateway's control plane was unreachable, or failed while looking it up). The gateway answers a retryable 503 rather than a 401 that tells the client its key is wrong. Wrap it with %w.

View Source
var ErrEndpointNotFound = errors.New("endpoint not found")

ErrEndpointNotFound is returned when the endpoint an auth plugin list is read or set for does not exist.

View Source
var ErrInvalidCatalogueReference = errors.New("invalid catalogue reference")

ErrInvalidCatalogueReference is returned when a catalogue id does not exist.

View Source
var ErrInvalidEndpointAuthPlugin = errors.New("invalid auth plugin")

ErrInvalidEndpointAuthPlugin is returned (wrapped) when a plugin cannot be attached to an endpoint as an auth plugin.

View Source
var ErrInvalidFilterSpec = errors.New("invalid filter")

ErrInvalidFilterSpec wraps a spec the service refuses to store: the caller's mistake, distinguishable with errors.Is.

View Source
var ErrInvalidPortalDetailPath = errors.New("invalid portal detail path")

ErrInvalidPortalDetailPath is returned when a resource type declares a portal detail path that is not a same-origin path.

View Source
var ErrInvalidRouterReference = errors.New("invalid router reference")

ErrInvalidRouterReference is returned when a router id does not exist.

View Source
var ErrInvalidSubmissionSchema = errors.New("invalid submission schema")

ErrInvalidSubmissionSchema is returned when a resource type declares a submission schema that is not a valid JSON Schema object.

View Source
var ErrMCPServerNotBrokerable = errors.New("AI Studio cannot issue a key for this MCP server; connect to it directly")

ErrMCPServerNotBrokerable is returned when an App would be bound to an MCP server AI Studio issues no key for (OAuth, mTLS, keyless, or no policy bundle pinned yet): the App would grant nothing, so it is refused.

View Source
var ErrMCPServerNotVisible = errors.New("MCP server is not available to this app")

ErrMCPServerNotVisible is returned when an App would be bound to an MCP server the caller's teams cannot see, or one that is not published and active on its Dashboard.

View Source
var ErrModelRouterNotVisible = errors.New("model router is not available to this app")

ErrModelRouterNotVisible is returned when an App would be granted a Model Router the caller's teams cannot see, or one that is not active.

View Source
var ErrNotificationNotFound = errors.New("notification not found")

ErrNotificationNotFound is returned when a notification does not exist or does not belong to the user asking for it; callers map it to 404.

View Source
var ErrPushesUnavailable = errors.New("configuration pushes are not available: the edge control server is not running")

ErrPushesUnavailable: this Studio has no control server, so nothing can deliver a push.

View Source
var ErrReservedAppMetadataKey = errors.New("metadata key " + AppGovernanceFlagsKey + " is reserved for governance plugins (SetAppGovernanceState)")

ErrReservedAppMetadataKey is returned when a caller tries to write the governance flags through the generic metadata paths.

View Source
var ErrResourceNotAppGranted = errors.New("resource access is not granted through apps")

ErrResourceNotAppGranted is returned when an App would be bound to a plugin resource instance that an App credential does not grant access to (models.PluginResourceType.AccessGrantedViaApp is false and the instance does not override it). Binding such a resource grants nothing, so the platform refuses new bindings rather than record a promise it cannot keep.

View Source
var ErrResourceTypeNotOwned = errors.New("resource type not registered by this plugin")

ErrResourceTypeNotOwned is returned when a plugin names a resource type it did not register (or that does not exist).

View Source
var ErrSemanticRouterNotVisible = errors.New("semantic router is not available to this app")

ErrSemanticRouterNotVisible is returned when an App would be granted a Semantic Router the caller's teams cannot see, or one that is not active.

View Source
var ErrUnknownGroup = errors.New("unknown group")

ErrUnknownGroup is returned when a grant names a group that does not exist.

View Source
var ErrVectorStoreUnavailable = errors.New("vector store not available in this build")

ErrVectorStoreUnavailable is returned when a datasource would use a vector store this build cannot reach: Chroma in a build without cgo.

View Source
var NewAIStudioManagementServerFunc func(*Service) interface{}

NewAIStudioManagementServerFunc is a factory function for creating AIStudioManagementServer This is set by the grpc package to avoid circular imports

PluginBaseActions are the actions of a plugin's base resource.

Functions

func CreatePluginIDInterceptor

func CreatePluginIDInterceptor(pluginID uint) grpc.UnaryServerInterceptor

CreatePluginIDInterceptor creates a gRPC interceptor that injects the plugin ID into context This is used for the brokered gRPC server where we already know the plugin ID from the caller

func DetectMimeType

func DetectMimeType(filename string) string

DetectMimeType detects MIME type from file extension

func EnsurePendingChangeIndexes

func EnsurePendingChangeIndexes(db *gorm.DB) error

EnsurePendingChangeIndexes creates the index each source table needs for the since-last-push filter: (namespace, updated_at) where the query also narrows by namespace, plain (updated_at) on global tables (gorm.Model indexes deleted_at already). Idempotent; run once at start-up after the tables exist.

func GenerateSecureRandomString

func GenerateSecureRandomString(length int) (string, error)

GenerateSecureRandomString generates a secure random string of given length.

func GetBrandingStoragePath

func GetBrandingStoragePath() string

GetBrandingStoragePath returns the path installed with SetBrandingStoragePath, else BRANDING_STORAGE_PATH, else the default.

func PluginBaseResource

func PluginBaseResource(plugin *models.Plugin) authz.Resource

PluginBaseResource builds the catalogue entry for a plugin.

func PluginSubResource

func PluginSubResource(plugin *models.Plugin, row models.PluginPermissionResource) authz.Resource

PluginSubResource builds the catalogue entry for one declared or runtime-registered sub-resource of a plugin.

func RedactedEmbedder

func RedactedEmbedder(e *models.Embedder) *models.Embedder

RedactedEmbedder is an embedder as events and API responses carry it.

func RequiredPermissionOf

func RequiredPermissionOf(entry *models.UIRegistry) string

RequiredPermissionOf is the exported form for API handlers serving the raw UI registry.

func ResolvePluginPermission

func ResolvePluginPermission(plugin *models.Plugin, raw string) string

ResolvePluginPermission turns a manifest permission string into a catalogue permission for the plugin: "" → the default, "read" / "write" / "execute" → the plugin's base resource, "assets:write" → a declared sub-resource, anything containing a colon already → returned as is.

func SetBrandingStoragePath

func SetBrandingStoragePath(path string)

SetBrandingStoragePath sets where branding assets are stored, taking the place of the BRANDING_STORAGE_PATH environment variable.

func SetGlobalEventServer

func SetGlobalEventServer(server *PluginEventServer)

SetGlobalEventServer sets the global event server for plugin pub/sub access

func SetGlobalServiceReference

func SetGlobalServiceReference(service *Service)

SetGlobalServiceReference sets the global service reference for GRPCServer access

func ValidatePayloadAgainstSchema

func ValidatePayloadAgainstSchema(schema string, payload map[string]interface{}) error

ValidatePayloadAgainstSchema validates a submission payload against a resource type's submission schema. An empty schema accepts any payload. Returns a single error listing every violation.

func ValidatePortalDetailPath

func ValidatePortalDetailPath(path string) error

ValidatePortalDetailPath checks that a resource type's portal detail path is either empty or a same-origin path: it must start with a single "/" and carry no scheme, so a plugin cannot turn the catalog's link into an off-site or javascript: redirect. "{id}" is optional.

func ValidateSubmissionSchema

func ValidateSubmissionSchema(schema string) error

ValidateSubmissionSchema checks that a resource type's submission schema is either empty or a JSON Schema describing an object. Community submissions for the type are validated against it, and the portal renders a form from it.

Types

type AIStudioPluginClient

type AIStudioPluginClient struct {
	// contains filtered or unexported fields
}

AIStudioPluginClient wraps the plugin client with broker access for host service setup

func (*AIStudioPluginClient) AcceptEdgePayload

func (c *AIStudioPluginClient) AcceptEdgePayload(ctx context.Context, req *pb.EdgePayloadRequest, opts ...grpc.CallOption) (*pb.EdgePayloadResponse, error)

func (*AIStudioPluginClient) Authenticate

func (c *AIStudioPluginClient) Authenticate(ctx context.Context, req *pb.AuthRequest, opts ...grpc.CallOption) (*pb.AuthResponse, error)

func (*AIStudioPluginClient) Call

func (*AIStudioPluginClient) CloseSession

CloseSession explicitly closes an active session.

func (*AIStudioPluginClient) CreateResourceInstance

func (*AIStudioPluginClient) ExecuteScheduledTask

func (*AIStudioPluginClient) GetAppByCredential

func (c *AIStudioPluginClient) GetAppByCredential(ctx context.Context, req *pb.GetAppRequest, opts ...grpc.CallOption) (*pb.GetAppResponse, error)

func (*AIStudioPluginClient) GetAsset

func (*AIStudioPluginClient) GetConfigSchema

func (*AIStudioPluginClient) GetEndpointRegistrations

GetEndpointRegistrations queries the plugin for custom endpoint registrations.

func (*AIStudioPluginClient) GetManifest

func (*AIStudioPluginClient) GetObjectHookRegistrations

func (*AIStudioPluginClient) GetResourceInstance

func (*AIStudioPluginClient) GetUserByCredential

func (c *AIStudioPluginClient) GetUserByCredential(ctx context.Context, req *pb.GetUserRequest, opts ...grpc.CallOption) (*pb.GetUserResponse, error)

func (*AIStudioPluginClient) HandleAgentMessage

func (*AIStudioPluginClient) HandleAnalytics

func (*AIStudioPluginClient) HandleBudgetUsage

func (*AIStudioPluginClient) HandleEndpointRequest

func (c *AIStudioPluginClient) HandleEndpointRequest(ctx context.Context, req *pb.EndpointRequest, opts ...grpc.CallOption) (*pb.EndpointResponse, error)

HandleEndpointRequest forwards an HTTP request to the plugin's custom endpoint handler.

func (*AIStudioPluginClient) HandleEndpointRequestStream

HandleEndpointRequestStream forwards a streaming HTTP request to the plugin.

func (*AIStudioPluginClient) HandleObjectHook

func (c *AIStudioPluginClient) HandleObjectHook(ctx context.Context, req *pb.ObjectHookRequest, opts ...grpc.CallOption) (*pb.ObjectHookResponse, error)

func (*AIStudioPluginClient) HandleProxyLog

func (*AIStudioPluginClient) Initialize

func (c *AIStudioPluginClient) Initialize(ctx context.Context, req *pb.InitRequest, opts ...grpc.CallOption) (*pb.InitResponse, error)

Delegate all PluginServiceClient methods to the plugin stub (with correct signatures)

func (*AIStudioPluginClient) ListAssets

func (*AIStudioPluginClient) ListResourceInstances

func (*AIStudioPluginClient) OnBeforeWrite

func (*AIStudioPluginClient) OnBeforeWriteHeaders

func (c *AIStudioPluginClient) OnBeforeWriteHeaders(ctx context.Context, req *pb.HeadersRequest, opts ...grpc.CallOption) (*pb.HeadersResponse, error)

func (*AIStudioPluginClient) OnStreamComplete

func (*AIStudioPluginClient) OpenSession

OpenSession opens a long-lived session for broker access. This blocks until timeout or CloseSession is called.

func (*AIStudioPluginClient) Ping

func (*AIStudioPluginClient) PortalCall

func (*AIStudioPluginClient) ProcessPostAuth

func (c *AIStudioPluginClient) ProcessPostAuth(ctx context.Context, req *pb.EnrichedRequest, opts ...grpc.CallOption) (*pb.PluginResponse, error)

func (*AIStudioPluginClient) ProcessPreAuth

func (c *AIStudioPluginClient) ProcessPreAuth(ctx context.Context, req *pb.PluginRequest, opts ...grpc.CallOption) (*pb.PluginResponse, error)

func (*AIStudioPluginClient) SetupServiceBroker

func (c *AIStudioPluginClient) SetupServiceBroker() (uint32, error)

SetupServiceBroker creates a long-lived brokered server for AI Studio services Returns the broker ID that the plugin can use to dial back to host services

func (*AIStudioPluginClient) Shutdown

func (*AIStudioPluginClient) ValidateResourceSelection

type AIStudioPluginGRPC

type AIStudioPluginGRPC struct {
	goplugin.NetRPCUnsupportedPlugin
}

AIStudioPluginGRPC implements the goplugin.Plugin interface for gRPC

func (*AIStudioPluginGRPC) GRPCClient

func (p *AIStudioPluginGRPC) GRPCClient(ctx context.Context, broker *goplugin.GRPCBroker, c *grpc.ClientConn) (interface{}, error)

func (*AIStudioPluginGRPC) GRPCServer

func (p *AIStudioPluginGRPC) GRPCServer(broker *goplugin.GRPCBroker, s *grpc.Server) error

type AIStudioPluginManager

type AIStudioPluginManager struct {
	// contains filtered or unexported fields
}

AIStudioPluginManager manages AI Studio plugin lifecycle and execution Reuses proven patterns from microgateway's plugin manager

func NewAIStudioPluginManager

func NewAIStudioPluginManager(db *gorm.DB, ociClient *ociplugins.OCIPluginClient) *AIStudioPluginManager

NewAIStudioPluginManager creates a new AI Studio plugin manager

func (*AIStudioPluginManager) CallPluginPortalRPC

func (m *AIStudioPluginManager) CallPluginPortalRPC(pluginID uint, method string, payload map[string]interface{}, userCtx *pb.PortalUserContext) (interface{}, error)

CallPluginPortalRPC calls a plugin's portal RPC method via gRPC with user context. This is the portal-scoped equivalent of CallPluginRPC, using PortalCall instead of Call.

func (*AIStudioPluginManager) CallPluginRPC

func (m *AIStudioPluginManager) CallPluginRPC(pluginID uint, method string, payload map[string]interface{}) (interface{}, error)

CallPluginRPC calls a plugin's RPC method via gRPC

func (*AIStudioPluginManager) CallPluginRPCAs

func (m *AIStudioPluginManager) CallPluginRPCAs(pluginID uint, method string, payload map[string]interface{}, userCtx *pb.PortalUserContext) (interface{}, error)

CallPluginRPCAs is CallPluginRPC with the identity of the administrator issuing the call. Plugins implementing plugin_sdk.UserAwareRPCHandler receive it; others ignore it. userCtx may be nil.

func (*AIStudioPluginManager) CreateResourceInstance

func (m *AIStudioPluginManager) CreateResourceInstance(pluginID uint, resourceTypeSlug string, payload []byte, reviewerID uint) (*pb.ResourceInstanceProto, error)

CreateResourceInstance calls a plugin's CreateResourceInstance RPC. Used when an administrator approves a community submission for a plugin resource type. payload is the JSON-encoded plugin_sdk.SubmissionEnvelope.

func (*AIStudioPluginManager) ExecuteScheduledTask

func (m *AIStudioPluginManager) ExecuteScheduledTask(ctx context.Context, pluginID uint, contextProto *pb.PluginContext, scheduleProto *pb.ScheduleDefinition) (*pb.ExecuteScheduledTaskResponse, error)

ExecuteScheduledTask executes a scheduled task on a plugin via gRPC

func (*AIStudioPluginManager) GetEventServer

func (m *AIStudioPluginManager) GetEventServer() *PluginEventServer

GetEventServer returns the plugin event server

func (*AIStudioPluginManager) GetLoadedPlugin

func (m *AIStudioPluginManager) GetLoadedPlugin(pluginID uint) (*LoadedAIStudioPlugin, bool)

GetLoadedPlugin returns a loaded plugin by ID

func (*AIStudioPluginManager) GetPlugin

func (m *AIStudioPluginManager) GetPlugin(pluginID uint) (*LoadedAIStudioPlugin, error)

GetPlugin returns a loaded plugin by ID

func (*AIStudioPluginManager) GetPluginAsset

func (m *AIStudioPluginManager) GetPluginAsset(pluginID uint, assetPath string) ([]byte, string, error)

GetPluginAsset retrieves an asset from a loaded plugin via gRPC

func (*AIStudioPluginManager) GetPluginConfigSchema

func (m *AIStudioPluginManager) GetPluginConfigSchema(pluginID uint) (string, error)

GetPluginConfigSchema retrieves config schema from a plugin by ID

func (*AIStudioPluginManager) GetPluginManifest

func (m *AIStudioPluginManager) GetPluginManifest(pluginID uint) (string, error)

GetPluginManifest retrieves the manifest from a loaded plugin via gRPC

func (*AIStudioPluginManager) GetServiceProvider

func (m *AIStudioPluginManager) GetServiceProvider(pluginID uint) (plugin_services.AIStudioServiceProvider, bool)

GetServiceProvider returns the service provider for a loaded plugin

func (*AIStudioPluginManager) InjectTestPlugin

func (m *AIStudioPluginManager) InjectTestPlugin(pluginID uint, name string, grpcClient pb.PluginServiceClient)

InjectTestPlugin injects a mock loaded plugin for testing purposes. This allows API handler tests to simulate a loaded plugin without starting a real plugin process.

func (*AIStudioPluginManager) IsPluginLoaded

func (m *AIStudioPluginManager) IsPluginLoaded(pluginID uint) bool

IsPluginLoaded checks if a plugin is currently loaded

func (*AIStudioPluginManager) ListPluginAssets

func (m *AIStudioPluginManager) ListPluginAssets(pluginID uint, pathPrefix string) ([]AssetInfo, error)

ListPluginAssets lists all assets available from a plugin

func (*AIStudioPluginManager) ListResourceInstances

func (m *AIStudioPluginManager) ListResourceInstances(pluginID uint, resourceTypeSlug string) ([]*pb.ResourceInstanceProto, error)

ListResourceInstances calls a plugin's ListResourceInstances RPC to get all instances of a given resource type. Used by the service layer to cache instance details.

func (*AIStudioPluginManager) LoadAllUIAndAgentPlugins

func (m *AIStudioPluginManager) LoadAllUIAndAgentPlugins() error

LoadAllUIAndAgentPlugins loads all active plugins that support studio_ui or agent hooks

func (*AIStudioPluginManager) LoadPlugin

func (m *AIStudioPluginManager) LoadPlugin(pluginID uint) (*LoadedAIStudioPlugin, error)

LoadPlugin loads an AI Studio plugin by ID

func (*AIStudioPluginManager) LoadPluginForConfigOnly

func (m *AIStudioPluginManager) LoadPluginForConfigOnly(ctx context.Context, command string) (ConfigProvider, error)

LoadPluginForConfigOnly loads a plugin with minimal resources for schema extraction Uses universal config provider handshake (AI_STUDIO_PLUGIN + "config" service) All plugins now use the unified handshake, eliminating the need for fallback logic

func (*AIStudioPluginManager) PingPlugin

func (m *AIStudioPluginManager) PingPlugin(pluginID uint) error

PingPlugin performs a health check on a loaded plugin

func (*AIStudioPluginManager) RemoveTestPlugin

func (m *AIStudioPluginManager) RemoveTestPlugin(pluginID uint)

RemoveTestPlugin removes a previously injected test plugin.

func (*AIStudioPluginManager) RouteEdgePayload

func (m *AIStudioPluginManager) RouteEdgePayload(ctx context.Context, payload *pb.PluginControlPayload) error

RouteEdgePayload routes a payload from an edge instance to the corresponding AI Studio plugin This implements the EdgePayloadRouter interface required by the control server

func (*AIStudioPluginManager) SetEventBus

func (m *AIStudioPluginManager) SetEventBus(bus eventbridge.Bus, nodeID string)

SetEventBus creates a PluginEventServer from the given event bus and node ID. This enables plugin pub/sub functionality.

func (*AIStudioPluginManager) SetManifestService

func (m *AIStudioPluginManager) SetManifestService(manifestService *PluginManifestService)

SetManifestService sets the manifest service (to avoid circular dependency)

func (*AIStudioPluginManager) SetSecurityService

func (m *AIStudioPluginManager) SetSecurityService(service plugin_security.Service)

SetSecurityService sets the security service used for OCI signature verification and load-time command validation

func (*AIStudioPluginManager) SetService

func (m *AIStudioPluginManager) SetService(service *Service)

SetService sets the main service reference (to avoid circular dependency)

func (*AIStudioPluginManager) Shutdown

func (m *AIStudioPluginManager) Shutdown() error

Shutdown gracefully shuts down all loaded plugins

func (*AIStudioPluginManager) UnloadConfigProvider

func (m *AIStudioPluginManager) UnloadConfigProvider(provider ConfigProvider) error

UnloadConfigProvider releases resources used by a ConfigProvider

func (*AIStudioPluginManager) UnloadPlugin

func (m *AIStudioPluginManager) UnloadPlugin(pluginID uint) error

UnloadPlugin unloads an AI Studio plugin

type AccessTokenService

type AccessTokenService struct {
	// contains filtered or unexported fields
}

AccessTokenService handles business logic for access tokens.

func NewAccessTokenService

func NewAccessTokenService(db *gorm.DB) *AccessTokenService

NewAccessTokenService creates a new AccessTokenService.

func (*AccessTokenService) CreateAccessToken

func (s *AccessTokenService) CreateAccessToken(args CreateAccessTokenArgs) (*models.AccessToken, string, error)

CreateAccessToken generates, stores, and returns a new access token. The actual token value is also returned for immediate use.

func (*AccessTokenService) GetValidAccessTokenByToken

func (s *AccessTokenService) GetValidAccessTokenByToken(tokenValue string) (*models.AccessToken, error)

GetValidAccessTokenByToken retrieves an access token by its value and checks if it's valid (not expired).

type AccessiblePluginResourceType

type AccessiblePluginResourceType struct {
	Type      models.PluginResourceType
	Instances []*pb.ResourceInstanceProto
}

AccessiblePluginResourceType is one plugin resource type with the active instances a user may use.

type AppGovernanceFlag

type AppGovernanceFlag struct {
	Value  string    `json:"value"`
	Reason string    `json:"reason,omitempty"`
	SetBy  string    `json:"set_by,omitempty"`
	At     time.Time `json:"at"`
}

AppGovernanceFlag is one flag on an App.

type AppOption

type AppOption func(*appOptions)

AppOption adjusts an App create or update.

func WithAppTeam

func WithAppTeam(teamID uint) AppOption

WithAppTeam attributes the App to the given team instead of the owner's resolved budget team (administrators only).

func WithModelRouters

func WithModelRouters(ids []uint) AppOption

WithModelRouters sets the App's Model Router grants. Callers check visibility first (ValidateModelRouterBindings).

func WithSemanticRouters

func WithSemanticRouters(ids []uint) AppOption

WithSemanticRouters sets the App's Semantic Router grants. Callers check visibility first (ValidateSemanticRouterBindings).

type AssetInfo

type AssetInfo struct {
	Path     string `json:"path"`
	MimeType string `json:"mime_type"`
	Size     int64  `json:"size"`
}

AssetInfo represents information about a plugin asset

type AuthCodeService

type AuthCodeService struct {
	// contains filtered or unexported fields
}

AuthCodeService handles business logic for authorization codes.

func NewAuthCodeService

func NewAuthCodeService(db *gorm.DB) *AuthCodeService

NewAuthCodeService creates a new AuthCodeService.

func (*AuthCodeService) CreateAuthCode

func (s *AuthCodeService) CreateAuthCode(args CreateAuthCodeArgs) (*models.AuthCode, string, error)

CreateAuthCode generates, stores, and returns a new authorization code.

func (*AuthCodeService) GetValidAuthCodeByCode

func (s *AuthCodeService) GetValidAuthCodeByCode(codeValue string) (*models.AuthCode, error)

GetValidAuthCodeByCode retrieves an authorization code by its value, checking for expiry and if it has already been used.

func (*AuthCodeService) MarkAuthCodeAsUsed

func (s *AuthCodeService) MarkAuthCodeAsUsed(codeValue string) error

MarkAuthCodeAsUsed marks an authorization code as used.

type BrandingFileStorage

type BrandingFileStorage struct {
	BasePath string
}

BrandingFileStorage handles file operations for branding assets

func NewBrandingFileStorage

func NewBrandingFileStorage(basePath string) (*BrandingFileStorage, error)

NewBrandingFileStorage creates a new branding file storage instance

func (*BrandingFileStorage) DeleteFavicon

func (bfs *BrandingFileStorage) DeleteFavicon(filename string) error

DeleteFavicon deletes the current favicon file

func (bfs *BrandingFileStorage) DeleteLogo(filename string) error

DeleteLogo deletes the current logo file

func (*BrandingFileStorage) FileExists

func (bfs *BrandingFileStorage) FileExists(filename string) bool

FileExists checks if a file exists in the branding storage

func (*BrandingFileStorage) GetFilePath

func (bfs *BrandingFileStorage) GetFilePath(filename string) string

GetFilePath returns the full path to a branding file

func (*BrandingFileStorage) SaveFavicon

func (bfs *BrandingFileStorage) SaveFavicon(file multipart.File, header *multipart.FileHeader) (string, error)

SaveFavicon saves an uploaded favicon file

func (bfs *BrandingFileStorage) SaveLogo(file multipart.File, header *multipart.FileHeader) (string, error)

SaveLogo saves an uploaded logo file

type BudgetService

type BudgetService = budget.Service

BudgetService is a type alias for backward compatibility. Use budget.Service interface in new code.

type BudgetServiceInterface

type BudgetServiceInterface interface {
	CheckBudget(app *models.App, llm *models.LLM) (float64, float64, error)
	AnalyzeBudgetUsage(app *models.App, llm *models.LLM)
}

BudgetServiceInterface defines budget operations needed by the application. This interface allows implementations to use databases, files, or other storage backends.

type CatalogueGroup

type CatalogueGroup struct {
	ID          uint   `json:"id"`
	Name        string `json:"name"`
	MemberCount int64  `json:"member_count"`
}

CatalogueGroup is one team that has been granted a catalogue, with its live member count, for the "teams using this catalogue" panel on the catalogue page and the delete confirmation.

type CatalogueRouters

type CatalogueRouters struct {
	ModelRouters    []models.ModelRouter
	SemanticRouters []models.SemanticRouter
}

CatalogueRouters are the routers published in one LLM catalogue.

type Config

type Config struct {
	APISecret string
	LogLevel  string
	// CookieSecure marks the broker's state cookie Secure (see
	// sso.NewStateStore).
	CookieSecure bool
}

type ConfigOnlyGRPC

type ConfigOnlyGRPC struct {
	goplugin.NetRPCUnsupportedPlugin
}

ConfigOnlyGRPC implements goplugin.Plugin interface for config-only extraction Uses a universal handshake that works with any plugin type

func (*ConfigOnlyGRPC) GRPCClient

func (p *ConfigOnlyGRPC) GRPCClient(ctx context.Context, broker *goplugin.GRPCBroker, c *grpc.ClientConn) (interface{}, error)

func (*ConfigOnlyGRPC) GRPCServer

func (p *ConfigOnlyGRPC) GRPCServer(broker *goplugin.GRPCBroker, s *grpc.Server) error

type ConfigOnlyPlugin

type ConfigOnlyPlugin struct {
	Command          string
	Client           *goplugin.Client
	ConfigGRPCClient configpb.ConfigProviderServiceClient
	LoadTime         time.Time
}

ConfigOnlyPlugin represents a plugin loaded only for configuration schema extraction Uses the isolated ConfigProviderService instead of the main PluginService

func (*ConfigOnlyPlugin) GetConfigSchema

func (cp *ConfigOnlyPlugin) GetConfigSchema(ctx context.Context) ([]byte, error)

GetConfigSchema implements ConfigProvider interface for ConfigOnlyPlugin

func (*ConfigOnlyPlugin) GetManifest

func (cp *ConfigOnlyPlugin) GetManifest(ctx context.Context) ([]byte, error)

GetManifest implements EnhancedConfigProvider interface for ConfigOnlyPlugin

type ConfigProvider

type ConfigProvider interface {
	// GetConfigSchema returns the JSON Schema for the plugin's configuration
	// The returned schema should be valid JSON Schema (jsonschema.org format)
	// Returns (schemaJSON, error) where schemaJSON is the schema as JSON string
	GetConfigSchema(ctx context.Context) ([]byte, error)
}

ConfigProvider is a minimal interface for loading plugins ONLY to get their configuration schema. This allows AI Studio to load plugins with minimal resource usage for schema extraction only. The interface is kept minimal to reduce the plugin loading footprint.

type ConfigProviderLoader

type ConfigProviderLoader interface {
	// LoadPluginForConfigOnly loads a plugin with minimal resources for schema extraction
	// command: the plugin command (e.g., "./my-plugin", "oci://registry/plugin:v1.0.0")
	// Returns a ConfigProvider interface that can be used to get the schema
	LoadPluginForConfigOnly(ctx context.Context, command string) (ConfigProvider, error)

	// UnloadConfigProvider releases resources used by a ConfigProvider
	// This should be called after schema extraction is complete
	UnloadConfigProvider(provider ConfigProvider) error
}

ConfigProviderLoader manages loading plugins as ConfigProviders

type ConfigSchemaService

type ConfigSchemaService interface {
	// GetPluginConfigSchema retrieves the schema for a plugin, using cache when possible
	GetPluginConfigSchema(ctx context.Context, pluginID uint) (string, error)

	// GetPluginConfigSchemaByCommand retrieves schema by command, using cache when possible
	GetPluginConfigSchemaByCommand(ctx context.Context, command string) (string, error)

	// RefreshPluginConfigSchema forces a refresh of the schema from the plugin
	RefreshPluginConfigSchema(ctx context.Context, pluginID uint) (string, error)

	// ValidatePluginConfig validates a config map against the plugin's schema
	ValidatePluginConfig(ctx context.Context, pluginID uint, config map[string]interface{}) error

	// InvalidateSchemaCache removes a schema from the cache
	InvalidateSchemaCache(command string) error
}

ConfigSchemaService provides high-level configuration schema operations

type CreateAccessTokenArgs

type CreateAccessTokenArgs struct {
	ClientID  string
	UserID    uint
	Scope     string
	ExpiresIn time.Duration // How long the token is valid for
	// AppID binds the token to the app chosen at consent. A token minted without
	// it authorises no resource at the gateway.
	AppID *uint
}

CreateAccessTokenArgs holds arguments for creating an access token.

type CreateAuthCodeArgs

type CreateAuthCodeArgs struct {
	ClientID            string
	UserID              uint
	RedirectURI         string
	Scope               string
	ExpiresIn           time.Duration // How long the code is valid for
	CodeChallenge       string
	CodeChallengeMethod string
	AppID               *uint // Selected app ID for MCP OAuth
}

CreateAuthCodeArgs holds arguments for creating an authorization code.

type CreateOCIPluginRequest

type CreateOCIPluginRequest struct {
	Name         string                 `json:"name" binding:"required"`
	Description  string                 `json:"description"`
	OCIReference string                 `json:"oci_reference" binding:"required"`
	Config       map[string]interface{} `json:"config"`
	HookType     string                 `json:"hook_type" binding:"required"`
	IsActive     bool                   `json:"is_active"`
	Namespace    string                 `json:"namespace,omitempty"`
}

CreateOCIPluginRequest represents a request to create a plugin from an OCI artifact

type CreatePluginRequest

type CreatePluginRequest struct {
	Name                string                 `json:"name" binding:"required"`
	Description         string                 `json:"description"`
	Command             string                 `json:"command" binding:"required"`
	Checksum            string                 `json:"checksum"` // Optional
	Config              map[string]interface{} `json:"config"`
	HookType            string                 `json:"hook_type"` // Optional - will be populated from manifest
	HookTypes           []string               `json:"hook_types"`
	HookTypesCustomized bool                   `json:"hook_types_customized"`
	IsActive            bool                   `json:"is_active"`
	Namespace           string                 `json:"namespace,omitempty"`
	OCIReference        string                 `json:"oci_reference,omitempty"`    // OCI artifact reference
	LoadImmediately     bool                   `json:"load_immediately,omitempty"` // Auto-load AI Studio plugins
}

Plugin request/response structures (adapted from microgateway)

type DatasourceTestResult

type DatasourceTestResult struct {
	EmbedderValid   bool   `json:"embedder_valid"`
	EmbedderError   string `json:"embedder_error,omitempty"`
	EmbedderVendor  string `json:"embedder_vendor"`
	EmbedderModel   string `json:"embedder_model"`
	EmbedTestPassed bool   `json:"embed_test_passed"`
	EmbedTestError  string `json:"embed_test_error,omitempty"`
}

DatasourceTestResult contains the result of datasource connectivity testing

type DependentRef

type DependentRef struct {
	ID   uint   `json:"id"`
	Name string `json:"name"`
}

DependentRef identifies one object that references another.

type Dependents

type Dependents struct {
	Apps         []DependentRef `json:"apps"`
	Catalogues   []DependentRef `json:"catalogues"`
	LLMs         []DependentRef `json:"llms"`
	Tools        []DependentRef `json:"tools"`
	Datasources  []DependentRef `json:"datasources"`
	Agents       []DependentRef `json:"agents"`
	ModelRouters []DependentRef `json:"model_routers"`
	// SemanticRouters that route to, hand off to, or classify with the object.
	SemanticRouters []DependentRef `json:"semantic_routers"`
	Chats           []DependentRef `json:"chats"`
	// Embedders linked to the object (an LLM).
	Embedders []DependentRef `json:"embedders"`
	Total     int            `json:"total"`
}

Dependents lists every object that references a given object, grouped by type. Every slice is non-nil so the JSON always carries every array, and Total is the sum of their lengths.

This is what the delete confirmation shows ("used by 2 apps and 1 catalogue") and what the object page uses to explain where something is exposed. The queries are plain joins on the association tables so they run the same on SQLite and Postgres.

type EdgeInstanceWithHealth

type EdgeInstanceWithHealth struct {
	*models.EdgeInstance
	IsHealthy     bool          `json:"is_healthy"`
	LastHeartbeat time.Duration `json:"last_heartbeat_ago,omitempty"`
}

EdgeInstanceWithHealth represents an edge instance with health status

type EdgeService

type EdgeService struct {
	// contains filtered or unexported fields
}

EdgeService handles edge instance management for hub-and-spoke architecture

func NewEdgeService

func NewEdgeService(db *gorm.DB) *EdgeService

NewEdgeService creates a new EdgeService

func (*EdgeService) CleanupStaleEdges

func (s *EdgeService) CleanupStaleEdges(maxAge time.Duration) error

CleanupStaleEdges marks edges as disconnected if they haven't sent heartbeat recently

func (*EdgeService) CreateOrUpdateEdge

func (s *EdgeService) CreateOrUpdateEdge(edgeID, namespace, version, buildHash string, metadata map[string]interface{}) (*models.EdgeInstance, error)

CreateOrUpdateEdge creates a new edge instance or updates existing one

func (*EdgeService) DeleteEdge

func (s *EdgeService) DeleteEdge(edgeID string) error

DeleteEdge removes an edge instance

func (*EdgeService) GetConnectedEdges

func (s *EdgeService) GetConnectedEdges() ([]EdgeInstanceWithHealth, error)

GetConnectedEdges returns all currently connected edges across all namespaces

func (*EdgeService) GetEdgeByEdgeID

func (s *EdgeService) GetEdgeByEdgeID(edgeID string) (*EdgeInstanceWithHealth, error)

GetEdgeByEdgeID returns an edge instance by its edge ID (string identifier)

func (*EdgeService) GetEdgeByID

func (s *EdgeService) GetEdgeByID(id uint) (*EdgeInstanceWithHealth, error)

GetEdgeByID returns an edge instance by its database ID

func (*EdgeService) GetEdgeStatistics

func (s *EdgeService) GetEdgeStatistics(namespace string) (*EdgeStatistics, error)

GetEdgeStatistics returns statistics for edges in a namespace

func (*EdgeService) GetEdgesInNamespace

func (s *EdgeService) GetEdgesInNamespace(namespace string) ([]EdgeInstanceWithHealth, error)

GetEdgesInNamespace returns all edges in a specific namespace

func (*EdgeService) ListEdges

func (s *EdgeService) ListEdges(namespace string, status string, page, limit int) ([]EdgeInstanceWithHealth, int64, error)

ListEdges returns paginated list of edge instances with optional filtering

func (*EdgeService) UpdateEdgeHeartbeat

func (s *EdgeService) UpdateEdgeHeartbeat(edgeID string) error

UpdateEdgeHeartbeat updates the heartbeat timestamp for an edge

func (*EdgeService) UpdateEdgeStatus

func (s *EdgeService) UpdateEdgeStatus(edgeID string, status string) error

UpdateEdgeStatus updates the status of an edge instance

type EdgeStatistics

type EdgeStatistics struct {
	TotalEdges        int64 `json:"total_edges"`
	ConnectedEdges    int64 `json:"connected_edges"`
	HealthyEdges      int64 `json:"healthy_edges"`
	DisconnectedEdges int64 `json:"disconnected_edges"`
	UnhealthyEdges    int64 `json:"unhealthy_edges"`
}

EdgeStatistics contains edge statistics for a namespace

type EmbedderInUseError

type EmbedderInUseError struct {
	Dependents *Dependents
}

EmbedderInUseError refuses a delete while other objects embed with the embedder.

func (*EmbedderInUseError) Error

func (e *EmbedderInUseError) Error() string

type EmbedderInput

type EmbedderInput struct {
	EmbedderID *uint
	Vendor     string
	URL        string
	APIKey     string
	Model      string

	// VectorConn and VectorAPIKey are the datasource's vector store
	// connection string and key. The Vertex embedder used to read its
	// project:location and key from them, and clients (the portal's
	// submission form among them) still send Vertex settings that way: a
	// Vertex configuration without its own URL takes them.
	VectorConn   string
	VectorAPIKey string

	// Namespace is the datasource's namespace: an embedder linked to an LLM
	// scoped to another namespace is refused (models.UsableInNamespace).
	Namespace string
}

EmbedderInput is how a datasource write names its embedder. EmbedderID, when set, wins (0 unlinks). Otherwise the legacy inline fields (the datasource API's embed_vendor/url/api_key/model) describe the embedding configuration and are resolved to an embedder: see resolveDatasourceEmbedder.

type EmbedderLockedError

type EmbedderLockedError struct {
	Datasources []DependentRef
}

EmbedderLockedError refuses a change to the model or API compatibility of an embedder that datasources use: their stored vectors came from the current model, so new queries embedded another way would not match them.

func (*EmbedderLockedError) Error

func (e *EmbedderLockedError) Error() string

type EmbedderNamespaceError

type EmbedderNamespaceError struct {
	Namespace string
	Consumers []DependentRef
}

EmbedderNamespaceError refuses a change that would leave datasources or routers using an embedder whose LLM is scoped to another namespace.

func (*EmbedderNamespaceError) Error

func (e *EmbedderNamespaceError) Error() string

type EmbedderPrivacyError

type EmbedderPrivacyError struct {
	EmbedderScore int
	Required      int
	Datasource    string
}

EmbedderPrivacyError refuses a pairing where the embedder is trusted with less than the data it would see.

func (*EmbedderPrivacyError) Error

func (e *EmbedderPrivacyError) Error() string

type EnhancedConfigProvider

type EnhancedConfigProvider interface {
	ConfigProvider
	// GetManifest returns the plugin manifest as JSON bytes
	GetManifest(ctx context.Context) ([]byte, error)
}

EnhancedConfigProvider extends ConfigProvider to include manifest support This interface will be implemented by config providers that support the enhanced protocol

type FilterSpec

type FilterSpec struct {
	Name           string
	Description    string
	Script         []byte
	ResponseFilter bool
	Namespace      string
	Kind           string
	Config         models.JSONMap
}

FilterSpec is the full set of attributes a filter is created or updated with. Kind selects a script filter (Script) or a guardrail filter (Config, validated against the provider catalogue and stored normalised so edges receive explicit defaults).

type GroupPluginResourceUpdate

type GroupPluginResourceUpdate struct {
	ResourceTypeID uint
	InstanceIDs    []string
}

GroupPluginResourceUpdate represents a single resource type update for a group.

type HookExecutionResult

type HookExecutionResult struct {
	Allowed         bool              // Whether operation should proceed
	RejectionReason string            // Why operation was rejected (if any)
	ModifiedObject  interface{}       // Modified object (if any plugin modified it)
	Metadata        map[string]string // Merged metadata from all plugins
	Executed        []string          // List of plugins that executed
	Errors          []error           // Non-fatal errors during execution
}

HookExecutionResult contains the result of executing all hooks for an operation

type HookManager

type HookManager struct {
	// contains filtered or unexported fields
}

HookManager executes hooks for object CRUD operations

func NewHookManager

func NewHookManager(registry *HookRegistry, pluginManager *AIStudioPluginManager) *HookManager

NewHookManager creates a new hook manager

func (*HookManager) ExecuteHooks

func (m *HookManager) ExecuteHooks(
	ctx context.Context,
	objectType ObjectType,
	hookType HookType,
	object interface{},
	userID uint32,
) (*HookExecutionResult, error)

ExecuteHooks executes all registered hooks for a specific operation

func (*HookManager) MergeMetadata

func (m *HookManager) MergeMetadata(object interface{}, hookMetadata map[string]string) error

MergeMetadata merges plugin metadata into the object's metadata field

func (*HookManager) SetTimeout

func (m *HookManager) SetTimeout(timeout time.Duration)

SetTimeout sets the timeout for hook execution

type HookRegistration

type HookRegistration struct {
	PluginID   uint32     `json:"plugin_id"`
	PluginName string     `json:"plugin_name"`
	ObjectType ObjectType `json:"object_type"`
	HookType   HookType   `json:"hook_type"`
	Priority   int32      `json:"priority"`
	Enabled    bool       `json:"enabled"`
}

HookRegistration represents a plugin's registration for a specific hook

type HookRegistry

type HookRegistry struct {
	// contains filtered or unexported fields
}

HookRegistry manages hook registrations from plugins

func NewHookRegistry

func NewHookRegistry() *HookRegistry

NewHookRegistry creates a new hook registry

func (*HookRegistry) DisableHook

func (r *HookRegistry) DisableHook(pluginID uint32, objectType ObjectType, hookType HookType) error

DisableHook disables a specific hook registration

func (*HookRegistry) EnableHook

func (r *HookRegistry) EnableHook(pluginID uint32, objectType ObjectType, hookType HookType) error

EnableHook enables a specific hook registration

func (*HookRegistry) GetAllRegistrations

func (r *HookRegistry) GetAllRegistrations() map[string][]*HookRegistration

GetAllRegistrations returns all hook registrations

func (*HookRegistry) GetHooks

func (r *HookRegistry) GetHooks(objectType ObjectType, hookType HookType) []*HookRegistration

GetHooks returns all registered hooks for a specific object type and hook type

func (*HookRegistry) GetPluginHooks

func (r *HookRegistry) GetPluginHooks(pluginID uint32) []*HookRegistration

GetPluginHooks returns all hooks registered by a specific plugin

func (*HookRegistry) RegisterHooks

func (r *HookRegistry) RegisterHooks(pluginID uint32, pluginName string, protoRegs []*pb.ObjectHookRegistration) error

RegisterHooks registers hooks for a plugin

func (*HookRegistry) UnregisterPlugin

func (r *HookRegistry) UnregisterPlugin(pluginID uint32)

UnregisterPlugin removes all hooks for a plugin

type HookType

type HookType string

HookType represents the stage at which a hook is invoked

const (
	HookBeforeCreate HookType = "before_create"
	HookAfterCreate  HookType = "after_create"
	HookBeforeUpdate HookType = "before_update"
	HookAfterUpdate  HookType = "after_update"
	HookBeforeDelete HookType = "before_delete"
	HookAfterDelete  HookType = "after_delete"
)

type HostIdentity

type HostIdentity struct {
	// Subject is the host's stable identifier for the user. Required.
	Subject string
	// Email and Name are kept in step with the host. Email is required.
	Email string
	Name  string
	// Admin makes the user a Studio administrator (an Administrator role
	// binding in Enterprise). The host is authoritative: false revokes it.
	Admin bool
	// Groups names the Studio groups (teams) the user belongs to, replacing
	// their memberships; every user also keeps the Default group. Nil leaves
	// memberships to Studio's own administration. Names Studio does not know
	// are ignored.
	Groups []string
	// Roles names the Studio roles (by slug: "editor", "viewer", a custom
	// role's slug) the host assigns the user, Enterprise. They are kept as
	// host-managed role bindings: added and removed as the host says, and
	// read-only in Studio's administration. Roles an administrator assigns
	// in Studio are left alone. Nil leaves host-managed roles as they are.
	// Admin remains the switch for the Administrator role.
	Roles []string
}

HostIdentity is a user as the host application Studio is embedded in has authenticated them.

type InternalTIB

type InternalTIB struct {
	// contains filtered or unexported fields
}

type LLMEmbedderConflictError

type LLMEmbedderConflictError struct {
	Reason    string
	Embedders []DependentRef
}

LLMEmbedderConflictError refuses an LLM change or delete that would break embedders linked to it.

func (*LLMEmbedderConflictError) Error

func (e *LLMEmbedderConflictError) Error() string

type LLMFailoverValidationError

type LLMFailoverValidationError struct {
	Index  int
	Field  string
	Detail string
}

LLMFailoverValidationError names the rung of the waterfall that failed validation so the API can answer 400 and the form can highlight the row. Index is -1 when the problem is not tied to one target.

func (*LLMFailoverValidationError) Error

type ListOptions

type ListOptions struct {
	Search   string
	Sort     string
	SortDesc bool
}

ListOptions carries the optional search and sort of a plain list endpoint (GET /llms, /tools, ...). Search is a case-insensitive substring match over the type's name and description-like columns; Sort is a column name from the type's whitelist, with Desc set for "-field". The API layer validates the sort field (api/list_query.go) so the column reaching here is trusted.

The zero value means "no search, default order", which is what every list did before these options existed.

func (ListOptions) Scopes

func (o ListOptions) Scopes(searchColumns ...string) []func(*gorm.DB) *gorm.DB

Scopes turns the options into GORM scopes for the model's GetAll.

type ListUsersParams

type ListUsersParams struct {
	Search         string
	ExcludeGroupID int
	PageSize       int
	PageNumber     int
	All            bool
	Sort           string

	// Optional filters: origin (models.AuthSource*), whether a key is
	// issued, and the disabled switch. nil / empty means "any".
	AuthSource string
	HasAPIKey  *bool
	Disabled   *bool
}

type LoadedAIStudioPlugin

type LoadedAIStudioPlugin struct {
	ID              uint
	Name            string
	PluginCategory  string // Human-readable category (e.g., "UI Extension", "Agent Plugin")
	Command         string
	IsOCI           bool
	Client          *goplugin.Client
	GRPCClient      pb.PluginServiceClient
	ServiceProvider plugin_services.AIStudioServiceProvider // Injected service provider
	SessionBrokerID uint32                                  // Long-lived broker ID for session-based service API access
	LoadTime        time.Time
	IsHealthy       bool
	LastPing        time.Time
}

LoadedAIStudioPlugin represents a loaded AI Studio plugin

type MarketplaceService

type MarketplaceService struct {
	// contains filtered or unexported fields
}

MarketplaceService handles marketplace operations

func NewMarketplaceService

func NewMarketplaceService(
	db *gorm.DB,
	ociClient *ociplugins.OCIPluginClient,
	pluginService *PluginService,
	pluginManager *AIStudioPluginManager,
	cacheDir string,
	defaultIndexURL string,
	syncInterval time.Duration,
) *MarketplaceService

NewMarketplaceService creates a new marketplace service

func (*MarketplaceService) CheckForUpdates

func (s *MarketplaceService) CheckForUpdates(ctx context.Context) error

CheckForUpdates refreshes the installed-version tracking for every plugin against the synced marketplace index.

func (*MarketplaceService) EnsureCacheDirectory

func (s *MarketplaceService) EnsureCacheDirectory() error

EnsureCacheDirectory ensures the marketplace cache directory exists

func (*MarketplaceService) GetAvailableUpdates

func (s *MarketplaceService) GetAvailableUpdates() (*marketplace.UpdateCheckResponse, error)

GetAvailableUpdates gets all plugins with available updates

func (*MarketplaceService) GetDB

func (s *MarketplaceService) GetDB() *gorm.DB

GetDB returns the database connection (for handlers)

func (*MarketplaceService) GetPlugin

func (s *MarketplaceService) GetPlugin(pluginID, version string) (*models.MarketplacePlugin, error)

GetPlugin gets a specific marketplace plugin

func (*MarketplaceService) GetPluginVersions

func (s *MarketplaceService) GetPluginVersions(pluginID string) ([]*models.MarketplacePlugin, error)

GetPluginVersions gets all versions of a marketplace plugin

func (*MarketplaceService) InstallFromMarketplace

InstallFromMarketplace installs a plugin from the marketplace

func (*MarketplaceService) OnPluginChanged

func (s *MarketplaceService) OnPluginChanged(pluginID uint)

OnPluginChanged re-links one plugin after its command may have changed.

func (*MarketplaceService) ReconcileInstalledVersions

func (s *MarketplaceService) ReconcileInstalledVersions(ctx context.Context, pluginIDs ...uint) error

ReconcileInstalledVersions is the single writer of installed_plugin_versions. It links installed OCI plugins back to their marketplace entry by OCI repository, records the installed and latest available versions, and removes tracking rows for plugins that no longer match anything (deleted, moved to a non-marketplace command). With no IDs it reconciles every plugin; with IDs it touches only those.

Because the link is derived from the command, installs made through the creation wizard - and installs that predate this tracking - are picked up without any install-time bookkeeping.

func (*MarketplaceService) SearchPlugins

SearchPlugins searches marketplace plugins

func (*MarketplaceService) Start

func (s *MarketplaceService) Start(ctx context.Context)

Start begins background marketplace sync

func (*MarketplaceService) Stop

func (s *MarketplaceService) Stop()

Stop stops the marketplace service

func (*MarketplaceService) SyncAll

func (s *MarketplaceService) SyncAll(ctx context.Context, forceRefresh bool) error

SyncAll syncs all active marketplace indexes. When forceRefresh is true, CDN caches are bypassed via cache-busting query params.

func (*MarketplaceService) SyncIndex

func (s *MarketplaceService) SyncIndex(ctx context.Context, idx *models.MarketplaceIndex, forceRefresh bool) error

SyncIndex syncs a single marketplace index. When forceRefresh is true, CDN caches are bypassed via cache-busting query params.

func (*MarketplaceService) UpgradeTargets

UpgradeTargets returns the marketplace versions the given installed plugin can move to (any version from the same OCI repository and marketplace ID, newest first), along with its tracking row.

type NamespaceInfo

type NamespaceInfo struct {
	Name        string `json:"name"`
	IsGlobal    bool   `json:"is_global"`
	EdgeCount   int64  `json:"edge_count"`
	LLMCount    int64  `json:"llm_count"`
	AppCount    int64  `json:"app_count"`
	TokenCount  int64  `json:"token_count"`
	FilterCount int64  `json:"filter_count"`
	PluginCount int64  `json:"plugin_count"`
}

NamespaceInfo contains information about a namespace

type NamespaceService

type NamespaceService struct {
	// contains filtered or unexported fields
}

NamespaceService handles namespace operations for hub-and-spoke architecture

func NewNamespaceService

func NewNamespaceService(db *gorm.DB, edgeService *EdgeService) *NamespaceService

NewNamespaceService creates a new NamespaceService

func (*NamespaceService) GetActiveNamespaces

func (s *NamespaceService) GetActiveNamespaces() ([]NamespaceInfo, error)

GetActiveNamespaces returns only namespaces that have active edges

func (*NamespaceService) GetEdgesInNamespace

func (s *NamespaceService) GetEdgesInNamespace(namespace string) ([]EdgeInstanceWithHealth, error)

GetEdgesInNamespace returns all edges in a specific namespace

func (*NamespaceService) GetNamespaceInfo

func (s *NamespaceService) GetNamespaceInfo(namespace string) (*NamespaceInfo, error)

GetNamespaceInfo returns detailed information about a specific namespace

func (*NamespaceService) GetNamespaceStatistics

func (s *NamespaceService) GetNamespaceStatistics() (map[string]*EdgeStatistics, error)

GetNamespaceStatistics returns comprehensive statistics for all namespaces

func (*NamespaceService) ListNamespaces

func (s *NamespaceService) ListNamespaces() ([]NamespaceInfo, error)

ListNamespaces returns all available namespaces with statistics

func (*NamespaceService) Pushes

func (s *NamespaceService) Pushes() *pushes.Coordinator

Pushes returns the push coordinator, or nil when there is none.

func (*NamespaceService) SetPushes

func (s *NamespaceService) SetPushes(c *pushes.Coordinator)

SetPushes sets the coordinator that records and delivers configuration pushes (see features/ClusterControlPlane.md).

func (*NamespaceService) TriggerAllReload

func (s *NamespaceService) TriggerAllReload(initiatedBy string) (*pushes.Result, error)

TriggerAllReload pushes the current configuration to every edge in every namespace, as one operation.

func (*NamespaceService) TriggerEdgeReload

func (s *NamespaceService) TriggerEdgeReload(edgeID string, initiatedBy string) (*pushes.Result, error)

TriggerEdgeReload pushes the current configuration to one edge. An edge that is not connected is waited for until the push's deadline.

func (*NamespaceService) TriggerNamespaceReload

func (s *NamespaceService) TriggerNamespaceReload(namespace string, initiatedBy string) (*pushes.Result, error)

TriggerNamespaceReload pushes the current configuration to every edge in the namespace. It returns once the push is recorded; delivery and the edges' answers are tracked on the returned operation.

func (*NamespaceService) ValidateNamespace

func (s *NamespaceService) ValidateNamespace(namespace string) (bool, error)

ValidateNamespace checks if a namespace exists (has any resources)

type NamespaceSyncSummary

type NamespaceSyncSummary struct {
	Namespace        string    `json:"namespace"`
	ExpectedChecksum string    `json:"expected_checksum"`
	ConfigVersion    string    `json:"config_version"`
	LastConfigChange time.Time `json:"last_config_change"`
	// LastPushAt is when a push was last issued for the namespace; nil
	// until the first one.
	LastPushAt   *time.Time `json:"last_push_at"`
	SyncedCount  int64      `json:"synced_count"`
	PendingCount int64      `json:"pending_count"`
	StaleCount   int64      `json:"stale_count"`
	UnknownCount int64      `json:"unknown_count"`
	TotalEdges   int64      `json:"total_edges"`
}

NamespaceSyncSummary represents sync status for a namespace with edge counts

type NonceTokenRequest

type NonceTokenRequest struct {
	ForSection                string
	OrgID                     string
	EmailAddress              string
	GroupID                   string
	GroupsIDs                 []string
	DisplayName               string
	SSOOnlyForRegisteredUsers bool
	ProfileID                 string    // identity provider profile the login came through; may be empty
	ExpiresAt                 time.Time // New field for expiry
}

type NonceTokenResponse

type NonceTokenResponse struct {
	Meta    *string `json:"Meta"`
	Status  string  `json:"Status"`
	Message string  `json:"Message"`
}

type NotificationCounts

type NotificationCounts struct {
	Total  int64
	Unread int64
}

ListUserNotifications returns one page of the user's notifications, newest first, with the total for that filter. unreadOnly restricts the page and the total to unread ones. NotificationCounts is the size of a user's inbox: every notification, and the unread ones.

type NotificationService

type NotificationService struct {
	// contains filtered or unexported fields
}

NotificationService handles notification creation, storage, and delivery

func NewNotificationService

func NewNotificationService(db *gorm.DB, fromEmail, smtpHost string, smtpPort int, smtpUser, smtpPass string, mailer notifications.Mailer) *NotificationService

NewNotificationService creates a new notification service

func NewTestNotificationService

func NewTestNotificationService(db *gorm.DB) *NotificationService

NewTestNotificationService creates a new test notification service

func (*NotificationService) BackfillLegacyBodies

func (s *NotificationService) BackfillLegacyBodies() (int64, error)

BackfillLegacyBodies rewrites in-app notifications recorded before email framing was stripped at write time, so the bell stops showing "Subject: ... Dear Administrator ...". It pages through the table in id order and matches in Go, which works the same on SQLite and Postgres, and is idempotent: a rewritten body no longer matches. Returns the number of rows changed.

func (*NotificationService) ClearNotifications

func (s *NotificationService) ClearNotifications()

ClearNotifications clears all stored notifications (for testing)

func (*NotificationService) GetMailer

func (s *NotificationService) GetMailer() notifications.Mailer

GetMailer returns the mailer for testing purposes

func (*NotificationService) GetNotifications

func (s *NotificationService) GetNotifications() []models.Notification

GetNotifications returns all stored notifications (for testing)

func (*NotificationService) GetUnreadCount

func (s *NotificationService) GetUnreadCount(userID uint) (int64, error)

GetUnreadCount returns the number of unread notifications for a user

func (*NotificationService) GetUserNotifications

func (s *NotificationService) GetUserNotifications(userID uint, limit, offset int) ([]models.Notification, error)

GetUserNotifications retrieves notifications for a specific user

func (*NotificationService) ListUserNotifications

func (s *NotificationService) ListUserNotifications(userID uint, limit, offset int, unreadOnly bool) ([]models.Notification, NotificationCounts, error)

ListUserNotifications returns one page of the user's notifications, newest first, plus the inbox counts. With unreadOnly the page holds only unread notifications and Total equals Unread. The counts come from one aggregate query, the page from one select.

func (*NotificationService) MarkAllAsRead

func (s *NotificationService) MarkAllAsRead(userID uint) error

MarkAllAsRead marks all unread notifications as read for a user

func (*NotificationService) MarkAsRead

func (s *NotificationService) MarkAsRead(userID uint, notificationID uint) error

MarkAsRead marks one of the user's notifications as read. A notification that does not exist or belongs to someone else yields ErrNotificationNotFound, so a caller cannot probe other users' ids.

func (*NotificationService) Notify

func (s *NotificationService) Notify(notificationID string, title string, templatePath string, data interface{}, userFlags uint) error

Notify creates and sends a notification using a template userFlags can be a specific user ID, models.NotifyAdmins, or a combination using bitwise OR (|)

func (*NotificationService) NotifyDirect

func (s *NotificationService) NotifyDirect(notificationID string, notifType string, title string, content string, userFlags uint) error

NotifyDirect creates and sends a notification with pre-rendered content (plain text or markdown; the email keeps it as given, the in-app record is reduced to plain text by stripMarkup). Use this when no email template applies, e.g. for notifications raised by plugins or by workflows whose content is composed in code.

notifType is stored on the record (e.g. "submission", "plugin:asset-catalog") and may be empty. userFlags follows the same convention as Notify.

func (*NotificationService) NotifyTemplate

func (s *NotificationService) NotifyTemplate(notificationID string, title string, templatePath string, data interface{}, userFlags uint, opts NotifyOptions) error

NotifyTemplate renders an email template and delivers it. The rendered template is the email body; the in-app record gets opts.Summary, or the rendered body with its email framing stripped when no summary is given.

func (*NotificationService) NotifyWithOptions

func (s *NotificationService) NotifyWithOptions(notificationID string, title string, content string, userFlags uint, opts NotifyOptions) error

NotifyWithOptions is the delivery core behind Notify, NotifyTemplate and NotifyDirect. content is the email body; the in-app record stores opts.Summary when given, otherwise content with its email framing removed. The actor named in opts never receives a copy.

func (*NotificationService) Send

func (s *NotificationService) Send(notification *models.Notification) error

Send creates and sends a notification, preventing duplicates based on NotificationID. The email body is the notification content.

type NotifyOptions

type NotifyOptions struct {
	// Type is stored on the record (e.g. "app", "user", "submission") and
	// may be empty.
	Type string
	// Link is the in-app path the notification points at ("/admin/apps/3").
	// Empty when there is nothing to open.
	Link string
	// ActorID is the user who performed the action. They are never a
	// recipient: an administrator does not need to be told about the app they
	// just created, and a user does not need to be told they registered.
	ActorID uint
	// Summary is the plain-text in-app content. When empty, the content
	// passed to NotifyWithOptions is used after stripEmailFraming.
	Summary string
	// SkipEmail records the notification without sending an email, for
	// callers that have already mailed the recipient through another path.
	SkipEmail bool
}

NotifyOptions refines how a notification is recorded and delivered.

type OAuthClientService

type OAuthClientService struct {
	// contains filtered or unexported fields
}

OAuthClientService handles business logic for OAuth clients.

func NewOAuthClientService

func NewOAuthClientService(db *gorm.DB) *OAuthClientService

NewOAuthClientService creates a new OAuthClientService.

func (*OAuthClientService) CreateClient

func (s *OAuthClientService) CreateClient(name string, redirectURIs []string, userID *uint, scope string) (*models.OAuthClient, string, error)

CreateClient creates a new OAuth client. It returns the client object and the plain text client secret (which should be shown to the user once). For public clients (isPublic=true), no client secret is generated.

func (*OAuthClientService) CreateClientWithAuthMethod

func (s *OAuthClientService) CreateClientWithAuthMethod(name string, redirectURIs []string, userID *uint, scope string, authMethod string) (*models.OAuthClient, string, error)

CreateClientWithAuthMethod creates a new OAuth client with specified auth method.

func (*OAuthClientService) GetClient

func (s *OAuthClientService) GetClient(clientID string) (*models.OAuthClient, error)

GetClient retrieves an OAuth client by its ID.

func (*OAuthClientService) IsPublicClient

func (s *OAuthClientService) IsPublicClient(client *models.OAuthClient) bool

IsPublicClient checks if the client is a public client (no client secret).

func (*OAuthClientService) ValidateClientSecret

func (s *OAuthClientService) ValidateClientSecret(client *models.OAuthClient, secret string) (bool, error)

ValidateClientSecret compares a provided secret with the stored hashed secret. For public clients, this always returns false.

func (*OAuthClientService) ValidateRedirectURI

func (s *OAuthClientService) ValidateRedirectURI(client *models.OAuthClient, redirectURI string) (bool, error)

ValidateRedirectURI checks if the provided redirectURI is valid for the client. The redirectURI must exactly match one of the registered URIs.

type ObjectEventPayload

type ObjectEventPayload struct {
	ObjectType string      `json:"object_type"` // "llm", "app", "datasource", "user", "group", "tool"
	Action     string      `json:"action"`      // "created", "updated", "deleted", "approved"
	ObjectID   uint        `json:"object_id"`   // ID of the affected object
	UserID     uint        `json:"user_id"`     // User who performed the action (0 if system/unknown)
	Timestamp  time.Time   `json:"timestamp"`   // When the event occurred
	Object     interface{} `json:"object"`      // The full object (for create/update, nil for delete)
}

ObjectEventPayload is the standard payload for all system CRUD events

type ObjectType

type ObjectType string

ObjectType represents the type of object being hooked

const (
	ObjectTypeLLM        ObjectType = "llm"
	ObjectTypeDatasource ObjectType = "datasource"
	ObjectTypeTool       ObjectType = "tool"
	ObjectTypeUser       ObjectType = "user"
	// ObjectTypeGovernedMetadata hooks fire on governed metadata records (Enterprise).
	// Only before_update/after_update/before_delete/after_delete are ever invoked.
	ObjectTypeGovernedMetadata ObjectType = "governed_metadata"
)

type PendingAuthRequestService

type PendingAuthRequestService struct {
	// contains filtered or unexported fields
}

PendingAuthRequestService handles business logic for pending OAuth authorization requests.

func NewPendingAuthRequestService

func NewPendingAuthRequestService(db *gorm.DB) *PendingAuthRequestService

NewPendingAuthRequestService creates a new PendingAuthRequestService.

func (*PendingAuthRequestService) DeletePendingAuthRequest

func (s *PendingAuthRequestService) DeletePendingAuthRequest(id string) error

DeletePendingAuthRequest removes a pending auth request from storage.

func (*PendingAuthRequestService) GetPendingAuthRequest

func (s *PendingAuthRequestService) GetPendingAuthRequest(id string, userID uint) (*models.PendingOAuthRequest, error)

GetPendingAuthRequest retrieves a pending auth request by its ID, checking for expiry. It also verifies that the provided userID matches the one in the stored request.

func (*PendingAuthRequestService) StorePendingAuthRequest

StorePendingAuthRequest creates a new unique ID, stores the request details, and returns the ID.

type PendingChange

type PendingChange struct {
	Type   string    `json:"type"`   // llm, app, filter, tool, datasource, plugin, model_router, semantic_router, model_price, oauth_client, access_token
	ID     uint      `json:"id"`     // object id
	Name   string    `json:"name"`   // display name at the time of the query
	Change string    `json:"change"` // created | updated | deleted
	At     time.Time `json:"at"`     // when that change happened
}

PendingChange is one object that changed since the last push.

type PendingChanges

type PendingChanges struct {
	// Namespace is the canonical spelling (models.CanonicalNamespace).
	Namespace string `json:"namespace"`
	// Since is the reference point: the namespace's last push, or -- when
	// no push was ever recorded but an edge is in sync with the namespace
	// checksum -- that edge's ack. Nil when there is neither, in which case
	// every object is "created". Baseline says which.
	Since      *time.Time      `json:"since"`
	LastPushAt *time.Time      `json:"last_push_at"`
	Baseline   string          `json:"baseline"` // push | edge_ack | none
	Total      int             `json:"total"`
	Changes    []PendingChange `json:"changes"`
}

PendingChanges is the response of GET /api/v1/sync/pending-changes.

type PluginEventServer

type PluginEventServer struct {
	pb.UnimplementedPluginEventServiceServer
	// contains filtered or unexported fields
}

PluginEventServer implements the PluginEventServiceServer interface for AI Studio. It bridges plugin event requests to the local eventbridge.Bus.

func NewPluginEventServer

func NewPluginEventServer(bus eventbridge.Bus, nodeID string) *PluginEventServer

NewPluginEventServer creates a new PluginEventServer instance. The bus parameter is the local event bus to publish/subscribe to. The nodeID identifies this node for event origin tracking.

func (*PluginEventServer) CleanupAllSubscriptions

func (s *PluginEventServer) CleanupAllSubscriptions()

CleanupAllSubscriptions removes all active subscriptions. Called during shutdown.

func (*PluginEventServer) GetActiveSubscriptionCount

func (s *PluginEventServer) GetActiveSubscriptionCount() int

GetActiveSubscriptionCount returns the number of active subscriptions. Useful for monitoring and debugging.

func (*PluginEventServer) Publish

Publish receives an event from a plugin and publishes it to the local bus. The event will be routed based on its direction field.

func (*PluginEventServer) Subscribe

Subscribe creates a subscription and streams events back to the plugin. The stream remains open until the client disconnects.

func (*PluginEventServer) Unsubscribe

Unsubscribe removes a subscription by ID. Note: This is optional since subscriptions are automatically cleaned up when the Subscribe stream closes.

type PluginGroupSummary

type PluginGroupSummary struct {
	ID        uint
	Name      string
	IsDefault bool
}

PluginGroupSummary is one team as a plugin sees it.

type PluginKVService

type PluginKVService struct {
	// contains filtered or unexported fields
}

PluginKVService implements key-value storage operations for AI Studio plugins

func NewPluginKVService

func NewPluginKVService(db *gorm.DB) *PluginKVService

NewPluginKVService creates a new plugin KV service

func (*PluginKVService) CleanupExpiredData

func (s *PluginKVService) CleanupExpiredData(gracePeriod time.Duration) (int64, error)

CleanupExpiredData deletes plugin data entries that have expired beyond the grace period gracePeriod is the time to wait after expiration before actually deleting (handles clock skew)

func (*PluginKVService) ClearAllPluginData

func (s *PluginKVService) ClearAllPluginData(pluginID uint) error

ClearAllPluginData deletes all key-value entries for a specific plugin

func (*PluginKVService) CountPluginData

func (s *PluginKVService) CountPluginData(pluginID uint) (int64, error)

CountPluginData returns the count of key-value entries for a specific plugin

func (*PluginKVService) DeleteKV

func (s *PluginKVService) DeleteKV(pluginID uint, key string) (bool, error)

DeleteKV deletes a key-value entry for a plugin Returns true if the key existed and was deleted, false if the key didn't exist

func (*PluginKVService) ListPluginKeys

func (s *PluginKVService) ListPluginKeys(pluginID uint) ([]string, error)

ListPluginKeys returns all keys for a specific plugin

func (*PluginKVService) ReadKV

func (s *PluginKVService) ReadKV(pluginID uint, key string) ([]byte, error)

ReadKV retrieves a value by key for a specific plugin Returns error if key is not found or has expired

func (*PluginKVService) StartCleanupRoutine

func (s *PluginKVService) StartCleanupRoutine(interval, gracePeriod time.Duration)

StartCleanupRoutine starts a background goroutine that periodically cleans up expired data interval is how often to run the cleanup gracePeriod is the time to wait after expiration before actually deleting

func (*PluginKVService) WriteKV

func (s *PluginKVService) WriteKV(pluginID uint, key string, value []byte, expireAt *time.Time) (bool, error)

WriteKV creates or updates a key-value entry for a plugin Returns true if a new entry was created, false if an existing entry was updated expireAt is optional - pass nil for no expiration

type PluginManifestService

type PluginManifestService struct {
	// contains filtered or unexported fields
}

PluginManifestService handles plugin manifest parsing and UI registration

func NewPluginManifestService

func NewPluginManifestService(db *gorm.DB, ociClient *ociplugins.OCIPluginClient) *PluginManifestService

NewPluginManifestService creates a new plugin manifest service

func (*PluginManifestService) GetPluginAssets

func (s *PluginManifestService) GetPluginAssets(pluginID uint) ([]string, error)

GetPluginAssets returns asset paths for a plugin

func (*PluginManifestService) GetPortalSidebarMenuItemsForUser

func (s *PluginManifestService) GetPortalSidebarMenuItemsForUser(userGroups []string) ([]SidebarMenuItem, error)

GetPortalSidebarMenuItemsForUser returns portal sidebar menu items filtered by user's groups

func (*PluginManifestService) GetPortalUIRegistryForUser

func (s *PluginManifestService) GetPortalUIRegistryForUser(userGroups []string) ([]models.UIRegistry, error)

GetPortalUIRegistryForUser returns active portal UI components filtered by user's groups. If AllowedGroups is empty for an entry, it is visible to all portal users. If AllowedGroups has values, at least one of the user's groups must match.

func (*PluginManifestService) GetSidebarMenuItems

func (s *PluginManifestService) GetSidebarMenuItems() ([]SidebarMenuItem, error)

GetSidebarMenuItems returns sidebar menu items from registered plugins grouped by plugin

func (*PluginManifestService) GetSidebarMenuItemsFor

func (s *PluginManifestService) GetSidebarMenuItemsFor(allowed func(requiredPermission string) bool) ([]SidebarMenuItem, error)

GetSidebarMenuItemsFor returns the sidebar sections the caller may see: sub-items whose required permission the caller lacks are dropped, and a section is dropped when nothing in it survives.

func (*PluginManifestService) GetUIRegistry

func (s *PluginManifestService) GetUIRegistry() ([]models.UIRegistry, error)

GetUIRegistry returns all active admin UI components for the frontend

func (*PluginManifestService) LoadPluginUI

func (s *PluginManifestService) LoadPluginUI(pluginID uint) error

LoadPluginUI marks a plugin's UI as loaded and updates the registry

func (*PluginManifestService) ParsePluginManifest

func (s *PluginManifestService) ParsePluginManifest(plugin *models.Plugin) (*models.PluginManifest, error)

ParsePluginManifest extracts and parses the manifest from an OCI plugin

func (*PluginManifestService) RegisterPluginUI

func (s *PluginManifestService) RegisterPluginUI(plugin *models.Plugin, manifest *models.PluginManifest) error

RegisterPluginUI registers plugin UI components in the system

func (*PluginManifestService) ServePluginAsset

func (s *PluginManifestService) ServePluginAsset(pluginID uint, assetPath string) (string, error)

ServePluginAsset serves plugin assets with proper path resolution

func (*PluginManifestService) SetPermissionSync

func (s *PluginManifestService) SetPermissionSync(fn pluginPermissionSyncer)

SetPermissionSync installs the callback that refreshes a plugin's permission resource once its manifest (and therefore its stable permission key) is known.

func (*PluginManifestService) UnloadPluginUI

func (s *PluginManifestService) UnloadPluginUI(pluginID uint) error

UnloadPluginUI marks a plugin's UI as unloaded

func (*PluginManifestService) ValidatePluginPermissions

func (s *PluginManifestService) ValidatePluginPermissions(pluginID uint, requiredPermissions map[string][]string) error

ValidatePluginPermissions checks if a plugin has the required permissions

type PluginMetadata

type PluginMetadata struct {
	ConfigSchema string                 `json:"config_schema"` // JSON schema as string
	Manifest     *models.PluginManifest `json:"manifest"`      // Parsed manifest
	Command      string                 `json:"command"`       // Plugin command used for loading
	LoadTime     time.Time              `json:"load_time"`     // When this metadata was loaded
}

PluginMetadata represents combined plugin metadata from a single load operation

type PluginMetadataLoader

type PluginMetadataLoader struct {
	// contains filtered or unexported fields
}

PluginMetadataLoader provides unified loading of plugin configuration schema and manifest

func NewPluginMetadataLoader

func NewPluginMetadataLoader(db *gorm.DB, pluginManager *AIStudioPluginManager) *PluginMetadataLoader

NewPluginMetadataLoader creates a new plugin metadata loader

func (*PluginMetadataLoader) ExtractScopesFromMetadata

func (l *PluginMetadataLoader) ExtractScopesFromMetadata(metadata *PluginMetadata) []string

ExtractScopesFromMetadata extracts all permission scopes from metadata (if manifest is available) This includes both service scopes (AI Studio services) and object_hooks permissions

func (*PluginMetadataLoader) LoadPluginMetadata

func (l *PluginMetadataLoader) LoadPluginMetadata(ctx context.Context, command string) (*PluginMetadata, error)

LoadPluginMetadata loads both config schema and manifest using enhanced ConfigProviderService

func (*PluginMetadataLoader) LoadPluginMetadataByID

func (l *PluginMetadataLoader) LoadPluginMetadataByID(ctx context.Context, pluginID uint) (*PluginMetadata, error)

LoadPluginMetadataByID loads metadata for a plugin by its database ID

type PluginPermissionInfo

type PluginPermissionInfo struct {
	Key        string            // "plugin:<manifest id>"
	RPCMethods map[string]string // manifest rbac.rpc_methods (plugin-relative)
	Plugin     *models.Plugin    // snapshot used to resolve plugin-relative permissions
}

PluginPermissionInfo is the cached authorisation view of one plugin.

func LookupPluginPermissionInfo

func LookupPluginPermissionInfo(pluginID uint) (PluginPermissionInfo, bool)

LookupPluginPermissionInfo returns the cached view for a plugin ID.

type PluginResourceSelection

type PluginResourceSelection struct {
	PluginID         uint     `json:"plugin_id"`
	ResourceTypeSlug string   `json:"resource_type_slug"`
	InstanceIDs      []string `json:"instance_ids"`
}

PluginResourceSelection represents plugin resources to associate with an app.

type PluginResourceTypeKey

type PluginResourceTypeKey struct {
	PluginID uint
	Slug     string
}

PluginResourceTypeKey identifies a resource type by plugin ID and slug.

type PluginService

type PluginService struct {
	// contains filtered or unexported fields
}

PluginService implements plugin management for AI Studio

func NewPluginService

func NewPluginService(db *gorm.DB) *PluginService

NewPluginService creates a new plugin service

func NewPluginServiceWithOCI

func NewPluginServiceWithOCI(db *gorm.DB, ociConfig *ociplugins.OCIConfig) (*PluginService, error)

NewPluginServiceWithOCI creates a new plugin service with OCI support

func (*PluginService) AuthorizePluginServiceAccess

func (s *PluginService) AuthorizePluginServiceAccess(pluginID uint, adminApproval bool) error

AuthorizePluginServiceAccess authorizes service access for a plugin (admin operation)

func (*PluginService) CleanupOrphanedUIRegistryEntries

func (s *PluginService) CleanupOrphanedUIRegistryEntries() error

CleanupOrphanedUIRegistryEntries removes UI registry entries for plugins that no longer exist

func (*PluginService) CreateOCIPluginFromReference

func (s *PluginService) CreateOCIPluginFromReference(req *CreateOCIPluginRequest) (*models.Plugin, error)

CreateOCIPluginFromReference creates a plugin from an OCI reference

func (*PluginService) CreatePlugin

func (s *PluginService) CreatePlugin(req *CreatePluginRequest) (*models.Plugin, error)

CreatePlugin creates a new plugin (adapted from microgateway)

func (*PluginService) DeletePlugin

func (s *PluginService) DeletePlugin(id uint) error

DeletePlugin soft deletes a plugin (adapted from microgateway)

func (*PluginService) ExtractAndStoreServiceScopes

func (s *PluginService) ExtractAndStoreServiceScopes(pluginID uint) error

ExtractAndStoreServiceScopes extracts service scopes from manifest and stores them in the database

func (*PluginService) GetAIStudioPluginsWithManifests

func (s *PluginService) GetAIStudioPluginsWithManifests() ([]models.Plugin, error)

GetAIStudioPluginsWithManifests returns AI Studio plugins that have UI manifests

func (*PluginService) GetActivePluginsInNamespace

func (s *PluginService) GetActivePluginsInNamespace(namespace string) ([]models.Plugin, error)

GetActivePluginsInNamespace returns active plugins in a specific namespace (AI Studio specific)

func (*PluginService) GetEndpointAuthPlugins

func (s *PluginService) GetEndpointAuthPlugins(objectType string, objectID uint) ([]models.Plugin, error)

GetEndpointAuthPlugins returns the auth plugins attached to an endpoint, in execution order.

func (*PluginService) GetLLMPluginConfig

func (s *PluginService) GetLLMPluginConfig(llmID, pluginID uint) (map[string]interface{}, error)

GetLLMPluginConfig returns the configuration for a specific plugin-LLM association (adapted from microgateway)

func (*PluginService) GetPlugin

func (s *PluginService) GetPlugin(id uint) (*models.Plugin, error)

GetPlugin retrieves a plugin by ID (adapted from microgateway)

func (*PluginService) GetPluginConfigSchema

func (s *PluginService) GetPluginConfigSchema(ctx context.Context, pluginID uint) (string, error)

GetPluginConfigSchema retrieves the configuration schema for a plugin, using cache when possible

func (*PluginService) GetPluginConfigSchemaByCommand

func (s *PluginService) GetPluginConfigSchemaByCommand(ctx context.Context, command string) (string, error)

GetPluginConfigSchemaByCommand retrieves schema by command, using cache when possible

func (*PluginService) GetPluginsByType

func (s *PluginService) GetPluginsByType(pluginType string) ([]models.Plugin, error)

GetPluginsByType returns plugins filtered by type

func (*PluginService) GetPluginsForLLM

func (s *PluginService) GetPluginsForLLM(llmID uint) ([]models.Plugin, error)

GetPluginsForLLM returns plugins associated with an LLM, ordered by execution order (adapted from microgateway)

func (*PluginService) GetPluginsInNamespace

func (s *PluginService) GetPluginsInNamespace(namespace string) ([]models.Plugin, error)

GetPluginsInNamespace returns plugins in a specific namespace (AI Studio specific)

func (*PluginService) InvalidateSchemaCache

func (s *PluginService) InvalidateSchemaCache(command string) error

InvalidateSchemaCache removes a schema from the cache

func (*PluginService) ListAllPlugins

func (s *PluginService) ListAllPlugins(page, limit int, hookType string, namespace string) ([]models.Plugin, int64, error)

ListAllPlugins lists all plugins (both active and inactive) with pagination and filtering

func (*PluginService) ListCachedOCIPlugins

func (s *PluginService) ListCachedOCIPlugins() ([]*ociplugins.LocalPlugin, error)

ListCachedOCIPlugins returns all cached OCI plugins

func (*PluginService) ListPlugins

func (s *PluginService) ListPlugins(page, limit int, hookType string, isActive bool, namespace string) ([]models.Plugin, int64, error)

ListPlugins lists plugins with pagination and filtering (adapted from microgateway)

func (*PluginService) LoadPluginManifestViaGRPC

func (s *PluginService) LoadPluginManifestViaGRPC(pluginID uint) (*models.PluginManifest, error)

LoadPluginManifestViaGRPC loads manifest from any plugin type using the GetManifest gRPC method

func (*PluginService) RefreshOCIPlugin

func (s *PluginService) RefreshOCIPlugin(pluginID uint) (*models.Plugin, error)

RefreshOCIPlugin refreshes an OCI plugin from the registry

func (*PluginService) RefreshPluginConfigSchema

func (s *PluginService) RefreshPluginConfigSchema(ctx context.Context, pluginID uint) (string, error)

RefreshPluginConfigSchema forces a refresh of the schema from the plugin

func (*PluginService) SetEndpointAuthPlugins

func (s *PluginService) SetEndpointAuthPlugins(objectType string, objectID uint, pluginIDs []uint) error

SetEndpointAuthPlugins replaces an endpoint's auth plugin list; the slice order is the execution order. Each plugin must exist, support the auth hook and be global or in the endpoint's namespace (an edge only receives those). An inactive plugin may be attached: an edge does not load it, so requests to the endpoint are refused until it is activated, which is the safe direction.

func (*PluginService) SetPermissionSync

func (s *PluginService) SetPermissionSync(fn pluginPermissionSyncer)

SetPermissionSync installs the callback that registers or removes a plugin's permission resource after create, update and delete.

func (*PluginService) SetPluginManager

func (s *PluginService) SetPluginManager(pluginManager *AIStudioPluginManager)

SetPluginManager sets the AI Studio plugin manager (to avoid circular dependency)

func (*PluginService) SetSecurityService

func (s *PluginService) SetSecurityService(service ociplugins.SecurityService)

SetSecurityService sets the enterprise security service for OCI signature verification

func (*PluginService) TestPlugin

func (s *PluginService) TestPlugin(pluginID uint, testData interface{}) (interface{}, error)

TestPlugin tests a plugin with provided test data (simplified from microgateway)

func (*PluginService) UpdateLLMPluginConfig

func (s *PluginService) UpdateLLMPluginConfig(llmID, pluginID uint, configOverride map[string]interface{}) error

UpdateLLMPluginConfig updates the configuration override for a specific plugin-LLM association

func (*PluginService) UpdateLLMPlugins

func (s *PluginService) UpdateLLMPlugins(llmID uint, pluginIDs []uint) error

UpdateLLMPlugins updates plugin associations for an LLM (adapted from microgateway)

func (*PluginService) UpdatePlugin

func (s *PluginService) UpdatePlugin(id uint, req *UpdatePluginRequest) (*models.Plugin, error)

UpdatePlugin updates an existing plugin (adapted from microgateway)

type PluginServiceInterface

type PluginServiceInterface interface {
	// CRUD operations
	CreatePlugin(req *CreatePluginRequest) (*models.Plugin, error)
	GetPlugin(id uint) (*models.Plugin, error)
	ListPlugins(page, limit int, hookType string, isActive bool) ([]models.Plugin, int64, error)
	ListAllPlugins(page, limit int, hookType string) ([]models.Plugin, int64, error)
	UpdatePlugin(id uint, req *UpdatePluginRequest) (*models.Plugin, error)
	DeletePlugin(id uint) error

	// LLM associations
	GetPluginsForLLM(llmID uint) ([]models.Plugin, error)
	UpdateLLMPlugins(llmID uint, pluginIDs []uint) error
	GetLLMPluginConfig(llmID, pluginID uint) (map[string]interface{}, error)

	// Validation and utilities
	TestPlugin(pluginID uint, testData interface{}) (interface{}, error)
}

PluginServiceInterface defines the interface for plugin operations (adapted from microgateway)

type PluginUpgradePreview

type PluginUpgradePreview struct {
	PluginID          uint                   `json:"plugin_id"`
	PluginName        string                 `json:"plugin_name"`
	MarketplaceID     string                 `json:"marketplace_id"`
	InstalledVersion  string                 `json:"installed_version"`
	TargetVersion     string                 `json:"target_version"`
	LatestVersion     string                 `json:"latest_version"`
	IsDowngrade       bool                   `json:"is_downgrade"`
	SameVersion       bool                   `json:"same_version"` // already on the target; nothing to apply
	TargetCommand     string                 `json:"target_command"`
	Scopes            UpgradeDiff            `json:"scopes"`
	Hooks             UpgradeDiff            `json:"hooks"`
	ConfigSchema      map[string]interface{} `json:"config_schema,omitempty"`
	ConfigIssues      []string               `json:"config_issues"`
	Warnings          []string               `json:"warnings"`
	Deprecated        bool                   `json:"deprecated"`
	DeprecatedMessage string                 `json:"deprecated_message,omitempty"`
	MinStudioVersion  string                 `json:"min_studio_version,omitempty"`
	AffectsEdges      bool                   `json:"affects_edges"`
	Changelog         string                 `json:"changelog"`
	Versions          []UpgradeVersionOption `json:"versions"`
}

PluginUpgradePreview is what an admin reviews before confirming an upgrade.

type PluginUpgradeRequest

type PluginUpgradeRequest struct {
	Version        string   `json:"version"`         // empty = latest upgrade candidate
	ApprovedScopes []string `json:"approved_scopes"` // must cover every scope the target adds
	AllowDowngrade bool     `json:"allow_downgrade"` // required to move to an older version
}

PluginUpgradeRequest selects the version to move to.

type PluginUpgradeResult

type PluginUpgradeResult struct {
	Plugin       *models.Plugin `json:"-"`
	FromVersion  string         `json:"from_version"`
	ToVersion    string         `json:"to_version"`
	Reloaded     bool           `json:"reloaded"`
	AffectsEdges bool           `json:"affects_edges"`
	Warnings     []string       `json:"warnings"`
}

PluginUpgradeResult reports a completed upgrade.

type PluginUpgradeService

type PluginUpgradeService struct {
	// contains filtered or unexported fields
}

PluginUpgradeService moves an installed marketplace plugin to another published version in place. The plugin row - and with it the configuration and everything keyed on the plugin ID (KV data, agent configs, app and group resource bindings, LLM associations, schedules, RBAC grants) - is kept; only the artifact and what the artifact declares about itself change.

func NewPluginUpgradeService

func NewPluginUpgradeService(db *gorm.DB, plugins *PluginService, marketplaceService *MarketplaceService, manager *AIStudioPluginManager, manifests *PluginManifestService) *PluginUpgradeService

NewPluginUpgradeService wires the upgrade service to the running Studio services.

func (*PluginUpgradeService) Preview

func (s *PluginUpgradeService) Preview(ctx context.Context, pluginID uint, version string) (*PluginUpgradePreview, error)

Preview resolves and probes the target version and reports what would change. It writes nothing, but it does pull and start the new artifact.

func (*PluginUpgradeService) Upgrade

Upgrade moves the plugin to the requested version. The new artifact has to start with the existing configuration; if it does not, the previous version is restored and an *UpgradeRolledBackError is returned.

type PrivacyScoreMismatch

type PrivacyScoreMismatch struct {
	ResourceKind  string // "Data source", "Tool", "Plugin resource"
	ResourceName  string
	ResourceScore int
	LLMName       string
	MaxLLMScore   int // -1 when the app carries no providers at all
}

PrivacyScoreMismatch describes exactly which resource was refused and why.

The bare sentinel produced "Failed to create app. Please try again." at the portal, which is the least useful thing it could have said: nothing about the request has changed, so retrying can never succeed. Carry the offending pair and the two numbers so the caller can name them.

It unwraps to ERRPrivacyScoreMismatch, so existing errors.Is checks still classify it as a privacy refusal.

func (*PrivacyScoreMismatch) Error

func (e *PrivacyScoreMismatch) Error() string

func (*PrivacyScoreMismatch) Unwrap

func (e *PrivacyScoreMismatch) Unwrap() error

type ResourceInstanceCreator

type ResourceInstanceCreator interface {
	CreateResourceInstance(pluginID uint, resourceTypeSlug string, payload []byte, reviewerID uint) (*pb.ResourceInstanceProto, error)
}

ResourceInstanceCreator is the slice of the AI Studio plugin manager used to create plugin resource instances from approved submissions. It exists so the submission service can be tested with a fake plugin.

type SSOService

type SSOService struct {
	InternalTIB *InternalTIB
	// contains filtered or unexported fields
}

func NewSSOService

func NewSSOService(config *Config, router *gin.Engine, db *gorm.DB, notificationSvc *NotificationService) *SSOService

func (*SSOService) GenerateNonce

func (s *SSOService) GenerateNonce(request NonceTokenRequest) (*string, error)

func (*SSOService) GetTapProfile

func (s *SSOService) GetTapProfile(id string) (tap.TAProvider, *tap.Profile, error)

func (*SSOService) HandleSSO

func (s *SSOService) HandleSSO(login *NonceTokenRequest) (*models.User, error)

func (*SSOService) InitInternalTIB

func (s *SSOService) InitInternalTIB()

func (*SSOService) ResolveNonce

func (s *SSOService) ResolveNonce(token string, consume bool) (*NonceTokenRequest, error)

func (*SSOService) ValidateNonceRequest

func (s *SSOService) ValidateNonceRequest(request *NonceTokenRequest) error

type SecretReference

type SecretReference struct {
	Type string `json:"type"`
	ID   uint   `json:"id"`
	Name string `json:"name"`
}

SecretReference is one object that reads a secret through a $SECRET/<name> reference. Type is "llm", "tool" or "datasource".

type Service

type Service struct {
	DB     *gorm.DB
	Budget budget.Service
	// TeamBudget is the team (Group) budget feature (Enterprise). It takes
	// part in every Budget check; see InitBudgets.
	TeamBudget          team_budget.Service
	GroupAccessService  group_access.Service
	NotificationService *NotificationService
	LogExportService    log_export.Service
	// Hub-and-Spoke Services
	EdgeService           *EdgeService
	NamespaceService      *NamespaceService
	EdgeManagementService edge_management.Service
	PluginService         *PluginService
	PluginManifestService *PluginManifestService
	AIStudioPluginManager *AIStudioPluginManager
	// PluginResourceRPC creates plugin resource instances from approved
	// submissions. Defaults to AIStudioPluginManager; tests inject a fake.
	PluginResourceRPC    ResourceInstanceCreator
	PluginMetadataLoader *PluginMetadataLoader
	MarketplaceService   *MarketplaceService
	// PluginUpgradeService is built on first use by the API; tests inject their own.
	PluginUpgradeService *PluginUpgradeService
	// Object Hooks
	HookRegistry *HookRegistry
	HookManager  *HookManager
	// System Events
	EventBus     eventbridge.Bus
	SystemEvents *SystemEventEmitter
	// Licensing (set after creation via SetLicensingService)
	LicensingService licensing.Service
	// Model Router (Enterprise)
	ModelRouterService model_router.Service
	// Semantic Router (Enterprise)
	SemanticRouterService semantic_router.Service
	// Governed Metadata (Enterprise)
	GovernedMetadataService governed_metadata.Service
	// Sync Status (Hub-and-Spoke)
	SyncStatusService *SyncStatusService
	// Role-based access control (ENT: roles and bindings, CE: admin-or-not stub)
	RBAC rbac.Service
	// Webhooks (Enterprise; set by InitWebhooks once the event bus is wired)
	Webhooks webhooks.Service
	// TykMCP is the Tyk Dashboard MCP integration (Enterprise; set by
	// InitTykMCP once the event bus is wired)
	TykMCP tykmcp.Service
	// contains filtered or unexported fields
}

func NewService

func NewService(db *gorm.DB) *Service

func NewServiceWithOCI

func NewServiceWithOCI(db *gorm.DB, ociConfig *ociplugins.OCIConfig) *Service

func (*Service) AccessiblePluginResourceInstances

func (s *Service) AccessiblePluginResourceInstances(userID uint, seeAll bool, only *PluginResourceTypeKey) ([]AccessiblePluginResourceType, error)

AccessiblePluginResourceInstances is the one visibility rule for plugin resources in the portal, shared by GET /common/accessible-plugin-resources (the AppBuilder) and the portal catalog: every active resource type with its active instances, all of them when seeAll is set (callers who manage teams), otherwise only the instances granted to the user's teams. `only` restricts the lookup to one type. Each type is one RPC to its plugin, run concurrently; a type whose plugin cannot be reached is returned with no instances. Nil is returned when nothing is registered or the plugin manager is not running.

func (*Service) AccessibleResourceInstanceIDs

func (s *Service) AccessibleResourceInstanceIDs(ctx context.Context, pluginID uint, slug string, userID uint) (seeAll bool, ids []string, err error)

AccessibleResourceInstanceIDs answers "which of this plugin's instances of a type can this user reach?" with the platform's portal rule (AccessiblePluginResourceInstances): a user who manages teams (groups:write) sees every instance (seeAll), anyone else sees the instances granted to their teams. Instance activity is the plugin's own business and is not checked here.

func (*Service) ActivateAppCredential

func (s *Service) ActivateAppCredential(appID uint) error

ActivateAppCredential activates the credential associated with an app

func (*Service) ActivateCredential

func (s *Service) ActivateCredential(id uint) error

ActivateCredential activates a credential

func (*Service) AddAllowedModel

func (s *Service) AddAllowedModel(id uint, modelPattern string) error

Add some helper functions for managing allowed models

func (*Service) AddCatalogueToGroup

func (s *Service) AddCatalogueToGroup(catalogueID, groupID uint) error

func (*Service) AddDataCatalogueToGroup

func (s *Service) AddDataCatalogueToGroup(dataCatalogueID, groupID uint) error

func (*Service) AddDatasourceToApp

func (s *Service) AddDatasourceToApp(appID, datasourceID uint) error

AddDatasourceToApp adds a datasource to an app

func (*Service) AddDatasourceToDataCatalogue

func (s *Service) AddDatasourceToDataCatalogue(dataCatalogueID, datasourceID uint) error

func (*Service) AddDependencyToTool

func (s *Service) AddDependencyToTool(toolID uint, dependencyID uint) error

AddDependencyToTool adds a dependency to a Tool

func (*Service) AddExtraContextToChat

func (s *Service) AddExtraContextToChat(toolID uint, fileStoreID uint) error

AddExtraContextToChat adds a ExtraContext to a Chat

func (*Service) AddFileStoreToTool

func (s *Service) AddFileStoreToTool(toolID uint, fileStoreID uint) error

AddFileStoreToTool adds a FileStore to a Tool

func (*Service) AddFileToDatasource

func (s *Service) AddFileToDatasource(dsID uint, fileStoreID uint) error

AddFileStoreToTool adds a FileStore to a Tool

func (*Service) AddFilterToTool

func (s *Service) AddFilterToTool(toolID uint, filterID uint) error

AddFilterToTool adds a Filter to a Tool

func (*Service) AddLLMToApp

func (s *Service) AddLLMToApp(appID, llmID uint) error

AddLLMToApp adds an LLM to an app

func (*Service) AddLLMToCatalogue

func (s *Service) AddLLMToCatalogue(llmID, catalogueID uint) error

func (*Service) AddOperationToTool

func (s *Service) AddOperationToTool(toolID uint, operation string) error

AddOperationToTool adds an operation to a tool

func (*Service) AddTagToDataCatalogue

func (s *Service) AddTagToDataCatalogue(dataCatalogueID, tagID uint) error

func (*Service) AddTagToToolCatalogue

func (s *Service) AddTagToToolCatalogue(tagID, toolCatalogueID uint) error

func (*Service) AddTagsToDatasource

func (s *Service) AddTagsToDatasource(datasourceID uint, tagNames []string) error

func (*Service) AddToolCatalogueToGroup

func (s *Service) AddToolCatalogueToGroup(toolCatalogueID, groupID uint) error

func (*Service) AddToolToApp

func (s *Service) AddToolToApp(appID, toolID uint) (*models.App, error)

AddToolToApp adds a tool to an app

func (*Service) AddToolToToolCatalogue

func (s *Service) AddToolToToolCatalogue(toolID, toolCatalogueID uint) error

func (*Service) AddUserToGroup

func (s *Service) AddUserToGroup(userID, groupID uint) error

func (*Service) ApplyPluginChangeFromReplica

func (s *Service) ApplyPluginChangeFromReplica(topic string, pluginID uint)

ApplyPluginChangeFromReplica brings this replica in line with a plugin change another replica made (a relayed system.plugin.* event). The other replica already wrote the database, refreshed the system roles and restarted its own copy; this one only updates what it holds in memory:

  • the permission catalogue entries for the plugin, re-read from the database (no writes, no role refresh);
  • the running plugin: a deleted or deactivated plugin is stopped, an updated one that was running is restarted with its new command and configuration, and one Studio loads at start (UI, agent, object hooks) is started if it is not running.

It may take seconds (a plugin process starts); callers run it off the event reader's goroutine, in event order.

func (*Service) ApproveSubmission

func (s *Service) ApproveSubmission(submissionID, reviewerID uint, finalPrivacyScore int, catalogueIDs models.JSONMap, reviewNotes string) (*models.Submission, error)

ApproveSubmission approves a submission and creates or updates the resource (admin). All operations are wrapped in a DB transaction to prevent orphaned resources.

func (*Service) ApproveSubmissionWithOptions

func (s *Service) ApproveSubmissionWithOptions(submissionID, reviewerID uint, finalPrivacyScore int, catalogueIDs models.JSONMap, reviewNotes string, opts SubmissionApproveOptions) (*models.Submission, error)

ApproveSubmissionWithOptions is ApproveSubmission with the reviewer choices that only some resource types take.

func (*Service) Audit

func (s *Service) Audit() audit.Service

Audit returns the attached audit trail, or nil before the API is built (and always nil in proxy-only mode). Callers must handle nil.

func (*Service) AuthenticateUser

func (s *Service) AuthenticateUser(email, password string) (*models.User, error)

func (*Service) Authz

func (s *Service) Authz() rbac.Service

Authz returns the RBAC service, falling back to the edition-appropriate default when the Service was constructed by hand (tests).

func (*Service) CallToolOperation

func (s *Service) CallToolOperation(toolID uint, operationID string, params map[string][]string, payload map[string]interface{}, headers map[string][]string) (interface{}, error)

CallToolOperation calls an operation from the tool's OpenAPI spec

func (*Service) CheckEmbedderForNamespace

func (s *Service) CheckEmbedderForNamespace(embedderID *uint, ns string) error

CheckEmbedderForNamespace refuses an embedder (by id; nil means none) that may not serve an object in namespace ns: one linked to an LLM scoped to another namespace.

func (*Service) CheckLLMDeleteForEmbedders

func (s *Service) CheckLLMDeleteForEmbedders(llmID uint) error

CheckLLMDeleteForEmbedders refuses deleting an LLM that embedders link to.

func (*Service) CheckLLMUpdateForEmbedders

func (s *Service) CheckLLMUpdateForEmbedders(current *models.LLM, newVendor models.Vendor, newPrivacy int, newNamespace string) error

CheckLLMUpdateForEmbedders refuses an LLM change that would break the datasources embedding through it: a vendor its drivers cannot embed with or a different vendor (another vector space), or a privacy score below theirs.

Moving the LLM to a namespace is refused when datasources or routers in other namespaces embed through it.

func (*Service) Cleanup

func (s *Service) Cleanup() error

Cleanup stops the service (see Stop) and closes its database.

func (*Service) CleanupWithContext

func (s *Service) CleanupWithContext(ctx context.Context) error

CleanupWithContext performs graceful cleanup with a timeout context

func (*Service) ClearAllowedModels

func (s *Service) ClearAllowedModels(id uint) error

func (*Service) ClearAppMCPServers

func (s *Service) ClearAppMCPServers(appID uint) error

ClearAppMCPServers removes every MCP binding (App deletion).

func (*Service) ClearAppModelRouters

func (s *Service) ClearAppModelRouters(appID uint) error

ClearAppModelRouters removes every router grant (App deletion).

func (*Service) ClearAppPluginResources

func (s *Service) ClearAppPluginResources(appID uint) error

ClearAppPluginResources removes all plugin resource associations for an app.

func (*Service) ClearAppSemanticRouters

func (s *Service) ClearAppSemanticRouters(appID uint) error

ClearAppSemanticRouters removes every Semantic Router grant (App deletion).

func (*Service) ClearToolDependencies

func (s *Service) ClearToolDependencies(toolID uint) error

ClearToolDependencies removes all dependencies from a Tool

func (*Service) CloneDatasource

func (s *Service) CloneDatasource(sourceDatasourceID uint) (*models.Datasource, error)

CloneDatasource creates a copy of an existing datasource with all configuration including API keys

func (*Service) CountApps

func (s *Service) CountApps() (int64, error)

CountApps returns the total number of apps

func (*Service) CountAppsByUserID

func (s *Service) CountAppsByUserID(userID uint) (int64, error)

CountAppsByUserID returns the total number of apps for a specific user

func (*Service) CreateApp

func (s *Service) CreateApp(name, description string, userID uint, datasourceIDs []uint, llmIDs []uint, toolIDs []uint, monthlyBudget *float64, budgetStartDate *time.Time, metadata map[string]interface{}, opts ...AppOption) (*models.App, error)

CreateApp creates a new app with validity checks

func (*Service) CreateAppWithNamespace

func (s *Service) CreateAppWithNamespace(name, description string, userID uint, datasourceIDs []uint, llmIDs []uint, toolIDs []uint, monthlyBudget *float64, budgetStartDate *time.Time, namespace string, metadata map[string]interface{}, opts ...AppOption) (*models.App, error)

CreateAppWithNamespace creates a new app with namespace support

func (*Service) CreateAppWithResources

func (s *Service) CreateAppWithResources(
	name, description string,
	userID uint,
	datasourceIDs []uint,
	llmIDs []uint,
	toolIDs []uint,
	monthlyBudget *float64,
	budgetStartDate *time.Time,
	metadata map[string]interface{},
	pluginResources []PluginResourceSelection,
	opts ...AppOption,
) (*models.App, error)

CreateAppWithResources creates an app with both built-in and plugin resource associations. It extends CreateApp with plugin resource binding and generalized privacy validation.

func (*Service) CreateAttestationTemplate

func (s *Service) CreateAttestationTemplate(name, text, appliesToType string, required, active bool, sortOrder int) (*models.AttestationTemplate, error)

CreateAttestationTemplate creates a new attestation template (admin)

func (*Service) CreateCatalogue

func (s *Service) CreateCatalogue(name string) (*models.Catalogue, error)

func (*Service) CreateChat

func (s *Service) CreateChat(name string, description string, llmSettingsID, llmID uint, groupIDs []uint,
	filterIDs []uint, ragN int, toolSupport bool, systemPrompt string, defaultDSID uint, defaultTools []uint) (*models.Chat, error)

CreateChat creates a new chat

func (*Service) CreateChatHistoryRecord

func (s *Service) CreateChatHistoryRecord(sessionID string, chatID, userID uint, name string) (*models.ChatHistoryRecord, error)

CreateChatHistoryRecord creates a new ChatHistoryRecord

func (*Service) CreateCredential

func (s *Service) CreateCredential() (*models.Credential, error)

CreateCredential creates a new credential

func (*Service) CreateDataCatalogue

func (s *Service) CreateDataCatalogue(name, shortDesc, longDesc, icon string) (*models.DataCatalogue, error)

func (*Service) CreateDatasource

func (s *Service) CreateDatasource(name, shortDesc, longDesc, icon, url string, privacyScore int, userID uint, tagNames []string, dbConnString, dbSourceType, dbConnAPIKey, dbName string, embed EmbedderInput, active bool, namespace ...string) (*models.Datasource, error)

CreateDatasource creates a new datasource using the default DB connection.

func (*Service) CreateDatasourceWithDB

func (s *Service) CreateDatasourceWithDB(db *gorm.DB, name, shortDesc, longDesc, icon, url string, privacyScore int, userID uint, tagNames []string, dbConnString, dbSourceType, dbConnAPIKey, dbName string, embed EmbedderInput, active bool, namespace ...string) (*models.Datasource, error)

CreateDatasourceWithDB creates a new datasource using the provided DB connection (supports transactions).

func (*Service) CreateEmbedder

func (s *Service) CreateEmbedder(e *models.Embedder, userID uint) (*models.Embedder, error)

CreateEmbedder validates and stores a new embedder.

func (*Service) CreateFileStore

func (s *Service) CreateFileStore(fileName, description, content string, length int) (*models.FileStore, error)

CreateFileStore creates a new filestore entry with validity checks

func (*Service) CreateFilter

func (s *Service) CreateFilter(name, description string, script []byte, responseFilter bool, namespace string) (*models.Filter, error)

CreateFilter creates a script filter. Kept for the plugin management API; the admin API uses CreateFilterFromSpec.

func (*Service) CreateFilterFromSpec

func (s *Service) CreateFilterFromSpec(spec FilterSpec) (*models.Filter, error)

CreateFilterFromSpec creates a filter of either kind.

func (*Service) CreateGroup

func (s *Service) CreateGroup(name string, userIDs, catalogueIDs, dataCatalogueIDs, toolCatalogueIDs []uint) (*models.Group, error)

func (*Service) CreateLLM

func (s *Service) CreateLLM(name, apiKey, apiEndpoint string, privacyScore int,
	shortDescription, longDescription, logoURL string,
	vendor models.Vendor, active bool, filters []*models.Filter,
	defaultModel string, allowedModels []string, monthlyBudget *float64,
	budgetStartDate *time.Time, dontLogBodies bool, metadata models.JSONMap,
	failover *models.LLMFailover) (*models.LLM, error)

func (*Service) CreateLLMSettings

func (s *Service) CreateLLMSettings(settings *models.LLMSettings) (*models.LLMSettings, error)

CreateLLMSettings creates a new LLMSettings

func (*Service) CreateLLMWithNamespace

func (s *Service) CreateLLMWithNamespace(name, apiKey, apiEndpoint string, privacyScore int,
	shortDescription, longDescription, logoURL string,
	vendor models.Vendor, active bool, filters []*models.Filter,
	defaultModel string, allowedModels []string, monthlyBudget *float64,
	budgetStartDate *time.Time, namespace string, dontLogBodies bool, metadata models.JSONMap,
	failover *models.LLMFailover) (*models.LLM, error)

CreateLLMWithNamespace creates a new LLM with namespace support

func (*Service) CreateModelPrice

func (s *Service) CreateModelPrice(modelName, vendor string, cpt, cpit, cacheWritePT, cacheReadPT float64, currency string) (*models.ModelPrice, error)

CreateModelPrice creates a new model price

func (*Service) CreateMultipleModelPrices

func (s *Service) CreateMultipleModelPrices(modelPrices models.ModelPrices) error

CreateMultipleModelPrices creates multiple model prices at once

func (*Service) CreatePluginSubmission

func (s *Service) CreatePluginSubmission(submitterID uint, pluginResourceTypeID uint, status string, payload models.JSONMap,
	attestations models.JSONMap, suggestedPrivacy int, privacyJustification string,
	primaryContact, secondaryContact, slaExpectation string, dataCutoffDate *time.Time,
	documentationURL, notes string) (*models.Submission, error)

CreatePluginSubmission creates a submission for a plugin-provided resource type (ResourceProvider plugins with SupportsSubmissions). The payload is validated against the type's submission schema when one is declared.

func (*Service) CreateProfile

func (s *Service) CreateProfile(profile *models.Profile, userID uint) error

func (*Service) CreateSchedule

func (s *Service) CreateSchedule(pluginID uint, scheduleID, name, cronExpr, timezone string, timeoutSeconds int, config map[string]interface{}, enabled bool) (*models.PluginSchedule, error)

CreateSchedule creates a new schedule for a plugin

func (*Service) CreateSubmission

func (s *Service) CreateSubmission(submitterID uint, resourceType, status string, payload models.JSONMap,
	attestations models.JSONMap, suggestedPrivacy int, privacyJustification string,
	primaryContact, secondaryContact, slaExpectation string, dataCutoffDate *time.Time,
	documentationURL, notes string) (*models.Submission, error)

CreateSubmission creates a new datasource or tool submission (draft or submitted). Plugin resource submissions go through CreatePluginSubmission.

func (*Service) CreateTag

func (s *Service) CreateTag(name string) (*models.Tag, error)

func (*Service) CreateTool

func (s *Service) CreateTool(name, description, toolType string, oasSpec string, privacyScore int, schemaName, APIKey string) (*models.Tool, error)

CreateTool creates a new tool with validity checks CreateTool creates a new tool using the default DB connection.

func (*Service) CreateToolCatalogue

func (s *Service) CreateToolCatalogue(name, shortDescription, longDescription, icon string) (*models.ToolCatalogue, error)

func (*Service) CreateToolWithDB

func (s *Service) CreateToolWithDB(db *gorm.DB, name, description, toolType string, oasSpec string, privacyScore int, schemaName, APIKey string) (*models.Tool, error)

CreateToolWithDB creates a new tool using the provided DB connection (supports transactions).

func (*Service) CreateToolWithOptions

func (s *Service) CreateToolWithOptions(db *gorm.DB, name, description, toolType string, oasSpec string, privacyScore int, schemaName, APIKey string, opts ToolCreateOptions) (*models.Tool, error)

CreateToolWithOptions creates a tool fully configured in one step, so the before/after-create hooks and the created event all see the tool as it will be served. Creating it bare and saving the rest afterwards announced a tool with no operations first, and needed a second event to correct it.

Every creator of a tool comes through here (admin API, submission approval, plugin gRPC), so this is the one place the access-method default for new tools is applied.

func (*Service) CreateUpdateSubmission

func (s *Service) CreateUpdateSubmission(submitterID uint, resourceType string, targetResourceID uint,
	payload models.JSONMap, attestations models.JSONMap, suggestedPrivacy int, privacyJustification string,
	primaryContact, secondaryContact, slaExpectation string, dataCutoffDate *time.Time,
	documentationURL, notes string, status string) (*models.Submission, error)

CreateUpdateSubmission creates a submission that proposes changes to an existing published resource

func (*Service) CreateUser

func (s *Service) CreateUser(dto UserDTO) (*models.User, error)

func (*Service) DeactivateAppCredential

func (s *Service) DeactivateAppCredential(appID uint) error

DeactivateAppCredential deactivates the credential associated with an app

func (*Service) DeactivateCredential

func (s *Service) DeactivateCredential(id uint) error

DeactivateCredential deactivates a credential

func (*Service) DeactivatePluginResourceTypes

func (s *Service) DeactivatePluginResourceTypes(pluginID uint) error

DeactivatePluginResourceTypes marks all resource types for a plugin as inactive. Called when a plugin is unloaded.

func (*Service) DeactivatePluginResourceTypesExcept

func (s *Service) DeactivatePluginResourceTypesExcept(pluginID uint, keepSlugs []string) (int64, error)

DeactivatePluginResourceTypesExcept marks every active resource type of a plugin as inactive except those whose slug is in keepSlugs. Used when a plugin re-registers its types at runtime and some were removed. Returns the number of types deactivated.

func (*Service) DeleteApp

func (s *Service) DeleteApp(id uint) error

DeleteApp deletes an app

func (*Service) DeleteAttestationTemplate

func (s *Service) DeleteAttestationTemplate(id uint) error

DeleteAttestationTemplate deletes an attestation template (admin)

func (*Service) DeleteCatalogue

func (s *Service) DeleteCatalogue(id uint) error

func (*Service) DeleteChat

func (s *Service) DeleteChat(id uint) error

DeleteChat deletes a chat by its ID

func (*Service) DeleteChatHistoryRecord

func (s *Service) DeleteChatHistoryRecord(id uint) error

DeleteChatHistoryRecord deletes a ChatHistoryRecord by its ID

func (*Service) DeleteCredential

func (s *Service) DeleteCredential(id uint) error

DeleteCredential deletes a credential

func (*Service) DeleteDataCatalogue

func (s *Service) DeleteDataCatalogue(id uint) error

func (*Service) DeleteDatasource

func (s *Service) DeleteDatasource(id uint) error

func (*Service) DeleteEmbedder

func (s *Service) DeleteEmbedder(id uint, userID uint) error

DeleteEmbedder removes an embedder nothing uses.

func (*Service) DeleteFileStore

func (s *Service) DeleteFileStore(id uint) error

DeleteFileStore deletes a filestore entry

func (*Service) DeleteFilter

func (s *Service) DeleteFilter(id uint) error

func (*Service) DeleteGroup

func (s *Service) DeleteGroup(id uint) error

func (*Service) DeleteLLM

func (s *Service) DeleteLLM(id uint) error

The following functions remain unchanged

func (*Service) DeleteLLMSettings

func (s *Service) DeleteLLMSettings(id uint) error

DeleteLLMSettings deletes an LLMSettings by its ID

func (*Service) DeleteModelPrice

func (s *Service) DeleteModelPrice(id uint) error

DeleteModelPrice deletes a model price

func (*Service) DeleteMultipleModelPrices

func (s *Service) DeleteMultipleModelPrices(modelPrices models.ModelPrices) error

DeleteMultipleModelPrices deletes multiple model prices at once

func (*Service) DeleteProfile

func (s *Service) DeleteProfile(profileID string) error

func (*Service) DeleteSchedule

func (s *Service) DeleteSchedule(pluginID uint, scheduleID uint) error

DeleteSchedule deletes a schedule

func (*Service) DeleteSubmission

func (s *Service) DeleteSubmission(id, submitterID uint) error

DeleteSubmission deletes a draft submission

func (*Service) DeleteTag

func (s *Service) DeleteTag(id uint) error

func (*Service) DeleteTool

func (s *Service) DeleteTool(id uint) error

DeleteTool deletes a tool

func (*Service) DeleteToolCatalogue

func (s *Service) DeleteToolCatalogue(id uint) error

func (*Service) DeleteUser

func (s *Service) DeleteUser(user *models.User) error

func (*Service) EditUserMessage

func (s *Service) EditUserMessage(sessionID string, messageID uint, newContent string) error

EditUserMessage removes the edited message and all subsequent messages

func (*Service) EditUserMessageByIndex

func (s *Service) EditUserMessageByIndex(sessionID string, messageIndex int) error

EditUserMessageByIndex removes messages from the specified index onwards

func (*Service) EmbeddingVendors

func (s *Service) EmbeddingVendors() []models.Vendor

EmbeddingVendors lists the vendors whose drivers can embed.

func (*Service) EnsureDefaultGroupAccess

func (s *Service) EnsureDefaultGroupAccess(resourceTypeID uint, instanceIDs []string) error

EnsureDefaultGroupAccess checks all instances reported by the plugin and ensures any new instances are automatically assigned to the default group. This mirrors the built-in resource pattern where new LLMs/Datasources/Tools are added to the default catalogue so they're immediately visible to all users.

Called at registration and when a plugin reports an instance changed, for types that grant the Default group automatically (autoGrantsDefaultGroup), so plugins need not manage group assignments themselves.

func (*Service) FindOrCreateLinkedEmbedder

func (s *Service) FindOrCreateLinkedEmbedder(llmID uint, model string, userID uint) (*models.Embedder, error)

FindOrCreateLinkedEmbedder returns the embedder linked to the LLM with this model, creating one when there is none.

func (*Service) GenerateAPIKeyForUser

func (a *Service) GenerateAPIKeyForUser(id uint) (string, error)

GenerateAPIKeyForUser issues a new key for the user and returns it, so callers need not read the row back.

func (*Service) GetAccessiblePluginResourceInstances

func (s *Service) GetAccessiblePluginResourceInstances(userID, resourceTypeID uint) ([]string, error)

GetAccessiblePluginResourceInstances returns instance IDs accessible to a user for a given resource type, by joining through their group memberships.

func (*Service) GetAccessibleToolsForUser

func (s *Service) GetAccessibleToolsForUser(userID uint) ([]models.Tool, error)

func (*Service) GetActiveAppsInNamespace

func (s *Service) GetActiveAppsInNamespace(namespace string) ([]models.App, error)

GetActiveAppsInNamespace returns active apps in a specific namespace (including global)

func (*Service) GetActiveCredentials

func (s *Service) GetActiveCredentials() (models.Credentials, error)

GetActiveCredentials retrieves all active credentials

func (*Service) GetActiveDatasources

func (s *Service) GetActiveDatasources() ([]models.Datasource, error)

func (*Service) GetActiveLLMs

func (s *Service) GetActiveLLMs() ([]models.LLM, error)

func (*Service) GetActiveLLMsInNamespace

func (s *Service) GetActiveLLMsInNamespace(namespace string) ([]models.LLM, error)

GetActiveLLMsInNamespace returns active LLMs in a specific namespace (including global)

func (*Service) GetAllAccessiblePluginResources

func (s *Service) GetAllAccessiblePluginResources(userID uint) ([]models.GroupPluginResource, error)

GetAllAccessiblePluginResources returns all plugin resource access entries for a user.

func (*Service) GetAllAttestationTemplates

func (s *Service) GetAllAttestationTemplates(activeOnly bool) (models.AttestationTemplates, error)

GetAllAttestationTemplates retrieves all attestation templates

func (*Service) GetAllCatalogues

func (s *Service) GetAllCatalogues(pageSize int, pageNumber int, all bool, opts ...ListOptions) (models.Catalogues, int64, int, error)

func (*Service) GetAllCredentials

func (s *Service) GetAllCredentials(pageSize int, pageNumber int, all bool) (models.Credentials, int64, int, error)

GetAllCredentials retrieves all credentials

func (*Service) GetAllDataCatalogues

func (s *Service) GetAllDataCatalogues(pageSize int, pageNumber int, all bool, opts ...ListOptions) (models.DataCatalogues, int64, int, error)

func (*Service) GetAllDatasources

func (s *Service) GetAllDatasources(pageSize int, pageNumber int, all bool, opts ...ListOptions) (models.Datasources, int64, int, error)

func (*Service) GetAllDatasourcesWithFilters

func (s *Service) GetAllDatasourcesWithFilters(pageSize int, pageNumber int, all bool, isActive *bool, userID *uint) (models.Datasources, int64, int, error)

GetAllDatasourcesWithFilters returns all datasources with filtering by active status and user ID

func (*Service) GetAllFileStores

func (s *Service) GetAllFileStores(pageSize int, pageNumber int, all bool) ([]models.FileStore, int64, int, error)

GetAllFileStores retrieves all filestore entries with pagination

func (*Service) GetAllFilters

func (s *Service) GetAllFilters(pageSize int, pageNumber int, all bool) ([]models.Filter, int64, int, error)

func (*Service) GetAllFiltersWithFilters

func (s *Service) GetAllFiltersWithFilters(pageSize int, pageNumber int, all bool, namespace string) ([]models.Filter, int64, int, error)

GetAllFiltersWithFilters returns all filters with namespace filtering Note: is_active filtering not supported by main Filter model (only microgateway Filter has this field)

func (*Service) GetAllGroups

func (s *Service) GetAllGroups(pageSize int, pageNumber int, all bool, sort string) (models.Groups, int64, int, error)

func (*Service) GetAllLLMSettings

func (s *Service) GetAllLLMSettings(pageSize int, pageNumber int, all bool) (*models.LLMSettingsSlice, int64, int, error)

GetAllLLMSettings retrieves all LLMSettings GetAllLLMSettings retrieves all LLMSettings with pagination

func (*Service) GetAllLLMs

func (s *Service) GetAllLLMs(pageSize int, pageNumber int, all bool, opts ...ListOptions) (models.LLMs, int64, int, error)

func (*Service) GetAllModelPrices

func (s *Service) GetAllModelPrices(pageSize int, pageNumber int, all bool, opts ...ListOptions) (models.ModelPrices, int64, int, error)

GetAllModelPrices retrieves all model prices

func (*Service) GetAllSubmissions

func (s *Service) GetAllSubmissions(status, resourceType string, pageSize, pageNumber int) (models.Submissions, int64, int, error)

GetAllSubmissions retrieves all submissions with optional filters (admin)

func (*Service) GetAllTags

func (s *Service) GetAllTags(pageSize int, pageNumber int, all bool) (models.Tags, int64, int, error)

func (*Service) GetAllToolCatalogues

func (s *Service) GetAllToolCatalogues(pageSize int, pageNumber int, all bool, opts ...ListOptions) (models.ToolCatalogues, int64, int, error)

func (*Service) GetAllTools

func (s *Service) GetAllTools(pageSize int, pageNumber int, all bool, opts ...ListOptions) ([]models.Tool, int64, int, error)

GetAllTools retrieves all tools

func (*Service) GetAllUsers

func (s *Service) GetAllUsers(pageSize int, pageNumber int, all bool, sort string) (models.Users, int64, int, error)

GetAllUsers is a wrapper for ListUsers for backward compatibility

func (*Service) GetAllowedModels

func (s *Service) GetAllowedModels(id uint) ([]string, error)

func (*Service) GetAppByCredentialID

func (s *Service) GetAppByCredentialID(credentialID uint) (*models.App, error)

GetAppByCredentialID retrieves an app by its credential ID

func (*Service) GetAppByID

func (s *Service) GetAppByID(id uint) (*models.App, error)

GetAppByID retrieves an app by its ID

func (*Service) GetAppByName

func (s *Service) GetAppByName(name string) (*models.App, error)

GetAppByName retrieves an app by its name

func (*Service) GetAppDatasources

func (s *Service) GetAppDatasources(appID uint) ([]models.Datasource, error)

GetAppDatasources retrieves all datasources associated with an app

func (*Service) GetAppDependents

func (s *Service) GetAppDependents(appID uint) (*Dependents, error)

GetAppDependents lists what references an app: the agents configured to run as it (agent_configs.app_id). Chats do not reference apps, and an app's plugin resource bindings (app_plugin_resources) are its own configuration, cleared by DeleteApp, rather than dependents.

func (*Service) GetAppGrantableToolsForUser

func (s *Service) GetAppGrantableToolsForUser(userID uint) ([]models.Tool, error)

GetAppGrantableToolsForUser is GetAccessibleToolsForUser without chat-only tools: what the portal's App builder may offer. The chat tool picker uses the unfiltered list.

func (*Service) GetAppLLMs

func (s *Service) GetAppLLMs(appID uint, pageSize int, pageNumber int, all bool) ([]models.LLM, int64, int, error)

GetAppLLMs retrieves all LLMs associated with an app

func (*Service) GetAppMCPServers

func (s *Service) GetAppMCPServers(appID uint) ([]models.MCPServer, error)

GetAppMCPServers lists the MCP servers bound to an App.

func (*Service) GetAppPluginResources

func (s *Service) GetAppPluginResources(appID uint) ([]models.AppPluginResource, error)

GetAppPluginResources returns all plugin resource associations for an app.

func (*Service) GetAppTools

func (s *Service) GetAppTools(appID uint) ([]models.Tool, error)

GetAppTools retrieves all tools associated with an app

func (*Service) GetAppsByUserID

func (s *Service) GetAppsByUserID(userID uint) ([]models.App, error)

GetAppsByUserID retrieves all apps for a specific user

func (*Service) GetAppsInNamespace

func (s *Service) GetAppsInNamespace(namespace string) ([]models.App, error)

GetAppsInNamespace returns apps in a specific namespace (including global)

func (*Service) GetAttestationTemplateByID

func (s *Service) GetAttestationTemplateByID(id uint) (*models.AttestationTemplate, error)

GetAttestationTemplateByID retrieves an attestation template by ID

func (*Service) GetAttestationTemplatesByType

func (s *Service) GetAttestationTemplatesByType(resourceType string, activeOnly bool) (models.AttestationTemplates, error)

GetAttestationTemplatesByType retrieves templates applicable to a resource type

func (*Service) GetAvailableEmbedders

func (s *Service) GetAvailableEmbedders() ([]VendorDriverInfo, error)

GetAvailableEmbedders lists the vendors whose drivers can embed (the drivers' ProvidesEmbedder is the one source).

func (*Service) GetAvailableLLMDrivers

func (s *Service) GetAvailableLLMDrivers() ([]VendorDriverInfo, error)

GetAvailableLLMDrivers returns actual available LLM drivers from switches package

func (*Service) GetAvailableVectorStores

func (s *Service) GetAvailableVectorStores() ([]VendorDriverInfo, error)

GetAvailableVectorStores returns available vector store implementations

func (*Service) GetBrandingSettings

func (s *Service) GetBrandingSettings() (*models.BrandingSettings, error)

GetBrandingSettings retrieves the current branding settings Creates default settings if none exist

func (*Service) GetCMessagesForSession

func (s *Service) GetCMessagesForSession(sessionID string) ([]models.CMessage, error)

GetCMessagesForSession returns every message of a session, oldest first.

func (*Service) GetCMessagesForSessionPage

func (s *Service) GetCMessagesForSessionPage(sessionID string, before uint, limit int) ([]models.CMessage, bool, error)

GetCMessagesForSessionPage returns up to limit messages of a session ending just before the row id `before` (0 = the newest), oldest first, and whether older rows exist. The v2 history endpoint pages backwards with it so a long conversation is never loaded whole.

func (*Service) GetCMessagesForSessionPaginated

func (s *Service) GetCMessagesForSessionPaginated(sessionID string, pageSize, pageNumber int) ([]models.CMessage, int64, int, error)

GetCMessagesForSessionPaginated retrieves CMessage records for a given session ID with pagination

func (*Service) GetCatalogueActiveLLMs

func (s *Service) GetCatalogueActiveLLMs(catalogueID uint) (models.LLMs, error)

GetCatalogueActiveLLMs returns the LLMs in a catalogue that are live.

This is the portal-facing listing. GetAccessibleLLMs already hides inactive LLMs from the portal's flat list, but the per-catalogue page went through GetCatalogueLLMs and showed drafts that were never approved. Admin listings keep using GetCatalogueLLMs so an administrator still sees everything in the catalogue.

func (*Service) GetCatalogueByID

func (s *Service) GetCatalogueByID(id uint) (*models.Catalogue, error)

func (*Service) GetCatalogueGroups

func (s *Service) GetCatalogueGroups(kind string, catalogueID uint) ([]CatalogueGroup, error)

GetCatalogueGroups lists the teams that hold a catalogue, ordered by name, with the count of their non-deleted members. kind is "catalogues", "data-catalogues" or "tool-catalogues". Never nil: an unshared catalogue yields an empty slice.

func (*Service) GetCatalogueLLMs

func (s *Service) GetCatalogueLLMs(catalogueID uint) (models.LLMs, error)

func (*Service) GetCatalogueRouters

func (s *Service) GetCatalogueRouters(catalogueID uint) (*CatalogueRouters, error)

GetCatalogueRouters lists the routers published in the catalogue.

func (*Service) GetChatByID

func (s *Service) GetChatByID(id uint) (*models.Chat, error)

GetChatByID retrieves a chat by its ID

func (*Service) GetChatExtraContexts

func (s *Service) GetChatExtraContexts(toolID uint) ([]models.FileStore, error)

GetChatExtraContexts gets all ExtraContexts associated with a Chat

func (*Service) GetChatHistoryRecordByChatID

func (s *Service) GetChatHistoryRecordByChatID(chatID uint) (*models.ChatHistoryRecord, error)

GetChatHistoryRecordByChatID retrieves a ChatHistoryRecord by its ChatID

func (*Service) GetChatHistoryRecordByID

func (s *Service) GetChatHistoryRecordByID(id uint) (*models.ChatHistoryRecord, error)

GetChatHistoryRecordByID retrieves a ChatHistoryRecord by its ID

func (*Service) GetChatHistoryRecordBySessionID

func (s *Service) GetChatHistoryRecordBySessionID(sessionID string) (*models.ChatHistoryRecord, error)

GetChatHistoryRecordBySessionID retrieves a ChatHistoryRecord by its SessionID

func (*Service) GetChatsByGroupID

func (s *Service) GetChatsByGroupID(groupID uint) (models.Chats, error)

GetChatsByGroupID retrieves all chats associated with a specific group

func (*Service) GetChatsByLLMID

func (s *Service) GetChatsByLLMID(llmID uint) (models.Chats, error)

GetChatsByLLMID retrieves all chats associated with a specific LLM

func (*Service) GetChatsByLLMSettingsID

func (s *Service) GetChatsByLLMSettingsID(llmSettingsID uint) (models.Chats, error)

GetChatsByLLMSettingsID retrieves all chats associated with specific LLM settings

func (*Service) GetCredentialByID

func (s *Service) GetCredentialByID(id uint) (*models.Credential, error)

GetCredentialByID retrieves a credential by its ID

func (*Service) GetCredentialByKeyID

func (s *Service) GetCredentialByKeyID(keyID string) (*models.Credential, error)

GetCredentialByKeyID retrieves a credential by its KeyID

func (*Service) GetCredentialBySecret

func (s *Service) GetCredentialBySecret(secret string) (*models.Credential, error)

func (*Service) GetDB

func (s *Service) GetDB() *gorm.DB

func (*Service) GetDataCatalogueByID

func (s *Service) GetDataCatalogueByID(id uint) (*models.DataCatalogue, error)

func (*Service) GetDataCataloguesByDatasource

func (s *Service) GetDataCataloguesByDatasource(datasourceID uint) (models.DataCatalogues, error)

func (*Service) GetDataCataloguesByTag

func (s *Service) GetDataCataloguesByTag(tagName string) (models.DataCatalogues, error)

func (*Service) GetDatasourceByID

func (s *Service) GetDatasourceByID(id uint) (*models.Datasource, error)

func (*Service) GetDatasourceByIDResolved

func (s *Service) GetDatasourceByIDResolved(id uint) (*models.Datasource, error)

GetDatasourceByIDResolved returns a datasource with all secret references resolved to their actual values. Use this for internal operations (embedding, vector store access) where the actual API keys are needed. The embedder's references are resolved when its spec is taken (DatasourceEmbedderSpec).

func (*Service) GetDatasourceDependents

func (s *Service) GetDatasourceDependents(datasourceID uint) (*Dependents, error)

GetDatasourceDependents lists the apps, data catalogues, agents and chats that reference a datasource.

func (*Service) GetDatasourcesByMaxPrivacyScore

func (s *Service) GetDatasourcesByMaxPrivacyScore(maxScore int) (models.Datasources, error)

func (*Service) GetDatasourcesByMinPrivacyScore

func (s *Service) GetDatasourcesByMinPrivacyScore(minScore int) (models.Datasources, error)

func (*Service) GetDatasourcesByPrivacyScoreRange

func (s *Service) GetDatasourcesByPrivacyScoreRange(minScore, maxScore int) (models.Datasources, error)

func (*Service) GetDatasourcesByTag

func (s *Service) GetDatasourcesByTag(tagName string) (models.Datasources, error)

func (*Service) GetDatasourcesByUserID

func (s *Service) GetDatasourcesByUserID(userID uint) (models.Datasources, error)

func (*Service) GetEmbedder

func (s *Service) GetEmbedder(id uint) (*models.Embedder, error)

GetEmbedder returns an embedder with its LLM loaded.

func (*Service) GetEmbedderDependents

func (s *Service) GetEmbedderDependents(embedderID uint) (*Dependents, error)

GetEmbedderDependents lists the datasources and Semantic Routers that embed with an embedder.

func (*Service) GetFaviconFilePath

func (s *Service) GetFaviconFilePath() (string, error)

GetFaviconFilePath returns the full file path to the favicon

func (*Service) GetFileStoreByFileName

func (s *Service) GetFileStoreByFileName(fileName string) (*models.FileStore, error)

GetFileStoreByFileName retrieves a filestore entry by its filename

func (*Service) GetFileStoreByID

func (s *Service) GetFileStoreByID(id uint) (*models.FileStore, error)

GetFileStoreByID retrieves a filestore entry by its ID

func (*Service) GetFilterByID

func (s *Service) GetFilterByID(id uint) (*models.Filter, error)

func (*Service) GetFilterByName

func (s *Service) GetFilterByName(name string) (*models.Filter, error)

func (*Service) GetFilterDependents

func (s *Service) GetFilterDependents(filterID uint) (*Dependents, error)

GetFilterDependents lists the LLMs, tools and chats a filter is attached to.

func (*Service) GetFiltersByChatID

func (s *Service) GetFiltersByChatID(chatID uint) ([]*models.Filter, error)

func (*Service) GetGroupByID

func (s *Service) GetGroupByID(id uint, preloads ...string) (*models.Group, error)

func (*Service) GetGroupCatalogues

func (s *Service) GetGroupCatalogues(groupID uint) (models.Catalogues, error)

func (*Service) GetGroupDataCatalogues

func (s *Service) GetGroupDataCatalogues(groupID uint) (models.DataCatalogues, error)

func (*Service) GetGroupPluginResources

func (s *Service) GetGroupPluginResources(groupID uint) ([]models.GroupPluginResource, error)

GetGroupPluginResources returns all plugin resource access entries for a group.

func (*Service) GetGroupToolCatalogues

func (s *Service) GetGroupToolCatalogues(groupID uint, pageSize int, pageNumber int, all bool) (models.ToolCatalogues, int64, int, error)

func (*Service) GetGroupUsers

func (s *Service) GetGroupUsers(groupID uint, pageSize int, pageNumber int, all bool) (models.Users, int64, int, error)

func (*Service) GetGroupsByUserID

func (s *Service) GetGroupsByUserID(userID uint) (models.Groups, error)

func (*Service) GetGroupsWithMemberCounts

func (s *Service) GetGroupsWithMemberCounts(term string, pageSize int, pageNumber int, all bool, sort string) (models.Groups, []models.GroupMemberCount, int64, int, error)

func (*Service) GetLLMByID

func (s *Service) GetLLMByID(id uint) (*models.LLM, error)

func (*Service) GetLLMByName

func (s *Service) GetLLMByName(name string) (*models.LLM, error)

func (*Service) GetLLMDependents

func (s *Service) GetLLMDependents(llmID uint) (*Dependents, error)

GetLLMDependents lists the apps, catalogues, agents, failover primaries and model routers that reference an LLM.

func (*Service) GetLLMSettingsByID

func (s *Service) GetLLMSettingsByID(id uint) (*models.LLMSettings, error)

GetLLMSettingsByID retrieves an LLMSettings by its ID

func (*Service) GetLLMSettingsByModel

func (s *Service) GetLLMSettingsByModel(model string) (*models.LLMSettings, error)

GetLLMSettingsByModel retrieves LLMSettings by model name

func (*Service) GetLLMsByMaxPrivacyScore

func (s *Service) GetLLMsByMaxPrivacyScore(score int) (models.LLMs, error)

func (*Service) GetLLMsByMinPrivacyScore

func (s *Service) GetLLMsByMinPrivacyScore(score int) (models.LLMs, error)

func (*Service) GetLLMsByNameStub

func (s *Service) GetLLMsByNameStub(name string) (models.LLMs, error)

func (*Service) GetLLMsByPrivacyScoreRange

func (s *Service) GetLLMsByPrivacyScoreRange(min, max int) (models.LLMs, error)

func (*Service) GetLLMsInNamespace

func (s *Service) GetLLMsInNamespace(namespace string) ([]models.LLM, error)

GetLLMsInNamespace returns LLMs in a specific namespace (including global)

func (*Service) GetLastCMessagesForSession

func (s *Service) GetLastCMessagesForSession(sessionID string, limit int) ([]models.CMessage, error)

GetLastCMessagesForSession retrieves the last X CMessage records for a given session ID

func (*Service) GetLatestChatHistoryRecord

func (s *Service) GetLatestChatHistoryRecord(userID uint) (*models.ChatHistoryRecord, error)

GetLatestChatHistoryRecord retrieves the most recent ChatHistoryRecord for a given UserID

func (*Service) GetLoginPageProfile

func (s *Service) GetLoginPageProfile() (*models.Profile, error)

func (*Service) GetLogoFilePath

func (s *Service) GetLogoFilePath() (string, error)

GetLogoFilePath returns the full file path to the logo

func (*Service) GetModelPriceByID

func (s *Service) GetModelPriceByID(id uint) (*models.ModelPrice, error)

GetModelPriceByID retrieves a model price by its ID

func (*Service) GetModelPriceByModelName

func (s *Service) GetModelPriceByModelName(modelName string) (*models.ModelPrice, error)

GetModelPriceByModelName retrieves a model price by its model name

func (*Service) GetModelPriceByModelNameAndVendor

func (s *Service) GetModelPriceByModelNameAndVendor(modelName, vendor string) (*models.ModelPrice, error)

GetModelPriceByModelNameAndVendor implements ServiceInterface

func (*Service) GetModelPricesByVendor

func (s *Service) GetModelPricesByVendor(vendor string) (models.ModelPrices, error)

GetModelPricesByVendor retrieves all model prices for a specific vendor

func (*Service) GetModelRouterCatalogues

func (s *Service) GetModelRouterCatalogues(routerID uint) ([]models.Catalogue, error)

GetModelRouterCatalogues lists the LLM catalogues a router is published in.

func (*Service) GetModelRouterDependents

func (s *Service) GetModelRouterDependents(routerID uint) (*Dependents, error)

GetModelRouterDependents lists what references a model router: the apps granted it and the LLM catalogues it is published in. Deleting the router withdraws both (ModelRouter.Delete).

func (*Service) GetOAuthClient

func (s *Service) GetOAuthClient(clientID string) (*models.OAuthClient, error)

GetOAuthClient returns an OAuth client by its client ID. This implements OAuth support for the ServiceInterface.

func (*Service) GetOrCreateModelPriceByName

func (s *Service) GetOrCreateModelPriceByName(modelName string) (*models.ModelPrice, error)

GetOrCreateModelPriceByName retrieves a model price by its name, creating it with default values if it doesn't exist

func (*Service) GetOrphanedCommunityResources

func (s *Service) GetOrphanedCommunityResources() ([]models.Datasource, []models.Tool, error)

GetOrphanedCommunityResources returns community resources whose owners have been deleted

func (*Service) GetPluginClient

func (s *Service) GetPluginClient(pluginID uint) (pb.PluginServiceClient, error)

GetPluginClient gets a loaded plugin client by plugin ID

func (*Service) GetPluginResourceTypeByID

func (s *Service) GetPluginResourceTypeByID(id uint) (*models.PluginResourceType, error)

GetPluginResourceTypeByID returns a resource type by its ID.

func (*Service) GetPluginResourceTypeByPluginAndSlug

func (s *Service) GetPluginResourceTypeByPluginAndSlug(pluginID uint, slug string) (*models.PluginResourceType, error)

GetPluginResourceTypeByPluginAndSlug returns a resource type by plugin ID and slug.

func (*Service) GetPluginResourceTypes

func (s *Service) GetPluginResourceTypes() ([]models.PluginResourceType, error)

GetPluginResourceTypes returns all active resource types across all plugins.

func (*Service) GetPluginResourceTypesBatch

func (s *Service) GetPluginResourceTypesBatch(keys []PluginResourceTypeKey) (map[PluginResourceTypeKey]*models.PluginResourceType, error)

GetPluginResourceTypesBatch fetches multiple resource types in a single query. Returns a map keyed by (PluginID, Slug) for O(1) lookup.

func (*Service) GetProfileByID

func (s *Service) GetProfileByID(profileID string) (*models.Profile, error)

func (*Service) GetProfileByName

func (s *Service) GetProfileByName(name string) (*models.Profile, error)

func (*Service) GetResourceVersions

func (s *Service) GetResourceVersions(resourceType string, resourceID uint) (models.SubmissionVersions, error)

GetResourceVersions returns all version snapshots for a resource

func (*Service) GetSchedule

func (s *Service) GetSchedule(pluginID uint, scheduleID uint) (*models.PluginSchedule, error)

GetSchedule retrieves a specific schedule

func (*Service) GetScheduleByManifestID

func (s *Service) GetScheduleByManifestID(pluginID uint, manifestScheduleID string) (*models.PluginSchedule, error)

GetScheduleByManifestID retrieves a schedule by its manifest schedule ID

func (*Service) GetScheduleExecutions

func (s *Service) GetScheduleExecutions(pluginID uint, scheduleID uint, limit, offset int) ([]models.PluginScheduleExecution, int64, int64, float64, error)

GetScheduleExecutions retrieves execution history for a schedule

func (*Service) GetSecretDependents

func (s *Service) GetSecretDependents(varName string) (*Dependents, error)

GetSecretDependents lists the LLMs, tools and datasources that read a secret through a $SECRET/<name> reference.

func (*Service) GetSemanticRouterCatalogues

func (s *Service) GetSemanticRouterCatalogues(routerID uint) ([]models.Catalogue, error)

GetSemanticRouterCatalogues lists the LLM catalogues a router is published in.

func (*Service) GetSemanticRouterDependents

func (s *Service) GetSemanticRouterDependents(routerID uint) (*Dependents, error)

GetSemanticRouterDependents lists what references a semantic router: the apps granted it and the LLM catalogues it is published in. Deleting the router withdraws both (SemanticRouter.Delete).

func (*Service) GetSubmissionActivities

func (s *Service) GetSubmissionActivities(submissionID uint) (models.SubmissionActivities, error)

GetSubmissionActivities retrieves the audit trail for a submission

func (*Service) GetSubmissionByID

func (s *Service) GetSubmissionByID(id uint) (*models.Submission, error)

GetSubmissionByID retrieves a submission by ID

func (*Service) GetSubmissionStatusCounts

func (s *Service) GetSubmissionStatusCounts() (map[string]int64, error)

GetSubmissionStatusCounts returns status counts for the admin dashboard

func (*Service) GetSubmissionsBySubmitter

func (s *Service) GetSubmissionsBySubmitter(submitterID uint, status string, pageSize, pageNumber int) (models.Submissions, int64, int, error)

GetSubmissionsBySubmitter retrieves submissions for a specific user

func (*Service) GetSubmittablePluginResourceTypes

func (s *Service) GetSubmittablePluginResourceTypes() ([]models.PluginResourceType, error)

GetSubmittablePluginResourceTypes returns the active resource types that accept community submissions (portal submission form).

func (*Service) GetTagByID

func (s *Service) GetTagByID(id uint) (*models.Tag, error)

func (*Service) GetTagByName

func (s *Service) GetTagByName(name string) (*models.Tag, error)

func (*Service) GetToolByID

func (s *Service) GetToolByID(id uint) (*models.Tool, error)

GetToolByID retrieves a tool by its ID

func (*Service) GetToolByName

func (s *Service) GetToolByName(name string) (*models.Tool, error)

GetToolByName retrieves a tool by its name

func (*Service) GetToolBySlug

func (s *Service) GetToolBySlug(slug string) (*models.Tool, error)

GetToolBySlug retrieves a tool by its slug (pre-computed from name using slug.Make)

This is the gateway's lookup, so it resolves active tools only. An inactive tool is never shipped to an edge gateway; the embedded gateway has to agree, or deactivating a tool only takes effect at the edge.

func (*Service) GetToolCatalogueActiveTools

func (s *Service) GetToolCatalogueActiveTools(toolCatalogueID uint) (models.Tools, error)

GetToolCatalogueActiveTools is GetToolCatalogueTools restricted to live tools, filtered in the database. The portal uses it: inactive tools stay visible to administrators only. The catalogue lookup is kept so an unknown id still reports not-found rather than an empty list.

func (*Service) GetToolCatalogueByID

func (s *Service) GetToolCatalogueByID(id uint) (*models.ToolCatalogue, error)

func (*Service) GetToolCatalogueTags

func (s *Service) GetToolCatalogueTags(toolCatalogueID uint) (models.Tags, error)

func (*Service) GetToolCatalogueTools

func (s *Service) GetToolCatalogueTools(toolCatalogueID uint) (models.Tools, error)

func (*Service) GetToolCataloguesByTag

func (s *Service) GetToolCataloguesByTag(tagName string) (models.ToolCatalogues, error)

func (*Service) GetToolDependencies

func (s *Service) GetToolDependencies(toolID uint) ([]*models.Tool, error)

GetToolDependencies gets all dependencies associated with a Tool

func (*Service) GetToolDependents

func (s *Service) GetToolDependents(toolID uint) (*Dependents, error)

GetToolDependents lists the apps, tool catalogues, dependent tools, agents and chats that reference a tool.

func (*Service) GetToolFileStores

func (s *Service) GetToolFileStores(toolID uint) ([]models.FileStore, error)

GetToolFileStores gets all FileStores associated with a Tool

func (*Service) GetToolFilters

func (s *Service) GetToolFilters(toolID uint) ([]models.Filter, error)

GetToolFilters gets all Filters associated with a Tool

func (*Service) GetToolOperationDetails

func (s *Service) GetToolOperationDetails(toolID uint) ([]ToolOperationDetail, error)

GetToolOperationDetails retrieves detailed information about tool operations from OpenAPI spec

func (*Service) GetToolOperations

func (s *Service) GetToolOperations(toolID uint) ([]string, error)

GetToolOperations retrieves all operations associated with a tool

func (*Service) GetToolsByPrivacyScoreMax

func (s *Service) GetToolsByPrivacyScoreMax(maxScore int) ([]models.Tool, error)

GetToolsByPrivacyScoreMax retrieves all tools with a privacy score less than or equal to the given maximum

func (*Service) GetToolsByPrivacyScoreMin

func (s *Service) GetToolsByPrivacyScoreMin(minScore int) ([]models.Tool, error)

GetToolsByPrivacyScoreMin retrieves all tools with a privacy score greater than or equal to the given minimum

func (*Service) GetToolsByPrivacyScoreRange

func (s *Service) GetToolsByPrivacyScoreRange(minScore, maxScore int) ([]models.Tool, error)

GetToolsByPrivacyScoreRange retrieves all tools with a privacy score within the given range

func (*Service) GetToolsByType

func (s *Service) GetToolsByType(toolType string) ([]models.Tool, error)

GetToolsByType retrieves all tools of a specific type

func (*Service) GetUserAccessibleCatalogues

func (s *Service) GetUserAccessibleCatalogues(userID uint) (models.Catalogues, error)

func (*Service) GetUserByAPIKey

func (a *Service) GetUserByAPIKey(apiKey string) (*models.User, error)

func (*Service) GetUserByEmail

func (s *Service) GetUserByEmail(email string) (*models.User, error)

func (*Service) GetUserByID

func (s *Service) GetUserByID(id uint, preload ...string) (*models.User, error)

func (*Service) GetUserEntitlements

func (s *Service) GetUserEntitlements(userID uint) (*UserEntitlements, error)

GetUserEntitlements retrieves all entitlements for a given user CE: Returns all catalogues (no filtering) ENT: Returns catalogues filtered by user's group memberships

func (*Service) GetValidAccessTokenByToken

func (s *Service) GetValidAccessTokenByToken(token string) (*models.AccessToken, error)

GetValidAccessTokenByToken returns an access token by its token string. This implements OAuth support for the ServiceInterface.

func (*Service) GovernedMetadata

func (s *Service) GovernedMetadata() governed_metadata.Service

GovernedMetadata returns the governed metadata service, falling back to the edition-appropriate default when the Service was constructed by hand (tests).

func (*Service) HandleUserDeletionForUGC

func (s *Service) HandleUserDeletionForUGC(userID uint) error

HandleUserDeletionForUGC flags community resources owned by a deleted/deactivated user. Delegates to HandleUserDeletionForUGCTx with the default DB connection.

func (*Service) HandleUserDeletionForUGCTx

func (s *Service) HandleUserDeletionForUGCTx(db *gorm.DB, userID uint) error

HandleUserDeletionForUGCTx is the transaction-aware version of HandleUserDeletionForUGC.

func (*Service) HasToolDependency

func (s *Service) HasToolDependency(toolID uint, dependencyID uint) (bool, error)

HasToolDependency checks if a specific Tool is a dependency

func (*Service) InitBudgets

func (s *Service) InitBudgets(notifier *NotificationService)

InitBudgets (re)builds the App/LLM budget service and the team budget service around the given notification service, and has the former consult the latter on every check. main calls it again once SMTP is configured, and must hand the resulting Budget to the proxy so both share one cache.

func (*Service) InitTykMCP

func (s *Service) InitTykMCP(cfg config.TykMCPConfig, version string)

InitTykMCP builds the Tyk Dashboard MCP integration service (Enterprise implementation when linked in, community stub otherwise). Call after SetEventBus; the audit trail is looked up lazily through Audit().

func (*Service) InitWebhooks

func (s *Service) InitWebhooks(cfg config.WebhooksConfig, version string)

InitWebhooks builds the webhooks service (Enterprise implementation when linked in, community stub otherwise). Call after SetEventBus so ingestion can subscribe; the audit trail is looked up lazily through Audit().

func (*Service) IsModelAllowed

func (s *Service) IsModelAllowed(id uint, modelName string) (bool, error)

Add a validation helper

func (*Service) IsUserInGroup

func (s *Service) IsUserInGroup(userID, groupID uint) (bool, error)

IsUserInGroup reports whether the user is a member of the team.

func (*Service) LLMsReferencingAsFailoverTarget

func (s *Service) LLMsReferencingAsFailoverTarget(id uint) ([]string, error)

LLMsReferencingAsFailoverTarget returns the names of LLMs whose waterfall points at the given LLM. Used to refuse a delete that would leave dangling rungs; the table is small, so this scans in Go rather than in JSON SQL that differs between SQLite and Postgres.

func (*Service) LastUserMessageID

func (s *Service) LastUserMessageID(sessionID string) (uint, error)

LastUserMessageID returns the row id of the last user turn of a session, or 0 when there is none. Human rows that carry only a [CONTEXT] block (tool documentation injected on AddTool) do not count as a turn.

func (*Service) ListApps

func (s *Service) ListApps() (models.Apps, error)

ListApps returns all apps

func (*Service) ListAppsByUserID

func (s *Service) ListAppsByUserID(userID uint, pageSize, pageNumber int, all bool, sort string) (models.Apps, int64, int, error)

ListAppsByUserID returns all apps for a specific user with pagination

func (*Service) ListAppsWithFilters

func (s *Service) ListAppsWithFilters(pageSize, pageNumber int, all bool, sort, namespace string, isActive *bool, userID ...uint) (models.Apps, int64, int, error)

ListAppsWithFilters returns a paginated list of apps with namespace and active status filtering

func (*Service) ListAppsWithPagination

func (s *Service) ListAppsWithPagination(pageSize, pageNumber int, all bool, sort string) (models.Apps, int64, int, error)

ListAppsWithPagination returns a paginated list of apps

func (*Service) ListChatHistoryRecordsByUserID

func (s *Service) ListChatHistoryRecordsByUserID(userID uint, pageSize int, pageNumber int, all bool) ([]models.ChatHistoryRecord, int64, int, error)

ListChatHistoryRecordsByUserID retrieves all ChatHistoryRecords for a given UserID

func (*Service) ListChatHistoryRecordsByUserIDPaginated

func (s *Service) ListChatHistoryRecordsByUserIDPaginated(userID uint, pageSize int, pageNumber int, all bool) ([]models.ChatHistoryRecord, int64, int, error)

ListChatHistoryRecordsByUserIDPaginated retrieves ChatHistoryRecords for a given UserID with pagination

func (*Service) ListChats

func (s *Service) ListChats(pageSize int, pageNumber int, all bool) (models.Chats, int64, int, error)

ListChats retrieves all chats

func (*Service) ListEmbedders

func (s *Service) ListEmbedders(pageSize, pageNumber int, all bool, opts ...ListOptions) (models.Embedders, int64, int, error)

ListEmbedders lists embedders with their LLMs.

func (*Service) ListFilters

func (s *Service) ListFilters(pageSize int, pageNumber int, all bool, opts ListOptions) ([]models.Filter, int64, int, error)

ListFilters is GetAllFilters with the admin list's search and sort. It is a separate method because GetAllFilters' signature is fixed by ServiceInterface, which the microgateway adapter also implements.

func (*Service) ListGroupsForPlugin

func (s *Service) ListGroupsForPlugin() ([]PluginGroupSummary, error)

ListGroupsForPlugin returns every team, ordered by name, with the Default team flagged.

func (*Service) ListModelRouters

func (s *Service) ListModelRouters(pageSize int, pageNumber int, all bool, opts ...ListOptions) ([]models.ModelRouter, int64, int, error)

ListModelRouters is the searchable, sortable form of ModelRouterService.ListRouters. A plain list (no search, no sort) is exactly ListRouters and goes through the interface, so an edition stub or a test double keeps its say. The router service interface is shared with the Enterprise submodule, so rather than widen it for search and sort the filtered query runs here against the same model, behind the same edition gate: Community Edition answers ErrEnterpriseFeature as ListRouters does.

func (*Service) ListProfiles

func (s *Service) ListProfiles(pageSize int, pageNumber int, all bool, sort string) (models.Profiles, int64, int, error)

func (*Service) ListSchedules

func (s *Service) ListSchedules(pluginID uint) ([]models.PluginSchedule, error)

ListSchedules lists all schedules for a plugin

func (*Service) ListSemanticRouters

func (s *Service) ListSemanticRouters(pageSize int, pageNumber int, all bool, opts ...ListOptions) ([]models.SemanticRouter, int64, int, error)

ListSemanticRouters is the searchable, sortable router list.

func (*Service) ListToolOperationsFromSpec

func (s *Service) ListToolOperationsFromSpec(toolID uint) ([]string, error)

ListToolOperationsFromSpec retrieves all operations from the tool's OpenAPI spec

func (*Service) ListUsers

func (s *Service) ListUsers(params ListUsersParams) (models.Users, int64, int, error)

func (*Service) ModelRouterReachableLLMs

func (s *Service) ModelRouterReachableLLMs(routerID uint) ([]models.LLM, error)

ModelRouterReachableLLMs lists the active LLMs behind a router's active vendors: what a grant of the router lets an App reach.

func (*Service) PatchAppMetadata

func (s *Service) PatchAppMetadata(appID uint, key, value string, deleteKey bool) (map[string]interface{}, error)

PatchAppMetadata atomically updates a single metadata key on an app. If deleteKey is true, the key is removed. Otherwise, the value (JSON string) is set. Uses a database transaction for safe concurrent access. PostgreSQL uses FOR UPDATE row locking; SQLite serializes transactions implicitly.

func (*Service) ProvisionHostUser

func (s *Service) ProvisionHostUser(id HostIdentity) (*models.User, error)

ProvisionHostUser returns the Studio user for a host-authenticated identity, creating it on first sight and keeping its name, email, administrator status and (when given) groups in step with the host.

A user is found by subject. On first sight an existing user with the same email and no host subject is linked (an account that predates embedding); otherwise a new host-origin user is created. Nothing is written when the identity is unchanged, apart from a throttled login stamp.

func (*Service) RebuildPermissionCatalogue

func (s *Service) RebuildPermissionCatalogue() error

RebuildPermissionCatalogue registers the resource of every installed plugin. main.go calls it before seeding the system roles so Viewer, Editor and Auditor are computed against the full catalogue.

func (*Service) RecordSubmissionActivity

func (s *Service) RecordSubmissionActivity(submissionID, actorID uint, actorName, activityType, feedback, internalNote string)

RecordSubmissionActivity logs an action on a submission for audit trail

func (*Service) RegisterPluginPermissionResources

func (s *Service) RegisterPluginPermissionResources(pluginID uint, rows []models.PluginPermissionResource, removeMissing bool) (string, int, error)

RegisterPluginPermissionResources stores runtime-registered sub-resources for a plugin (management API) and refreshes the catalogue. With removeMissing, runtime rows not in rows are deleted; manifest rows are untouched. It returns the plugin's permission key.

func (*Service) RegisterPluginResourceTypes

func (s *Service) RegisterPluginResourceTypes(pluginID uint, registrations []models.PluginResourceType) error

RegisterPluginResourceTypes upserts resource type records for a plugin. Called when a plugin is loaded and its manifest/capabilities are parsed. After registration, reconciles default group access by fetching instances from the plugin and ensuring new ones are assigned to the default group.

The plugin row is loaded so AccessGrantedViaApp can be resolved from its hook types when the registration leaves it undeclared; callers that already hold the plugin should use RegisterPluginResourceTypesForPlugin.

func (*Service) RegisterPluginResourceTypesForPlugin

func (s *Service) RegisterPluginResourceTypesForPlugin(plugin *models.Plugin, registrations []models.PluginResourceType) error

RegisterPluginResourceTypesForPlugin is RegisterPluginResourceTypes for a caller that already holds the plugin row. Each registration's AccessGrantedViaApp is resolved here (models.ResolveAccessGrantedViaApp) from AccessGrantedViaAppDeclared and the plugin's hook types, and stored, so every read path sees the effective value without loading the plugin.

func (*Service) RejectSubmission

func (s *Service) RejectSubmission(submissionID, reviewerID uint, feedback, reviewNotes string) (*models.Submission, error)

RejectSubmission rejects a submission (admin)

func (*Service) RemoveAllowedModel

func (s *Service) RemoveAllowedModel(id uint, modelPattern string) error

func (*Service) RemoveCatalogueFromGroup

func (s *Service) RemoveCatalogueFromGroup(catalogueID, groupID uint) error

func (*Service) RemoveDataCatalogueFromGroup

func (s *Service) RemoveDataCatalogueFromGroup(dataCatalogueID, groupID uint) error

func (*Service) RemoveDatasourceFromApp

func (s *Service) RemoveDatasourceFromApp(appID, datasourceID uint) error

RemoveDatasourceFromApp removes a datasource from an app

func (*Service) RemoveDatasourceFromDataCatalogue

func (s *Service) RemoveDatasourceFromDataCatalogue(dataCatalogueID, datasourceID uint) error

func (*Service) RemoveDependencyFromTool

func (s *Service) RemoveDependencyFromTool(toolID uint, dependencyID uint) error

RemoveDependencyFromTool removes a dependency from a Tool

func (*Service) RemoveExtraContextFromChat

func (s *Service) RemoveExtraContextFromChat(toolID uint, fileStoreID uint) error

RemoveExtraContextFromChat removes a ExtraContext from a Chat

func (*Service) RemoveFileFromDatasource

func (s *Service) RemoveFileFromDatasource(dsID uint, fileStoreID uint) error

RemoveFileStoreFromTool removes a FileStore from a Tool

func (*Service) RemoveFileStoreFromTool

func (s *Service) RemoveFileStoreFromTool(toolID uint, fileStoreID uint) error

RemoveFileStoreFromTool removes a FileStore from a Tool

func (*Service) RemoveFilterFromTool

func (s *Service) RemoveFilterFromTool(toolID uint, filterID uint) error

RemoveFilterFromTool removes a Filter from a Tool

func (*Service) RemoveLLMFromApp

func (s *Service) RemoveLLMFromApp(appID, llmID uint) error

RemoveLLMFromApp removes an LLM from an app

func (*Service) RemoveLLMFromCatalogue

func (s *Service) RemoveLLMFromCatalogue(llmID, catalogueID uint) error

func (*Service) RemoveOperationFromTool

func (s *Service) RemoveOperationFromTool(toolID uint, operation string) error

RemoveOperationFromTool removes an operation from a tool

func (*Service) RemovePluginPermissions

func (s *Service) RemovePluginPermissions(plugin *models.Plugin)

RemovePluginPermissions unregisters everything the plugin contributed.

func (*Service) RemoveTagFromDataCatalogue

func (s *Service) RemoveTagFromDataCatalogue(dataCatalogueID, tagID uint) error

func (*Service) RemoveTagFromToolCatalogue

func (s *Service) RemoveTagFromToolCatalogue(tagID, toolCatalogueID uint) error

func (*Service) RemoveToolCatalogueFromGroup

func (s *Service) RemoveToolCatalogueFromGroup(toolCatalogueID, groupID uint) error

func (*Service) RemoveToolFromApp

func (s *Service) RemoveToolFromApp(appID, toolID uint) error

RemoveToolFromApp removes a tool from an app

func (*Service) RemoveToolFromToolCatalogue

func (s *Service) RemoveToolFromToolCatalogue(toolID, toolCatalogueID uint) error

func (*Service) RemoveUserFromGroup

func (s *Service) RemoveUserFromGroup(userID, groupID uint) error

func (*Service) RequestChanges

func (s *Service) RequestChanges(submissionID, reviewerID uint, feedback, reviewNotes string) (*models.Submission, error)

RequestChanges requests changes from the submitter (admin)

func (*Service) ResetAppBudget

func (s *Service) ResetAppBudget(appID uint) error

ResetAppBudget resets the budget period for an app by setting the start date to today

func (*Service) ResetBrandingToDefaults

func (s *Service) ResetBrandingToDefaults(isAdmin bool) (*models.BrandingSettings, error)

ResetBrandingToDefaults resets all branding settings to defaults

func (*Service) ResolveActorName

func (s *Service) ResolveActorName(actorID uint, actorName string) string

ResolveActorName returns a human-readable name for an activity actor.

Every caller passes an empty actorName, which left ActorName empty on every row and made the review history render "User #1" instead of naming people. An audit trail that does not name people is most of the way to not being an audit trail, so resolve the name here rather than at each call site.

A caller that already knows the name keeps it. A lookup failure is not worth failing the write for: the UI falls back to "User #<id>", which is what it rendered before.

func (*Service) ResourceInstanceGroups

func (s *Service) ResourceInstanceGroups(pluginID uint, slug, instanceID string) ([]uint, error)

ResourceInstanceGroups returns the IDs of the teams granted one of the plugin's resource instances, ascending.

func (*Service) RevokeAPIKeyForUser

func (a *Service) RevokeAPIKeyForUser(id uint) error

RevokeAPIKeyForUser clears the user's API key; the key stops working immediately and the user shows as having none issued.

func (*Service) RollbackResource

func (s *Service) RollbackResource(resourceType string, resourceID uint, versionID uint, adminID uint) error

RollbackResource restores a resource to a previous version snapshot

func (*Service) SearchApps

func (s *Service) SearchApps(searchTerm string, pageSize, pageNumber int, all bool, sort string) (models.Apps, int64, int, error)

SearchApps returns apps matching the given search term with pagination

func (*Service) SearchCataloguesByNameStub

func (s *Service) SearchCataloguesByNameStub(stub string) (models.Catalogues, error)

func (*Service) SearchChatHistoryRecords

func (s *Service) SearchChatHistoryRecords(userID uint, query string, pageSize int, pageNumber int, all bool) ([]models.ChatHistoryRecord, int64, int, error)

SearchChatHistoryRecords searches for ChatHistoryRecords by name for a given UserID

func (*Service) SearchDataCatalogues

func (s *Service) SearchDataCatalogues(query string) (models.DataCatalogues, error)

func (*Service) SearchDatasources

func (s *Service) SearchDatasources(query string) (models.Datasources, error)

func (*Service) SearchFileStores

func (s *Service) SearchFileStores(query string) ([]models.FileStore, error)

SearchFileStores searches for filestore entries matching the given query in filename or description

func (*Service) SearchGroups

func (s *Service) SearchGroups(term string, pageSize int, pageNumber int, all bool, sort string) (models.Groups, int64, int, error)

func (*Service) SearchGroupsByNameStub

func (s *Service) SearchGroupsByNameStub(stub string) (models.Groups, error)

func (*Service) SearchLLMSettingsByModelStub

func (s *Service) SearchLLMSettingsByModelStub(modelStub string) (*models.LLMSettingsSlice, error)

SearchLLMSettingsByModelStub searches for LLMSettings by model name stub

func (*Service) SearchTagsByNameStub

func (s *Service) SearchTagsByNameStub(stub string) (models.Tags, error)

func (*Service) SearchToolCatalogues

func (s *Service) SearchToolCatalogues(query string) (models.ToolCatalogues, error)

func (*Service) SearchTools

func (s *Service) SearchTools(query string) ([]models.Tool, error)

SearchTools searches for tools matching the given query in name or description

func (*Service) SearchUsersByEmailStub

func (s *Service) SearchUsersByEmailStub(stub string) (models.Users, error)

func (*Service) SecretReferences

func (s *Service) SecretReferences() (map[string][]SecretReference, error)

SecretReferences returns, keyed by secret name, the objects that read each secret through a $SECRET/<name> reference. It is served from the secret_references index that the LLM, tool and datasource model hooks maintain (see models.SecretReference), so the secrets list is one indexed query however many objects exist.

func (*Service) SecretReferencesByNames

func (s *Service) SecretReferencesByNames(names []string) (map[string][]SecretReference, error)

SecretReferencesByNames is SecretReferences restricted to the given secret names: the secrets list calls it for the page it is about to render, so the query is bounded by the page size rather than by the whole index.

func (*Service) SemanticRouterReachableLLMs

func (s *Service) SemanticRouterReachableLLMs(routerID uint) ([]models.LLM, error)

SemanticRouterReachableLLMs lists the active LLMs a router's routes can answer with: what a grant of the router lets an App reach.

func (*Service) SetAppActive

func (s *Service) SetAppActive(id uint, active bool, userID uint) (*models.App, error)

SetAppActive sets the is_active flag of an app. Apps have no object hooks.

func (*Service) SetAppGovernanceState

func (s *Service) SetAppGovernanceState(appID uint, active *bool, flags map[string]string, reason, setBy string) (*models.App, map[string]interface{}, error)

SetAppGovernanceState changes an App's active state and governance flags for a governance plugin. active nil leaves the state alone; a flag with an empty value is cleared. It returns the App and what changed (for the audit trail): {"is_active": {old, new}, "flag:<name>": {old, new}}.

func (*Service) SetAppMCPServers

func (s *Service) SetAppMCPServers(appID uint, serverIDs []uint) (*models.App, error)

SetAppMCPServers replaces the App's MCP server bindings, reconciles the access-grant ledger and returns the App reloaded with its associations, so callers answer with the new state without a second fetch. Callers validate with ValidateMCPServerBindings first.

func (*Service) SetAppPluginResources

func (s *Service) SetAppPluginResources(appID, resourceTypeID uint, instanceIDs []string) error

SetAppPluginResources replaces all plugin resource associations for an app and a given resource type. This is a full replace (delete old, insert new).

func (*Service) SetAuditService

func (s *Service) SetAuditService(a audit.Service)

SetAuditService attaches the audit trail. Called by api.SetAuditService.

func (*Service) SetCatalogueRouters

func (s *Service) SetCatalogueRouters(catalogueID uint, modelRouterIDs, semanticRouterIDs *[]uint) (*CatalogueRouters, error)

SetCatalogueRouters replaces the catalogue's routers of each kind given; a nil list leaves that kind as it is. Every router must exist.

func (*Service) SetChatExtraContexts

func (s *Service) SetChatExtraContexts(toolID uint, fileStoreIDs []uint) error

SetChatExtraContexts replaces all existing ExtraContext associations with new ones

func (*Service) SetDatasourceActive

func (s *Service) SetDatasourceActive(id uint, active bool, userID uint) (*models.Datasource, error)

SetDatasourceActive sets the active flag of a datasource.

func (*Service) SetEventBus

func (s *Service) SetEventBus(bus eventbridge.Bus)

SetEventBus sets the event bus and initializes the system event emitter

func (*Service) SetGroupPluginResources

func (s *Service) SetGroupPluginResources(groupID, resourceTypeID uint, instanceIDs []string) error

SetGroupPluginResources replaces all plugin resource access entries for a group and a given resource type.

func (*Service) SetGroupPluginResourcesBatch

func (s *Service) SetGroupPluginResourcesBatch(groupID uint, updates []GroupPluginResourceUpdate) error

SetGroupPluginResourcesBatch atomically replaces plugin resource access entries for a group across multiple resource types in a single transaction.

func (*Service) SetLLMActive

func (s *Service) SetLLMActive(id uint, active bool, userID uint) (*models.LLM, error)

SetLLMActive sets the active flag of an LLM.

func (*Service) SetLicensingService

func (s *Service) SetLicensingService(svc licensing.Service)

SetLicensingService sets the licensing service for plugin license checks

func (*Service) SetModelRouterCatalogues

func (s *Service) SetModelRouterCatalogues(routerID uint, catalogueIDs []uint) ([]models.Catalogue, error)

SetModelRouterCatalogues replaces the LLM catalogues a router is published in. Every catalogue must exist.

func (*Service) SetProfileUseInLoginPage

func (s *Service) SetProfileUseInLoginPage(profileID string) error

func (*Service) SetResourceInstanceGroups

func (s *Service) SetResourceInstanceGroups(pluginID uint, slug, instanceID string, groupIDs []uint, replace bool) ([]uint, error)

SetResourceInstanceGroups grants one of the plugin's resource instances to groupIDs. With replace the instance ends up granted to exactly groupIDs (an empty list revokes every grant); otherwise the groups are added to the existing grants. Returns the grants after the change.

Revoked rows are hard-deleted: the (group, type, instance) unique index would otherwise block granting the same team again later.

func (*Service) SetSemanticRouterCatalogues

func (s *Service) SetSemanticRouterCatalogues(routerID uint, catalogueIDs []uint) ([]models.Catalogue, error)

SetSemanticRouterCatalogues replaces the LLM catalogues a router is published in. Every catalogue must exist.

func (*Service) SetToolActive

func (s *Service) SetToolActive(id uint, active bool, userID uint) (*models.Tool, error)

SetToolActive sets the active flag of a tool.

func (*Service) SetToolDependencies

func (s *Service) SetToolDependencies(toolID uint, dependencyIDs []uint) error

SetToolDependencies replaces all existing Tool dependencies with new ones

func (*Service) SetToolFileStores

func (s *Service) SetToolFileStores(toolID uint, fileStoreIDs []uint) error

SetToolFileStores replaces all existing FileStore associations with new ones

func (*Service) SetToolFilters

func (s *Service) SetToolFilters(toolID uint, filterIDs []uint) error

SetToolFilters replaces all existing Filter associations with new ones

func (*Service) SetTykMCPHost

func (s *Service) SetTykMCPHost(h *tykmcp.HostConnection)

SetTykMCPHost sets the Dashboard connection the host application provides; InitTykMCP hands it to the service it builds.

func (*Service) SetUserBudgetTeam

func (s *Service) SetUserBudgetTeam(userID uint, teamID *uint) error

SetUserBudgetTeam sets (or clears, with nil) the team a user's new Apps are attributed to. The user must be a member of the team.

func (*Service) SetUserDisabled

func (s *Service) SetUserDisabled(actorID, id uint, disabled bool) (*models.User, error)

SetUserDisabled switches an account off or on. Disabling drops the live session and any pending reset token, and deactivates the credentials of every app the user owns so their gateway access stops with them; those credentials are not re-activated on enable (an administrator does that per app, as after a deletion). The caller cannot disable themselves, the super admin, or (Enterprise) the last Owner.

func (*Service) SkipQuickStartForUser

func (s *Service) SkipQuickStartForUser(userID uint) error

func (*Service) StartReview

func (s *Service) StartReview(submissionID, reviewerID uint) (*models.Submission, error)

StartReview claims a submission for review (admin)

func (*Service) Stop

func (s *Service) Stop() error

Stop stops the service's background workers and plugins, leaving the database open for whoever owns it.

func (*Service) SubmitSubmission

func (s *Service) SubmitSubmission(id, submitterID uint) (*models.Submission, error)

SubmitSubmission moves a draft to submitted status

func (*Service) SubscribeResourceInstanceChanges

func (s *Service) SubscribeResourceInstanceChanges(bus eventbridge.Bus)

SubscribeResourceInstanceChanges registers an event handler that refreshes denormalized instance data in app_plugin_resources when a plugin notifies that an instance has changed. This keeps cached names, privacy scores, and metadata consistent with the plugin's source of truth.

Call this after SetEventBus to activate the subscription.

func (*Service) SyncPluginPermissions

func (s *Service) SyncPluginPermissions(plugin *models.Plugin)

SyncPluginPermissions registers (or refreshes) the plugin's permission resources: the base resource, the sub-resources its manifest declares (stored with source manifest, replacing the previous declaration) and any runtime-registered ones. A resource registered under a previous key is removed, and everything is dropped when the plugin no longer has an administrator surface.

func (*Service) TestDatasourceConnectivity

func (s *Service) TestDatasourceConnectivity(embedVendor, embedURL, embedAPIKey, embedModel string) (*DatasourceTestResult, error)

TestDatasourceConnectivity tests that an embedder can be created and optionally performs a test embedding

func (*Service) TruncateAfterMessage

func (s *Service) TruncateAfterMessage(sessionID string, afterID uint) (int64, error)

TruncateAfterMessage deletes every non-system message of a session whose id is greater than afterID (afterID 0 clears the conversation while keeping the system prompt). It is how an edit or a regenerate rewinds the stored history. It returns the number of rows removed.

func (*Service) UnavailableVectorStoreDatasources

func (s *Service) UnavailableVectorStoreDatasources() ([]models.Datasource, error)

UnavailableVectorStoreDatasources returns the datasources whose vector store this build cannot use (Chroma without cgo). Startup logs them: they fail every search and ingestion until moved to another store.

func (*Service) UpdateApp

func (s *Service) UpdateApp(id uint, name, description string, userID uint, datasourceIDs []uint, llmIDs []uint, toolIDs []uint, monthlyBudget *float64, budgetStartDate *time.Time, metadata map[string]interface{}, opts ...AppOption) (*models.App, error)

UpdateApp updates an existing app with validity checks

func (*Service) UpdateAppTitle

func (s *Service) UpdateAppTitle(title string, isAdmin bool) (*models.BrandingSettings, error)

UpdateAppTitle updates the application title

func (*Service) UpdateAppWithResources

func (s *Service) UpdateAppWithResources(
	id uint,
	name, description string,
	userID uint,
	datasourceIDs []uint,
	llmIDs []uint,
	toolIDs []uint,
	monthlyBudget *float64,
	budgetStartDate *time.Time,
	metadata map[string]interface{},
	pluginResources []PluginResourceSelection,
	opts ...AppOption,
) (*models.App, error)

UpdateAppWithResources updates an app with both built-in and plugin resource associations.

func (*Service) UpdateAttestationTemplate

func (s *Service) UpdateAttestationTemplate(id uint, name, text, appliesToType string, required, active bool, sortOrder int) (*models.AttestationTemplate, error)

UpdateAttestationTemplate updates an attestation template (admin)

func (*Service) UpdateBrandingColors

func (s *Service) UpdateBrandingColors(primaryColor, secondaryColor, backgroundColor string, isAdmin bool) (*models.BrandingSettings, error)

UpdateBrandingColors updates only the color settings

func (*Service) UpdateBrandingSettings

func (s *Service) UpdateBrandingSettings(settings *models.BrandingSettings, isAdmin bool) (*models.BrandingSettings, error)

UpdateBrandingSettings updates branding settings with validation

func (*Service) UpdateCatalogue

func (s *Service) UpdateCatalogue(id uint, name string) (*models.Catalogue, error)

func (*Service) UpdateChat

func (s *Service) UpdateChat(id uint, name string, description string, llmSettingsID, llmID uint, groupIDs []uint,
	filterIDs []uint, ragN int, toolSupport bool, systemPrompt string, defaultDSID uint, defaultToolIDs []uint) (*models.Chat, error)

UpdateChat updates an existing chat

func (*Service) UpdateChatHistoryRecord

func (s *Service) UpdateChatHistoryRecord(id uint, sessionID string, chatID, userID uint, name string) (*models.ChatHistoryRecord, error)

UpdateChatHistoryRecord updates an existing ChatHistoryRecord

func (*Service) UpdateCredential

func (s *Service) UpdateCredential(credential *models.Credential) error

UpdateCredential updates an existing credential

func (*Service) UpdateCustomCSS

func (s *Service) UpdateCustomCSS(css string, isAdmin bool) (*models.BrandingSettings, error)

UpdateCustomCSS updates the custom CSS

func (*Service) UpdateDataCatalogue

func (s *Service) UpdateDataCatalogue(id uint, name, shortDesc, longDesc, icon string) (*models.DataCatalogue, error)

func (*Service) UpdateDatasource

func (s *Service) UpdateDatasource(id uint, name, shortDesc, longDesc, icon, url string, privacyScore int, dbConnString, dbSourceType, dbConnAPIKey, dbName string, embed EmbedderInput, active bool, tagNames []string, userID uint, namespace ...string) (*models.Datasource, error)

func (*Service) UpdateEmbedder

func (s *Service) UpdateEmbedder(id uint, changes *models.Embedder, userID uint) (*models.Embedder, error)

UpdateEmbedder applies changes to an embedder. The key is kept when the caller sends it back redacted. The model and API compatibility (vendor, or the linked LLM) cannot change while datasources use the embedder, and the privacy score cannot drop below theirs.

func (*Service) UpdateFileStore

func (s *Service) UpdateFileStore(id uint, fileName, description, content string, length int) (*models.FileStore, error)

UpdateFileStore updates an existing filestore entry with validity checks

func (*Service) UpdateFilter

func (s *Service) UpdateFilter(id uint, name, description string, script []byte, responseFilter bool, namespace string) (*models.Filter, error)

UpdateFilter updates the script-filter attributes of a filter. Kept for the plugin management API; it leaves Kind and Config untouched so a guardrail filter renamed through it keeps its provider configuration.

func (*Service) UpdateFilterFromSpec

func (s *Service) UpdateFilterFromSpec(id uint, spec FilterSpec) (*models.Filter, error)

UpdateFilterFromSpec replaces every attribute of a filter.

func (*Service) UpdateGroup

func (s *Service) UpdateGroup(id uint, name string, userIDs, catalogueIDs, dataCatalogueIDs, toolCatalogueIDs []uint) (*models.Group, error)

func (*Service) UpdateGroupCatalogues

func (s *Service) UpdateGroupCatalogues(id uint, catalogueIDs, dataCatalogueIDs, toolCatalogueIDs []uint) error

func (*Service) UpdateGroupUsers

func (s *Service) UpdateGroupUsers(id uint, userIDs []uint) error

func (*Service) UpdateLLM

func (s *Service) UpdateLLM(id uint, name, apiKey, apiEndpoint string,
	privacyScore int, shortDescription, longDescription, logoURL string,
	vendor models.Vendor, active bool, filters []*models.Filter,
	defaultModel string, allowedModels []string, monthlyBudget *float64,
	budgetStartDate *time.Time, namespace string, dontLogBodies bool, metadata models.JSONMap,
	failover *models.LLMFailover) (*models.LLM, error)

func (*Service) UpdateLLMMetadata

func (s *Service) UpdateLLMMetadata(id uint, metadata models.JSONMap) error

UpdateLLMMetadata updates only the metadata field of an LLM. Used by the API to persist vendor-specific configuration (e.g., AWS credentials for Bedrock).

func (*Service) UpdateLLMSettings

func (s *Service) UpdateLLMSettings(settings *models.LLMSettings) (*models.LLMSettings, error)

UpdateLLMSettings updates an existing LLMSettings

func (*Service) UpdateModelPrice

func (s *Service) UpdateModelPrice(id uint, modelName, vendor string, cpt, cpit, cacheWritePT, cacheReadPT float64, currency string) (*models.ModelPrice, error)

UpdateModelPrice updates an existing model price

func (*Service) UpdateModelPriceAndRecalculate

func (s *Service) UpdateModelPriceAndRecalculate(id uint, modelName, vendor string, cpt, cpit, cacheWritePT, cacheReadPT float64, currency string) (*models.ModelPrice, error)

UpdateModelPriceAndRecalculate updates an existing model price and recalculates all associated chat record costs

func (*Service) UpdateMultipleModelPrices

func (s *Service) UpdateMultipleModelPrices(modelPrices models.ModelPrices) error

UpdateMultipleModelPrices updates multiple model prices at once

func (*Service) UpdateProfile

func (s *Service) UpdateProfile(profileID string, updatedProfile *models.Profile, userID uint) (*models.Profile, error)

func (*Service) UpdateSchedule

func (s *Service) UpdateSchedule(pluginID uint, scheduleID uint, updates map[string]interface{}) (*models.PluginSchedule, error)

UpdateSchedule updates an existing schedule

func (*Service) UpdateSubmission

func (s *Service) UpdateSubmission(id uint, submitterID uint, payload models.JSONMap,
	attestations models.JSONMap, suggestedPrivacy int, privacyJustification string,
	primaryContact, secondaryContact, slaExpectation string, dataCutoffDate *time.Time,
	documentationURL, notes string) (*models.Submission, error)

UpdateSubmission updates a draft or changes_requested submission

func (*Service) UpdateTag

func (s *Service) UpdateTag(id uint, name string) (*models.Tag, error)

func (*Service) UpdateTool

func (s *Service) UpdateTool(id uint, name, description, toolType string, oasSpec string, privacyScore int, schemaName, APIKey string) (*models.Tool, error)

UpdateTool updates an existing tool with validity checks

func (*Service) UpdateToolCatalogue

func (s *Service) UpdateToolCatalogue(id uint, name, shortDescription, longDescription, icon string) (*models.ToolCatalogue, error)

func (*Service) UpdateUser

func (s *Service) UpdateUser(user *models.User, dto UserDTO) (*models.User, error)

func (*Service) UploadFavicon

func (s *Service) UploadFavicon(file multipart.File, header *multipart.FileHeader, isAdmin bool) (*models.BrandingSettings, error)

UploadFavicon handles favicon file upload

func (s *Service) UploadLogo(file multipart.File, header *multipart.FileHeader, isAdmin bool) (*models.BrandingSettings, error)

UploadLogo handles logo file upload

func (*Service) ValidateLLMFailover

func (s *Service) ValidateLLMFailover(primary *models.LLM, f models.LLMFailover) error

ValidateLLMFailover checks a waterfall against the LLM it is attached to. primary.ID is zero on create; every other primary field is already final.

The rules exist because a fallback silently widens what the app can reach: access to a fallback is inherited from the primary, so the fallback must be at least as private, it must live where the primary lives (same namespace or global, or an edge in that namespace would not have it), and the model must be one the fallback actually allows -- using the same matcher the proxy applies at request time.

func (*Service) ValidateMCPServerBindings

func (s *Service) ValidateMCPServerBindings(userID uint, isAdmin bool, llmIDs []uint, serverIDs []uint) ([]models.MCPServer, error)

ValidateMCPServerBindings checks that every server may be bound by this user to an App with the given providers: visible (team grant, or any published server for an administrator), published and active on the Dashboard, and within the privacy rule (no server above the App's highest-privacy provider). It returns the servers in the order given.

func (*Service) ValidateModelRouterBindings

func (s *Service) ValidateModelRouterBindings(userID uint, isAdmin bool, routerIDs []uint) ([]models.ModelRouter, error)

ValidateModelRouterBindings checks that every router may be granted by this user: active, and in an LLM catalogue one of the user's teams holds (an administrator may grant any active router). It returns the routers in the order given.

func (*Service) ValidateOASSpec

func (s *Service) ValidateOASSpec(oasSpecBase64 string) (*SpecValidationResult, error)

ValidateOASSpec validates an OpenAPI spec and returns structured results

func (*Service) ValidateProfile

func (s *Service) ValidateProfile(profile *models.Profile, userID uint, validateProfileID bool) error

func (*Service) ValidateSemanticRouterBindings

func (s *Service) ValidateSemanticRouterBindings(userID uint, isAdmin bool, routerIDs []uint) ([]models.SemanticRouter, error)

ValidateSemanticRouterBindings checks that every router may be granted by this user: active, and in an LLM catalogue one of the user's teams holds (an administrator may grant any active router).

type ServiceInterface

type ServiceInterface interface {
	// LLM Management
	GetActiveLLMs() ([]models.LLM, error)
	GetLLMByID(id uint) (*models.LLM, error)
	GetLLMSettingsByID(id uint) (*models.LLMSettings, error)

	// Datasource Management
	GetActiveDatasources() ([]models.Datasource, error)
	GetDatasourceByID(id uint) (*models.Datasource, error)

	// Authentication & Authorization
	GetCredentialBySecret(secret string) (*models.Credential, error)
	AuthenticateUser(email, password string) (*models.User, error)
	GetUserByAPIKey(apiKey string) (*models.User, error)
	GetUserByEmail(email string) (*models.User, error)
	GetUserByID(id uint, preload ...string) (*models.User, error)
	AddUserToGroup(userID, groupID uint) error

	// OAuth Authentication (returns errors for implementations that don't support OAuth)
	GetValidAccessTokenByToken(token string) (*models.AccessToken, error)
	GetOAuthClient(clientID string) (*models.OAuthClient, error)

	// App Management
	GetAppByID(id uint) (*models.App, error)
	GetAppByCredentialID(credID uint) (*models.App, error)

	// Tool Management
	GetToolByID(id uint) (*models.Tool, error)
	GetToolBySlug(slug string) (*models.Tool, error)
	CallToolOperation(toolID uint, operationID string, params map[string][]string, payload map[string]interface{}, headers map[string][]string) (interface{}, error)

	// Analytics & Pricing
	GetModelPriceByModelNameAndVendor(modelName, vendor string) (*models.ModelPrice, error)

	// Filter Management (for scripting support)
	GetFilterByID(id uint) (*models.Filter, error)
	GetAllFilters(pageSize int, pageNumber int, all bool) ([]models.Filter, int64, int, error)
}

ServiceInterface defines the core operations needed by the application. This interface abstracts the data layer, allowing implementations to use databases, files, APIs, or any other backend while providing the same functionality.

This unified interface consolidates functionality from the original ServiceInterface and GatewayServiceInterface to eliminate duplication and confusion.

type SidebarMenuItem

type SidebarMenuItem struct {
	ID           string                 `json:"id"`
	Label        string                 `json:"label"`
	Icon         string                 `json:"icon"`
	Path         string                 `json:"path,omitempty"`
	Title        string                 `json:"title,omitempty"`
	PluginID     uint                   `json:"plugin_id"`
	PluginName   string                 `json:"plugin_name"`
	ComponentTag string                 `json:"component_tag,omitempty"`
	EntryPoint   string                 `json:"entry_point,omitempty"`
	MountConfig  map[string]interface{} `json:"mount_config,omitempty"`
	// RequiredPermission is the permission needed to see the section
	// (manifest mount_config.required_permission, else the default).
	RequiredPermission string           `json:"required_permission,omitempty"`
	SubItems           []SidebarSubItem `json:"sub_items,omitempty"`
}

SidebarMenuItem represents a plugin-contributed sidebar menu item

type SidebarSubItem

type SidebarSubItem struct {
	ID           string                 `json:"id"`
	Text         string                 `json:"text"`
	Path         string                 `json:"path"`
	ComponentTag string                 `json:"component_tag"`
	EntryPoint   string                 `json:"entry_point"`
	MountConfig  map[string]interface{} `json:"mount_config"`
	// RequiredPermission is the permission needed to open the page.
	RequiredPermission string `json:"required_permission,omitempty"`
}

SidebarSubItem represents a sub-item within a plugin sidebar section

type SpecExtractedAuthScheme

type SpecExtractedAuthScheme struct {
	Type    string `json:"type"`
	Name    string `json:"name"`
	In      string `json:"in,omitempty"`
	KeyName string `json:"key_name,omitempty"`
}

SpecExtractedAuthScheme describes an auth scheme found in the spec

type SpecExtractedInfo

type SpecExtractedInfo struct {
	Operations  []string                  `json:"operations"`
	AuthSchemes []SpecExtractedAuthScheme `json:"auth_schemes"`
	ServerURL   string                    `json:"server_url"`
}

SpecExtractedInfo contains useful data extracted from a valid spec

type SpecValidationError

type SpecValidationError struct {
	Field   string `json:"field"`
	Message string `json:"message"`
}

SpecValidationError represents a single validation issue with a field reference

type SpecValidationResult

type SpecValidationResult struct {
	Valid     bool                    `json:"valid"`
	Errors    []SpecValidationError   `json:"errors"`
	Warnings  []SpecValidationWarning `json:"warnings"`
	Extracted *SpecExtractedInfo      `json:"extracted,omitempty"`
}

SpecValidationResult contains the full result of OAS spec validation

type SpecValidationWarning

type SpecValidationWarning struct {
	Field   string `json:"field"`
	Message string `json:"message"`
}

SpecValidationWarning represents a non-blocking issue

type StorePendingAuthRequestArgs

type StorePendingAuthRequestArgs struct {
	ClientID            string
	UserID              uint
	RedirectURI         string
	Scope               string
	State               string
	CodeChallenge       string
	CodeChallengeMethod string
	ExpiresIn           time.Duration // How long the pending request is valid
}

StorePendingAuthRequestArgs holds arguments for storing a pending auth request.

type SubmissionApproveOptions

type SubmissionApproveOptions struct {
	// GatewayTags overrides the submitter's requested deployment target.
	GatewayTags *[]string
	// Publish publishes the created MCP server to the portal straight away.
	Publish bool
}

SubmissionApproveOptions carries reviewer choices that only apply to some resource types.

type SyncStatusService

type SyncStatusService struct {
	// contains filtered or unexported fields
}

SyncStatusService manages configuration sync status between control and edge gateways

func NewSyncStatusService

func NewSyncStatusService(db *gorm.DB) *SyncStatusService

NewSyncStatusService creates a new SyncStatusService

func (*SyncStatusService) GetNamespaceSyncStatus

func (s *SyncStatusService) GetNamespaceSyncStatus(namespace string) (*NamespaceSyncSummary, []models.EdgeInstance, error)

GetNamespaceSyncStatus returns detailed sync status for a specific namespace

func (*SyncStatusService) GetNamespaceSyncSummary

func (s *SyncStatusService) GetNamespaceSyncSummary() ([]NamespaceSyncSummary, error)

GetNamespaceSyncSummary returns sync status for all namespaces

func (*SyncStatusService) GetPendingChanges

func (s *SyncStatusService) GetPendingChanges(namespace string) (*PendingChanges, error)

GetPendingChanges lists what changed in the namespace since its last push. "", "global" and "default" all mean the default namespace (models.CanonicalNamespace), which ships the global objects plus those filed under "default"; a named namespace sees its own objects plus the global ones. This mirrors grpc.ControlServer.getConfigurationSnapshot.

When no push was recorded (a database from before last_push_at existed, or edges that only ever got their configuration when they registered) the latest time an edge confirmed it was in sync is the reference point (Baseline edge_ack) rather than reporting everything as never pushed. Offline edges count: the configuration as of their ack reached them.

func (*SyncStatusService) GetPendingNamespaces

func (s *SyncStatusService) GetPendingNamespaces() ([]string, error)

GetPendingNamespaces returns namespaces that have edges pending sync

func (*SyncStatusService) GetSyncAuditLog

func (s *SyncStatusService) GetSyncAuditLog(namespace, edgeID, eventType string, limit int) ([]models.SyncAuditLog, error)

GetSyncAuditLog returns audit log entries with optional filtering

func (*SyncStatusService) HasPendingSyncs

func (s *SyncStatusService) HasPendingSyncs() (bool, error)

HasPendingSyncs returns true if any namespace has edges waiting for sync

func (*SyncStatusService) MarkStaleEdges

func (s *SyncStatusService) MarkStaleEdges(staleThreshold time.Duration) error

MarkStaleEdges marks edges that have been out of sync for too long as stale staleThreshold is the duration after which pending edges are marked as stale (default 15 minutes)

type SystemEventEmitter

type SystemEventEmitter struct {
	// contains filtered or unexported fields
}

SystemEventEmitter provides a clean interface for emitting system events

func NewSystemEventEmitter

func NewSystemEventEmitter(bus eventbridge.Bus, nodeID string) *SystemEventEmitter

NewSystemEventEmitter creates a new SystemEventEmitter

func (*SystemEventEmitter) EmitAppApproved

func (e *SystemEventEmitter) EmitAppApproved(app interface{}, objectID uint, userID uint)

EmitAppApproved emits an event when an App is approved (credential activated)

func (*SystemEventEmitter) EmitAppCreated

func (e *SystemEventEmitter) EmitAppCreated(app interface{}, objectID uint, userID uint)

EmitAppCreated emits an event when an App is created

func (*SystemEventEmitter) EmitAppDeleted

func (e *SystemEventEmitter) EmitAppDeleted(objectID uint, userID uint)

EmitAppDeleted emits an event when an App is deleted

func (*SystemEventEmitter) EmitAppPluginResourcesChanged

func (e *SystemEventEmitter) EmitAppPluginResourcesChanged(appID uint, userID uint)

EmitAppPluginResourcesChanged emits an event when plugin resources on an App change. This fires after SetAppPluginResources() completes, so subscribers see the final state.

func (*SystemEventEmitter) EmitAppUpdated

func (e *SystemEventEmitter) EmitAppUpdated(app interface{}, objectID uint, userID uint)

EmitAppUpdated emits an event when an App is updated

func (*SystemEventEmitter) EmitDatasourceCreated

func (e *SystemEventEmitter) EmitDatasourceCreated(datasource interface{}, objectID uint, userID uint)

EmitDatasourceCreated emits an event when a Datasource is created

func (*SystemEventEmitter) EmitDatasourceDeleted

func (e *SystemEventEmitter) EmitDatasourceDeleted(objectID uint, userID uint)

EmitDatasourceDeleted emits an event when a Datasource is deleted

func (*SystemEventEmitter) EmitDatasourceUpdated

func (e *SystemEventEmitter) EmitDatasourceUpdated(datasource interface{}, objectID uint, userID uint)

EmitDatasourceUpdated emits an event when a Datasource is updated

func (*SystemEventEmitter) EmitEmbedderCreated

func (e *SystemEventEmitter) EmitEmbedderCreated(embedder interface{}, objectID uint, userID uint)

EmitEmbedderCreated emits an event when an Embedder is created

func (*SystemEventEmitter) EmitEmbedderDeleted

func (e *SystemEventEmitter) EmitEmbedderDeleted(objectID uint, userID uint)

EmitEmbedderDeleted emits an event when an Embedder is deleted

func (*SystemEventEmitter) EmitEmbedderUpdated

func (e *SystemEventEmitter) EmitEmbedderUpdated(embedder interface{}, objectID uint, userID uint)

EmitEmbedderUpdated emits an event when an Embedder is updated

func (*SystemEventEmitter) EmitFilterCreated

func (e *SystemEventEmitter) EmitFilterCreated(filter interface{}, objectID uint, userID uint)

EmitFilterCreated emits an event when a Filter is created

func (*SystemEventEmitter) EmitFilterDeleted

func (e *SystemEventEmitter) EmitFilterDeleted(objectID uint, userID uint)

EmitFilterDeleted emits an event when a Filter is deleted

func (*SystemEventEmitter) EmitFilterUpdated

func (e *SystemEventEmitter) EmitFilterUpdated(filter interface{}, objectID uint, userID uint)

EmitFilterUpdated emits an event when a Filter is updated

func (*SystemEventEmitter) EmitGroupCreated

func (e *SystemEventEmitter) EmitGroupCreated(group interface{}, objectID uint, userID uint)

EmitGroupCreated emits an event when a Group is created

func (*SystemEventEmitter) EmitGroupDeleted

func (e *SystemEventEmitter) EmitGroupDeleted(objectID uint, userID uint)

EmitGroupDeleted emits an event when a Group is deleted

func (*SystemEventEmitter) EmitGroupUpdated

func (e *SystemEventEmitter) EmitGroupUpdated(group interface{}, objectID uint, userID uint)

EmitGroupUpdated emits an event when a Group is updated

func (*SystemEventEmitter) EmitLLMCreated

func (e *SystemEventEmitter) EmitLLMCreated(llm interface{}, objectID uint, userID uint)

EmitLLMCreated emits an event when an LLM is created

func (*SystemEventEmitter) EmitLLMDeleted

func (e *SystemEventEmitter) EmitLLMDeleted(objectID uint, userID uint)

EmitLLMDeleted emits an event when an LLM is deleted

func (*SystemEventEmitter) EmitLLMUpdated

func (e *SystemEventEmitter) EmitLLMUpdated(llm interface{}, objectID uint, userID uint)

EmitLLMUpdated emits an event when an LLM is updated

func (*SystemEventEmitter) EmitModelPriceCreated

func (e *SystemEventEmitter) EmitModelPriceCreated(price interface{}, objectID uint, userID uint)

EmitModelPriceCreated emits an event when a ModelPrice is created

func (*SystemEventEmitter) EmitModelPriceDeleted

func (e *SystemEventEmitter) EmitModelPriceDeleted(objectID uint, userID uint)

EmitModelPriceDeleted emits an event when a ModelPrice is deleted

func (*SystemEventEmitter) EmitModelPriceUpdated

func (e *SystemEventEmitter) EmitModelPriceUpdated(price interface{}, objectID uint, userID uint)

EmitModelPriceUpdated emits an event when a ModelPrice is updated

func (*SystemEventEmitter) EmitModelRouterCreated

func (e *SystemEventEmitter) EmitModelRouterCreated(router interface{}, objectID uint, userID uint)

EmitModelRouterCreated emits an event when a ModelRouter is created

func (*SystemEventEmitter) EmitModelRouterDeleted

func (e *SystemEventEmitter) EmitModelRouterDeleted(objectID uint, userID uint)

EmitModelRouterDeleted emits an event when a ModelRouter is deleted

func (*SystemEventEmitter) EmitModelRouterUpdated

func (e *SystemEventEmitter) EmitModelRouterUpdated(router interface{}, objectID uint, userID uint)

EmitModelRouterUpdated emits an event when a ModelRouter is updated

func (*SystemEventEmitter) EmitObjectEvent

func (e *SystemEventEmitter) EmitObjectEvent(topic string, objectType string, action string, objectID uint, userID uint, object interface{})

EmitObjectEvent emits a system event for an object CRUD operation

func (*SystemEventEmitter) EmitPluginCreated

func (e *SystemEventEmitter) EmitPluginCreated(plugin interface{}, objectID uint, userID uint)

EmitPluginCreated emits an event when a Plugin is created

func (*SystemEventEmitter) EmitPluginDeleted

func (e *SystemEventEmitter) EmitPluginDeleted(objectID uint, userID uint)

EmitPluginDeleted emits an event when a Plugin is deleted

func (*SystemEventEmitter) EmitPluginUpdated

func (e *SystemEventEmitter) EmitPluginUpdated(plugin interface{}, objectID uint, userID uint)

EmitPluginUpdated emits an event when a Plugin is updated

func (*SystemEventEmitter) EmitSemanticRouterCreated

func (e *SystemEventEmitter) EmitSemanticRouterCreated(router interface{}, objectID uint, userID uint)

EmitSemanticRouterCreated emits an event when a SemanticRouter is created

func (*SystemEventEmitter) EmitSemanticRouterDeleted

func (e *SystemEventEmitter) EmitSemanticRouterDeleted(objectID uint, userID uint)

EmitSemanticRouterDeleted emits an event when a SemanticRouter is deleted

func (*SystemEventEmitter) EmitSemanticRouterUpdated

func (e *SystemEventEmitter) EmitSemanticRouterUpdated(router interface{}, objectID uint, userID uint)

EmitSemanticRouterUpdated emits an event when a SemanticRouter is updated

func (*SystemEventEmitter) EmitToolCreated

func (e *SystemEventEmitter) EmitToolCreated(tool interface{}, objectID uint, userID uint)

EmitToolCreated emits an event when a Tool is created

func (*SystemEventEmitter) EmitToolDeleted

func (e *SystemEventEmitter) EmitToolDeleted(objectID uint, userID uint)

EmitToolDeleted emits an event when a Tool is deleted

func (*SystemEventEmitter) EmitToolUpdated

func (e *SystemEventEmitter) EmitToolUpdated(tool interface{}, objectID uint, userID uint)

EmitToolUpdated emits an event when a Tool is updated

func (*SystemEventEmitter) EmitUserCreated

func (e *SystemEventEmitter) EmitUserCreated(user interface{}, objectID uint, userID uint)

EmitUserCreated emits an event when a User is created

func (*SystemEventEmitter) EmitUserDeleted

func (e *SystemEventEmitter) EmitUserDeleted(objectID uint, userID uint)

EmitUserDeleted emits an event when a User is deleted

func (*SystemEventEmitter) EmitUserUpdated

func (e *SystemEventEmitter) EmitUserUpdated(user interface{}, objectID uint, userID uint)

EmitUserUpdated emits an event when a User is updated

type TelemetryManager

type TelemetryManager struct {
	// contains filtered or unexported fields
}

TelemetryManager handles the periodic collection and transmission of telemetry data

func NewTelemetryManager

func NewTelemetryManager(db *gorm.DB, enabled bool, version string) *TelemetryManager

NewTelemetryManager creates a new telemetry manager

func (*TelemetryManager) IsEnabled

func (tm *TelemetryManager) IsEnabled() bool

IsEnabled returns whether telemetry is enabled

func (*TelemetryManager) Start

func (tm *TelemetryManager) Start()

Start begins the telemetry collection process

func (*TelemetryManager) Stop

func (tm *TelemetryManager) Stop()

Stop halts the telemetry collection process

type TelemetryPayload

type TelemetryPayload struct {
	Timestamp  time.Time              `json:"timestamp"`
	InstanceID string                 `json:"instance_id"`
	Version    string                 `json:"version"`
	LLMStats   map[string]interface{} `json:"llm_stats"`
	AppStats   map[string]interface{} `json:"app_stats"`
	UserStats  map[string]interface{} `json:"user_stats"`
	ChatStats  map[string]interface{} `json:"chat_stats"`
}

TelemetryPayload represents the structure of data sent to the telemetry service

type TelemetryService

type TelemetryService struct {
	DB *gorm.DB
	// contains filtered or unexported fields
}

func NewTelemetryService

func NewTelemetryService(db *gorm.DB) *TelemetryService

func (*TelemetryService) GetAppStats

func (s *TelemetryService) GetAppStats() (map[string]interface{}, error)

func (*TelemetryService) GetChatStats

func (s *TelemetryService) GetChatStats() (map[string]interface{}, error)

func (*TelemetryService) GetLLMStats

func (s *TelemetryService) GetLLMStats() (map[string]interface{}, error)

func (*TelemetryService) GetUserStats

func (s *TelemetryService) GetUserStats() (map[string]interface{}, error)

type TestNotificationService

type TestNotificationService = NotificationService

TestNotificationService is a mock notification service for testing

type ToolCreateOptions

type ToolCreateOptions struct {
	Operations []string
	Namespace  string
	// Active nil means active, the column default.
	Active *bool
	// Access methods; nil means the default for new tools
	// (models.DefaultToolRESTAccessEnabled / DefaultToolMCPAccessEnabled).
	RESTAccessEnabled *bool
	MCPAccessEnabled  *bool
}

ToolCreateOptions is what a creator may decide about a new tool beyond its basic fields. The zero value gives the defaults: no operations whitelisted, the global namespace, active, and chat only.

type ToolOperationDetail

type ToolOperationDetail struct {
	OperationID string
	Method      string
	Path        string
	Summary     string
	Description string
}

ToolOperationDetail represents detailed information about a tool operation

type UpdatePluginRequest

type UpdatePluginRequest struct {
	Name                *string                `json:"name"`
	Description         *string                `json:"description"`
	Command             *string                `json:"command"`
	Checksum            *string                `json:"checksum"`
	Config              map[string]interface{} `json:"config"`
	HookType            *string                `json:"hook_type"`
	HookTypes           []string               `json:"hook_types"`
	HookTypesCustomized *bool                  `json:"hook_types_customized"`
	IsActive            *bool                  `json:"is_active"`
	Namespace           *string                `json:"namespace"`
	OCIReference        *string                `json:"oci_reference"`
	LoadImmediately     *bool                  `json:"load_immediately,omitempty"` // Auto-load AI Studio plugins
}

type UpgradeDiff

type UpgradeDiff struct {
	Current []string `json:"current"`
	Target  []string `json:"target"`
	Added   []string `json:"added"`
	Removed []string `json:"removed"`
}

UpgradeDiff describes how a list (scopes, hooks) changes between versions.

type UpgradeRolledBackError

type UpgradeRolledBackError struct {
	Cause       error
	RollbackErr error // non-nil when restoring the previous version also failed
}

UpgradeRolledBackError is returned when the new version failed to start and the plugin was put back on the version it had.

func (*UpgradeRolledBackError) Error

func (e *UpgradeRolledBackError) Error() string

func (*UpgradeRolledBackError) Unwrap

func (e *UpgradeRolledBackError) Unwrap() error

type UpgradeScopesNotApprovedError

type UpgradeScopesNotApprovedError struct {
	Missing []string
}

UpgradeScopesNotApprovedError is returned when the target version asks for scopes the admin has not approved in this request.

func (*UpgradeScopesNotApprovedError) Error

type UpgradeVersionOption

type UpgradeVersionOption struct {
	Version        string    `json:"version"`
	Deprecated     bool      `json:"deprecated"`
	EnterpriseOnly bool      `json:"enterprise_only"`
	Installed      bool      `json:"installed"`
	ReleasedAt     time.Time `json:"released_at"`
}

UpgradeVersionOption is one entry of the version picker.

type UserDTO

type UserDTO struct {
	Email                string
	Name                 string
	Password             string
	IsAdmin              bool
	ShowChat             bool
	ShowPortal           bool
	EmailVerified        bool
	NotificationsEnabled bool
	AccessToSSOConfig    bool
	Groups               []uint
}

type UserEntitlements

type UserEntitlements struct {
	User           *models.User
	Catalogues     []models.Catalogue
	DataCatalogues []models.DataCatalogue
	ToolCatalogues []models.ToolCatalogue
	Chats          []models.Chat
}

func (*UserEntitlements) HasDataSourceAccess

func (ue *UserEntitlements) HasDataSourceAccess(dataSourceID uint) bool

func (*UserEntitlements) HasToolAccess

func (ue *UserEntitlements) HasToolAccess(toolID uint) bool

type VendorDriverInfo

type VendorDriverInfo struct {
	Name              string
	Vendor            string
	Version           string
	Description       string
	SupportedFeatures []string
}

VendorDriverInfo represents information about a vendor driver

Source Files

Directories

Path Synopsis
Package audit defines the platform audit trail: an append-only record of every action taken through the management API, who took it, from where, and what changed.
Package audit defines the platform audit trail: an append-only record of every action taken through the management API, who took it, from where, and what changed.
Package edition checks that a build carries every enterprise feature it was compiled for.
Package edition checks that a build carries every enterprise feature it was compiled for.
Package governed_metadata defines the Governed Metadata service used to attach admin-defined, validated metadata (owners, lifecycle state, risk tier, data classification, ...) to objects that AI Studio publishes to the portal or to edge gateways (LLMs, Tools, Datasources, and opted-in plugin resource types).
Package governed_metadata defines the Governed Metadata service used to attach admin-defined, validated metadata (owners, lifecycle state, risk tier, data classification, ...) to objects that AI Studio publishes to the portal or to edge gateways (LLMs, Tools, Datasources, and opted-in plugin resource types).
Package plugin_security provides security validation for plugins in both CE and ENT editions
Package plugin_security provides security validation for plugins in both CE and ENT editions
Package pushes delivers configuration pushes ("reloads") to edge gateways when several Studio replicas share the database.
Package pushes delivers configuration pushes ("reloads") to edge gateways when several Studio replicas share the database.
Package rbac defines role-based access control for the management API: roles are named bundles of catalogue permissions (see pkg/authz), bound to users or groups; a user's effective permissions are the union across their direct bindings and the bindings of every group they belong to.
Package rbac defines role-based access control for the management API: roles are named bundles of catalogue permissions (see pkg/authz), bound to users or groups; a user's effective permissions are the union across their direct bindings and the bindings of every group they belong to.
Package semantic_router manages Semantic Routers (Enterprise): routers that pick one of their named routes from what the prompt says.
Package semantic_router manages Semantic Routers (Enterprise): routers that pick one of their named routes from what the prompt says.
Package team_budget defines team (Group) level budgets: a monthly ceiling on the combined spend of a team's Apps, and an allocation pool that new Apps in the team draw their App budget from.
Package team_budget defines team (Group) level budgets: a monthly ceiling on the combined spend of a team's Apps, and an allocation pool that new Apps in the team draw their App budget from.
Package tykmcp defines the Tyk Dashboard MCP integration: MCP proxies defined in a Tyk Dashboard are discovered and published to the AI Portal as an asset class, registered from Studio into the Dashboard, proposed by portal users through the submission workflow, and access keys are brokered against Tyk security policies.
Package tykmcp defines the Tyk Dashboard MCP integration: MCP proxies defined in a Tyk Dashboard are discovered and published to the AI Portal as an asset class, registered from Studio into the Dashboard, proposed by portal users through the submission workflow, and access keys are brokered against Tyk security policies.
Package webhooks defines outbound webhook delivery: event-bus events are persisted, fanned out to administrator-approved HTTP targets, delivered with retries and a dead-letter queue, and every attempt is logged so an operator can search what was sent where, when, and what came back.
Package webhooks defines outbound webhook delivery: event-bus events are persisted, fanned out to administrator-approved HTTP targets, delivered with retries and a dead-letter queue, and every attempt is logged so an operator can search what was sent where, when, and what came back.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL