services

package
v2.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: AGPL-3.0 Imports: 106 Imported by: 2 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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 (
	GuardrailOutcomeBlocked       = "blocked"
	GuardrailOutcomeQuarantined   = "quarantined"
	GuardrailOutcomeJudgeSoftened = "judge_softened"
)

Guardrail outcome event names (GuardrailOutcomePayload.Outcome), each raised on eventbridge.GuardrailOutcomeTopicPrefix + name.

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"
	// TopicAppPromptTemplatesChanged: an App's trusted prompt templates
	// changed (proposed, edited, approved, retired, deleted). The approved
	// ones travel in the edge snapshot, so edges become pending. Payload
	// object: nil; object_id is the App.
	TopicAppPromptTemplatesChanged = "system.app.prompt_templates.changed"
	// TopicAppGuardrailExceptionsChanged: an App's guardrail exceptions
	// changed (proposed, edited, approved, retired, deleted, lapsed). The
	// approved ones travel in the edge snapshot, so edges become pending.
	// Payload object: nil; object_id is the App.
	TopicAppGuardrailExceptionsChanged = "system.app.guardrail_exceptions.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"

	// Secret events. The payload never carries the secret: no object, only
	// its ID. Edges get referenced values in their snapshot, so a change
	// makes them pending.
	TopicSecretCreated = "system.secret.created"
	TopicSecretUpdated = "system.secret.updated"
	TopicSecretDeleted = "system.secret.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 MaxNativeResourceListLimit = 1000

MaxNativeResourceListLimit caps NativeResourceStore.List pages.

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.

View Source
const ServiceAccountCode = "service_account"

ServiceAccountCode is the machine-readable code ("errors[0].code") of every refusal that exists because the account is a service account.

Variables

View Source
var (
	// ErrInvalidPromptTemplate is a template the service refuses to store.
	ErrInvalidPromptTemplate = errors.New("invalid prompt template")
	// ErrPromptTemplateConflict is an action the template's state does not
	// allow: approving one that is not proposed, or past the app's cap.
	ErrPromptTemplateConflict = errors.New("prompt template conflict")
	// ErrPromptTemplateChanged is an approval of a version that changed
	// since the administrator reviewed it (its content hash differs). It is
	// also an ErrPromptTemplateConflict.
	ErrPromptTemplateChanged = fmt.Errorf("%w: the template changed since it was reviewed", ErrPromptTemplateConflict)
)
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 (
	// ErrInvalidGuardrailException is an exception the service refuses to
	// store: a bad field, or an action below the app's floor.
	ErrInvalidGuardrailException = errors.New("invalid guardrail exception")
	// ErrGuardrailExceptionConflict is an action the exception's state does
	// not allow: approving one that is not proposed, a duplicate scope, or
	// past the app's cap.
	ErrGuardrailExceptionConflict = errors.New("guardrail exception conflict")
	// ErrGuardrailExceptionChanged is an approval of an exception that
	// changed since the administrator reviewed it. It is also an
	// ErrGuardrailExceptionConflict.
	ErrGuardrailExceptionChanged = fmt.Errorf("%w: the exception changed since it was reviewed", ErrGuardrailExceptionConflict)
)
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")
	// ErrHostServiceAccount is returned when the identity resolves to a
	// service account: a host can neither link one by email nor sign in
	// as one.
	ErrHostServiceAccount = errors.New("the identity matches a service account, which cannot sign in through the host")
)
View Source
var (
	// ErrNativeResourceExists: a row for this LLM, resource type and vendor
	// ID is already recorded.
	ErrNativeResourceExists = errors.New("native resource already recorded")
	// ErrNativeResourceNotFound: no row matches (or it belongs to another
	// App or LLM).
	ErrNativeResourceNotFound = errors.New("native resource not found")
)
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 (
	// ErrSecretNameTaken: another live secret has the name.
	ErrSecretNameTaken = errors.New("a secret with this name already exists")
	// ErrSecretDuplicateName: a grandfathered duplicate cannot move.
	ErrSecretDuplicateName = errors.New("another secret has the same name; rename one of them first")
)
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 ErrEdgePayloadRetry = errors.New("edge payload can be retried")

ErrEdgePayloadRetry marks an edge payload that was not delivered for a reason that may pass: the plugin is not loaded, healthy or reachable, or a service API call it made was refused (PermissionDenied while its scopes await approval) or unavailable. The edge keeps such a payload queued and sends it again; only the plugin's own refusal of the payload is final (rlk).

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 ErrGuardrailCapabilityReset = errors.New("the app's resources changed but its guardrail capability could not be cleared")

ErrGuardrailCapabilityReset: an App's resources changed but its attested guardrail capability could not be cleared. The change itself may have been saved; the caller reports a failure.

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 ErrInvalidGuardrailCapability = errors.New("invalid guardrail capability")

ErrInvalidGuardrailCapability is a capability value the service refuses.

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 ErrInvalidToolSpec = errors.New("invalid OpenAPI specification")

ErrInvalidToolSpec marks a tool's oas_spec that is not base64 of an OpenAPI 3 document the tool client can use.

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 ErrPushStained = errors.New("the push would carry pending changes from outside the Workspace")

ErrPushStained refuses a push limited to one Workspace (the only_workspace_id precondition) while changes from outside it are pending in a target namespace; the push would carry them. The error is a *PushStainedError.

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 ErrSubmissionAllowInternalHost = errors.New("submissions may not set allow_internal_host; an administrator sets it on the approved resource")

ErrSubmissionAllowInternalHost refuses a submission whose payload sets the "Allow internal host" switch: it is an administrator's, set on the asset after approval, which always creates the asset with it off (w4e).

View Source
var ErrSubmissionReference = errors.New("submissions may not contain $SECRET/ or $ENV/ references")

ErrSubmissionReference refuses a submission whose payload holds a $SECRET/ or $ENV/ reference.

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 ErrWorkspaceNotFound = models.ErrWorkspaceNotFound

ErrWorkspaceNotFound is returned when a Workspace id names no Workspace. It is the models (wsstamp) sentinel, so the stamped models' create hooks and this package report the same error.

GuardrailOutcomeTopics are the outcome event topics, sorted.

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.

View Source
var PluginScopeInterceptorsFunc func(*Service) (grpc.UnaryServerInterceptor, grpc.StreamServerInterceptor)

PluginScopeInterceptorsFunc builds the interceptors that check a plugin's approved service scopes on the management service. It is set by the services/grpc package (which owns the method-to-scope map) to avoid an import cycle.

Functions

func AssignedCatalogueIDs added in v2.3.0

func AssignedCatalogueIDs(assigned models.JSONMap) []uint

AssignedCatalogueIDs is the catalogue ids an approval's assigned_catalogues names, normalised as approval reads them, so a caller can authorise exactly what approval will write.

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 DefaultSecretNameBlocked added in v2.3.0

func DefaultSecretNameBlocked(db *gorm.DB) func(name string) (bool, error)

DefaultSecretNameBlocked reports whether a default secret (seeded at boot in the Default Workspace) must not be recreated under name: an object outside the Default references the name, and would resolve the new secret. It logs a warning when it blocks. For secrets.GetOrCreateDefaultSecrets.

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 EscapeMarkdown added in v2.3.0

func EscapeMarkdown(s string) string

EscapeMarkdown backslash-escapes the markdown metacharacters of a value written into notification markdown (a user's justification, an app's name), so it reads as the text it is: no link, image, emphasis or HTML. The stored value is unchanged; stripMarkup removes the backslashes again from the in-app record.

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 GuardrailAlertTopics added in v2.3.0

func GuardrailAlertTopics(db *gorm.DB) ([]string, error)

GuardrailAlertTopics lists the guardrail topics a webhook can subscribe to, sorted: the bus topic of every configured guardrail alert (guardrail.alert.<event>, from guardrail filters and exceptions) and the fixed outcome event topics (GuardrailOutcomeTopics). The webhook target editor offers them (Enterprise ListTopics).

func LockWorkspaceForInsert added in v2.3.0

func LockWorkspaceForInsert(tx *gorm.DB, id uint) error

LockWorkspaceForInsert checks, inside tx, that the Workspace exists and holds it until tx ends (FOR SHARE on Postgres; SQLite serializes writes), so an object or binding created in tx can never land in a Workspace that a concurrent delete (on any replica) is removing. Call it in the same transaction as the insert. ErrWorkspaceNotFound when it does not exist.

func NewSecretReferences added in v2.3.0

func NewSecretReferences(old, updated map[string]interface{}) []string

NewSecretReferences lists the keys of updated whose value is a secret reference that old does not already hold under the same key. Writing those needs the right to read secrets, since the plugin receives their values.

func PendingChangeIsForeign added in v2.3.0

func PendingChangeIsForeign(typ string, changeWorkspaceID *uint, workspaceID uint) bool

PendingChangeIsForeign reports whether a pending change is foreign to a push limited to workspaceID: a change on a stamped type owned by another Workspace, or on any unstamped type (plugin, model_price: global configuration). OAuth clients and access tokens never are. An unknown type is foreign (fail closed).

func PendingStampedTypes added in v2.3.0

func PendingStampedTypes() []string

PendingStampedTypes lists the pending-change types that report an owning Workspace.

func PluginBaseResource

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

PluginBaseResource builds the catalogue entry for a plugin.

func PluginBinaryChanged added in v2.3.0

func PluginBinaryChanged(commandBefore, ociReferenceBefore string, plugin *models.Plugin) bool

PluginBinaryChanged reports whether plugin now names another binary than the command and OCI reference it had.

func PluginBrokerServerOptions added in v2.3.0

func PluginBrokerServerOptions(opts []grpc.ServerOption, pluginID uint, svc *Service) []grpc.ServerOption

PluginBrokerServerOptions adds to opts the interceptors every brokered server that serves plugin pluginID must have: the plugin ID in the context (unary and streaming), then the scope check for management RPCs. Without the scope check registered, management RPCs are refused rather than served unchecked. It also sets the message limit to pluginlimits.HostServiceMaxMsgBytes.

func PluginRunsInStudio added in v2.3.0

func PluginRunsInStudio(plugin *models.Plugin) bool

PluginRunsInStudio reports whether Studio itself runs plugin (a UI, an agent, object hooks), as opposed to a gateway-only 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 PromptTemplateLimits added in v2.3.0

func PromptTemplateLimits() templates.Limits

PromptTemplateLimits are the template length rules of this Studio: PROMPT_TEMPLATE_MIN_ANCHORED_CONST_BYTES (AppConf.PromptTemplateMinAnchoredConstBytes) sets the shortest constant at an anchored edge.

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 RestoreSecretReferences added in v2.3.0

func RestoreSecretReferences(old, updated map[string]interface{}) map[string]interface{}

RestoreSecretReferences returns updated with the references from old put back where a plugin wrote the resolved value of the reference it was given: a plugin that saves its in-memory config must not turn a reference into a stored plaintext secret.

func RuntimeGuardrailException added in v2.3.0

func RuntimeGuardrailException(r models.GuardrailException) guardrails.Exception

RuntimeGuardrailException is the runtime view of a stored exception.

func ServiceAccountEmail added in v2.3.0

func ServiceAccountEmail(name string) (string, error)

ServiceAccountEmail generates the address a service account is created with: svc-<name slug>-<random>@service-account.invalid. It is never deliverable and never matches an identity provider's user.

func SetBrandingStoragePath

func SetBrandingStoragePath(path string)

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

func SetEdgeCredentialHasher added in v2.3.0

func SetEdgeCredentialHasher(encryptionKey string)

SetEdgeCredentialHasher sets the hasher from MICROGATEWAY_ENCRYPTION_KEY (pkg/studio calls it at start). A key that cannot make hashes leaves credential.changed events off.

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 UpdateHostCheckExemption added in v2.3.0

func UpdateHostCheckExemption(allowInternalHost bool, stored, command string) netguard.Exemption

UpdateHostCheckExemption is the exemption a plugin update checks command's hosts with. A command left as stored was accepted when it was saved, so its hosts are not checked again: turning the "Allow internal host" switch off must save, and the plugin is then refused when it is loaded or dialled (fail closed), not at the edit (w4e.5). A new command is checked with the switch as it will be stored.

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.

func ValidateToolOASSpec added in v2.3.0

func ValidateToolOASSpec(toolType, spec string) error

ValidateToolOASSpec checks that a tool's oas_spec is base64 of an OpenAPI 3 document the tool client accepts (version 3.x, a servers entry, a supported auth scheme when schemes are declared). It applies the same parse the tool uses at call time and in ListToolOperationsFromSpec, so a stored tool can always list its operations. CLIENT tools keep a client tool definition in the field instead, and an empty spec is allowed.

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(pluginID uint) (uint32, error)

SetupServiceBroker serves AI Studio services to plugin pluginID on a fresh broker ID for one call (an agent session): its calls carry that ID and are checked against its approved scopes. The server is stopped once the plugin can no longer connect to it, unless it did (startCallBroker).

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) SetSourcePolicy added in v2.3.0

func (h *AIStudioPluginManager) SetSourcePolicy(policy plugin_security.SourcePolicy)

SetSourcePolicy sets the plugin source policy, overriding the configured one.

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 WithAppTracing added in v2.3.0

func WithAppTracing(t models.AppTracingSettings) AppOption

WithAppTracing sets the App's agent tracing overrides. Without it a new App inherits every global setting and an update keeps the stored ones.

func WithAppWorkspace added in v2.3.0

func WithAppWorkspace(workspaceID uint) AppOption

WithAppWorkspace lands a new App in the Workspace (Enterprise Workspaces, the API's landing rule). It has no effect on an update: a move is the API's explicit workspace_id change.

func WithCapabilityActor added in v2.3.0

func WithCapabilityActor(userID uint, fullAdmin bool) AppOption

WithCapabilityActor names who changes an App's resources: a full administrator's change keeps the attested guardrail capability; anyone else's clears it.

func WithModelRouters

func WithModelRouters(ids []uint) AppOption

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

func WithSelfService added in v2.3.0

func WithSelfService() AppOption

WithSelfService marks an App create as self-service (portal, plugin SDK), which the entitlements service also holds to the per-user App quota. Administrator creates leave it out.

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 CapabilitySuggestion added in v2.3.0

type CapabilitySuggestion struct {
	Suggestion guardrails.Capability `json:"suggestion"`
	// Reasons explain the suggestion. For acting they name each tool
	// operation or MCP primitive that can act; otherwise what was seen.
	Reasons []string `json:"reasons"`
}

CapabilitySuggestion is Studio's suggested capability for an app and why.

func SuggestAppCapability added in v2.3.0

func SuggestAppCapability(app *models.App, pluginResources ...models.AppPluginResource) CapabilitySuggestion

SuggestAppCapability suggests a capability from the app's tools, MCP servers and datasources (load the app with App.Get, which preloads them):

  • read_only when it has none of them (nor plugin resources);
  • read_tools when every tool operation the app can call is read-only (GET/HEAD/OPTIONS, or x-mcp-read-only: true on the operation), every MCP tool primitive is marked readOnlyHint, and datasources (retrieval) are read-only by nature;
  • acting otherwise, including whatever Studio cannot tell (a spec it cannot parse, an MCP server whose primitives are not known).

Plugin resources bound to the App (pluginResources; load them with GetAppPluginResources, with their PluginResourceType) are something Studio cannot classify, so any binding makes it acting.

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"`
	// AllowInternalHost: the admin-only "Allow internal host" switch.
	AllowInternalHost bool `json:"allow_internal_host"`
}

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
	// AllowInternalHost is the admin-only "Allow internal host" switch: the
	// plugin's own hosts (OCI registry, grpc:// host) may be internal. The
	// API refuses it from a non-admin.
	AllowInternalHost bool `json:"allow_internal_host"`
}

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 counts every dependent, including Hidden ones.
	Total int `json:"total"`
	// Hidden counts the dependents left out of the lists because the caller
	// may not see them (Workspace-scoped objects in other Workspaces); only
	// the count is given, never their ids or names.
	Hidden int `json:"hidden"`
}

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
	// WorkspaceID is the Workspace a new filter lands in (create only; the
	// API's landing rule decides it). 0 is the Default.
	WorkspaceID uint
}

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 GuardrailAlertEvent added in v2.3.0

type GuardrailAlertEvent struct {
	ObjectType string                `json:"object_type"`
	Action     string                `json:"action"`
	ObjectID   uint                  `json:"object_id"`
	Timestamp  string                `json:"timestamp"`
	Object     GuardrailAlertPayload `json:"object"`
}

GuardrailAlertEvent is the bus event a guardrail alert is raised as: shaped like an object event (ObjectEventPayload), with the alert as its object (the compliance event is its id), so the webhook presets render it as they render any event.

type GuardrailAlertPayload added in v2.3.0

type GuardrailAlertPayload struct {
	// Name is the alert's name too, under the key the webhook presets show
	// for an object.
	Name              string   `json:"name"`
	Alert             string   `json:"alert"`
	Topic             string   `json:"topic"`
	FilterID          uint     `json:"filter_id"`
	FilterName        string   `json:"filter_name"`
	AppID             uint     `json:"app_id"`
	AppName           string   `json:"app_name,omitempty"`
	Detector          string   `json:"detector,omitempty"`
	Kinds             []string `json:"kinds,omitempty"`
	Roles             []string `json:"roles,omitempty"`
	ToolNames         []string `json:"tool_names,omitempty"`
	MaxScore          float64  `json:"max_score"`
	Action            string   `json:"action"`
	ExceptionID       uint     `json:"exception_id,omitempty"`
	RequestID         string   `json:"request_id,omitempty"`
	ComplianceEventID uint     `json:"compliance_event_id"`
	Timestamp         string   `json:"timestamp"`
	Link              string   `json:"link"`
	// URL is Link made absolute with SITE_URL, for a message read outside
	// AI Studio (a Slack post links to it); empty when SITE_URL is not set.
	URL      string   `json:"url,omitempty"`
	Excerpts []string `json:"excerpts,omitempty"`
}

GuardrailAlertPayload is what a guardrail alert carries. It never carries the flagged text, except masked excerpts when the filter's alert opts in (include_excerpt, which needs evidence.excerpt); an exception's alert never does.

type GuardrailExceptionActor added in v2.3.0

type GuardrailExceptionActor struct {
	UserID    uint
	FullAdmin bool
}

GuardrailExceptionActor is who creates or changes an exception. A full administrator's change is approved as it is made.

type GuardrailExceptionHits added in v2.3.0

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

GuardrailExceptionHits counts the hits of exceptions and writes them in batches, off the request path: a hit is counted in memory and an exception's pending count is written at most once per guardrailExceptionHitFlushEvery: the first hit at once, the ones after it when the interval has passed (by a timer, or Flush).

func NewGuardrailExceptionHits added in v2.3.0

func NewGuardrailExceptionHits(db *gorm.DB) *GuardrailExceptionHits

NewGuardrailExceptionHits builds a recorder writing to db.

func (*GuardrailExceptionHits) Flush added in v2.3.0

func (h *GuardrailExceptionHits) Flush()

Flush writes every pending count now (at shutdown, or from a periodic sweep, so trailing hits are not held until the next one).

func (*GuardrailExceptionHits) Hit added in v2.3.0

func (h *GuardrailExceptionHits) Hit(id uint, n int64)

Hit records n hits of the exception (edges report counts in batches).

type GuardrailExceptionSource added in v2.3.0

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

GuardrailExceptionSource serves an app's approved exceptions and its capability to the request guardrails (scripting.SetExceptionSource), cached per app, and records their hits.

func (*GuardrailExceptionSource) AppCapability added in v2.3.0

AppCapability implements scripting.CapabilitySource: the app's attested capability, whether or not it has exceptions, cached like its exceptions and dropped with them. "" when it cannot be read (acting).

func (*GuardrailExceptionSource) AppExceptions added in v2.3.0

AppExceptions returns the app's approved exceptions, nil when it has none or they cannot be read (the guardrails then apply the filters' actions).

func (*GuardrailExceptionSource) Hit added in v2.3.0

func (p *GuardrailExceptionSource) Hit(id uint)

Hit records that an exception applied to a request.

type GuardrailExceptionSpec added in v2.3.0

type GuardrailExceptionSpec struct {
	FilterID         *uint
	Detector         *string
	Channel          *string
	ToolName         *string
	Action           *string
	AlertEvent       *string
	Justification    *string
	ExpiresAfterDays *int
	SourceEvent      *uint
}

GuardrailExceptionSpec is what an exception is created or changed with. On an update nil fields are left as they are; the filter and the source event cannot change.

type GuardrailOutcomeEvent added in v2.3.0

type GuardrailOutcomeEvent struct {
	ObjectType string                  `json:"object_type"`
	Action     string                  `json:"action"`
	ObjectID   uint                    `json:"object_id"`
	Timestamp  string                  `json:"timestamp"`
	Object     GuardrailOutcomePayload `json:"object"`
}

GuardrailOutcomeEvent is the bus event an outcome is raised as, shaped like an object event (ObjectEventPayload) as alerts are, so the webhook presets render it: object type "guardrail", the outcome as its action.

type GuardrailOutcomeJudge added in v2.3.0

type GuardrailOutcomeJudge struct {
	LLMID         uint   `json:"llm_id,omitempty"`
	Model         string `json:"model,omitempty"`
	PromptVersion string `json:"prompt_version,omitempty"`
	Verdict       string `json:"verdict"`
	Reason        string `json:"reason,omitempty"`
	Coverage      string `json:"coverage,omitempty"`
	SoftenedFrom  string `json:"softened_from"`
	SoftenedTo    string `json:"softened_to"`
	Cached        bool   `json:"cached,omitempty"`
}

GuardrailOutcomeJudge is the LLM judge's opinion that softened a verdict.

type GuardrailOutcomePayload added in v2.3.0

type GuardrailOutcomePayload struct {
	// Name summarises the event (filter, detector, app) under the key the
	// webhook presets show for an object.
	Name              string   `json:"name"`
	Outcome           string   `json:"outcome"`
	Topic             string   `json:"topic"`
	FilterID          uint     `json:"filter_id"`
	FilterName        string   `json:"filter_name"`
	AppID             uint     `json:"app_id"`
	AppName           string   `json:"app_name,omitempty"`
	EventType         string   `json:"event_type"`
	Severity          string   `json:"severity,omitempty"`
	Detector          string   `json:"detector,omitempty"`
	Detectors         []string `json:"detectors,omitempty"`
	Kinds             []string `json:"kinds,omitempty"`
	Roles             []string `json:"roles,omitempty"`
	ToolNames         []string `json:"tool_names,omitempty"`
	MaxScore          float64  `json:"max_score,omitempty"`
	Action            string   `json:"action"`
	ReasonCode        string   `json:"reason_code,omitempty"`
	ExceptionIDs      []uint   `json:"exception_ids,omitempty"`
	RequestID         string   `json:"request_id,omitempty"`
	ComplianceEventID uint     `json:"compliance_event_id"`
	Timestamp         string   `json:"timestamp"`
	Link              string   `json:"link"`
	// URL is Link made absolute with SITE_URL (see GuardrailAlertPayload).
	URL string `json:"url,omitempty"`
	// Judge is the judge's opinion, on judge_softened only.
	Judge *GuardrailOutcomeJudge `json:"judge,omitempty"`
}

GuardrailOutcomePayload is what a guardrail outcome event carries.

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 LLMOption added in v2.3.0

type LLMOption func(*models.LLM) error

LLMOption sets an LLM attribute that CreateLLM, CreateLLMWithNamespace and UpdateLLM take outside their positional parameters. It runs before validation and the before-* object hooks; an error aborts the call. On UpdateLLM an attribute without an option keeps its stored value.

func WithAllowInternalHost added in v2.3.0

func WithAllowInternalHost(allow bool) LLMOption

WithAllowInternalHost sets the LLM's "Allow internal host" switch: its own endpoint may be an internal address (netguard.ExemptionFor). The API lets only an administrator change it.

func WithLLMTracing added in v2.3.0

func WithLLMTracing(contentModeMax string, propagationOptOut bool) LLMOption

WithLLMTracing sets the LLM's agent tracing content mode cap ("" for no cap) and whether traceparent propagation to its upstream is switched off.

func WithPriceMultipliers added in v2.3.0

func WithPriceMultipliers(m models.LLMPriceMultipliers) LLMOption

WithPriceMultipliers sets the LLM's per-tier price multiplier overrides (nil or empty removes them).

func WithVendorWorkspaceID added in v2.3.0

func WithVendorWorkspaceID(id string) LLMOption

WithVendorWorkspaceID pins the vendor workspace the gateway calls the LLM in ("" removes the pin).

func WithWorkspace added in v2.3.0

func WithWorkspace(workspaceID uint) LLMOption

WithWorkspace creates the LLM in the Workspace (the API's landing rule decides which). Creation only: an update never moves an object (.42).

type LLMValidationError added in v2.3.0

type LLMValidationError struct{ Err error }

LLMValidationError is an LLM attribute the caller got wrong (a 400).

func (*LLMValidationError) Error added in v2.3.0

func (e *LLMValidationError) Error() string

func (*LLMValidationError) Unwrap added in v2.3.0

func (e *LLMValidationError) Unwrap() error

type ListOptions

type ListOptions struct {
	Search   string
	Sort     string
	SortDesc bool
	// Filters are extra conditions from the API layer (the Workspace list
	// filters), applied before search and sort.
	Filters []func(*gorm.DB) *gorm.DB
}

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
	// AccountType: nil any; otherwise "" (people) or "service".
	AccountType *string
}

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) SetSourcePolicy added in v2.3.0

func (h *MarketplaceService) SetSourcePolicy(policy plugin_security.SourcePolicy)

SetSourcePolicy sets the plugin source policy, overriding the configured one.

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 ModelPriceExistsError added in v2.3.0

type ModelPriceExistsError struct {
	ID        uint
	ModelName string
	Vendor    string
}

ModelPriceExistsError is returned when creating a price for a model and vendor that already have a priced row.

func (*ModelPriceExistsError) Error added in v2.3.0

func (e *ModelPriceExistsError) Error() string

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, onlyWorkspaceID ...uint) (*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, onlyWorkspaceID ...uint) (*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, onlyWorkspaceID ...uint) (*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. onlyWorkspaceID, when given, is the push precondition (PushOnlyWorkspace).

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 NativeResourceListQuery added in v2.3.0

type NativeResourceListQuery struct {
	LLMID          uint
	AppID          uint
	ResourceType   string
	Limit          int
	AfterVendorID  string
	BeforeVendorID string
}

NativeResourceListQuery selects one page of NativeResourceStore.List. AfterVendorID pages to older rows than that one, BeforeVendorID to newer ones (at most one of the two); a cursor the App does not own is ErrNativeResourceNotFound.

type NativeResourceSnapshot added in v2.3.0

type NativeResourceSnapshot struct {
	State           string
	Snapshot        string
	EndedAt         *time.Time
	ResultsExpireAt *time.Time
}

NativeResourceSnapshot is the vendor's view of a resource.

type NativeResourceStore added in v2.3.0

type NativeResourceStore interface {
	// Create records r. AccountingState must be set (models.NativeAccounting*).
	// A duplicate (LLM, resource type, vendor ID) is ErrNativeResourceExists.
	Create(ctx context.Context, r *models.NativeResource) error
	// GetByOwner returns the row of vendorID if it was created by appID on
	// llmID, else ErrNativeResourceNotFound.
	GetByOwner(ctx context.Context, llmID, appID uint, resourceType, vendorID string) (*models.NativeResource, error)
	// Get returns the row with id, else ErrNativeResourceNotFound.
	Get(ctx context.Context, id uint) (*models.NativeResource, error)
	// List returns an App's rows of one type on one LLM, newest first, one
	// keyset page at a time.
	List(ctx context.Context, q NativeResourceListQuery) ([]models.NativeResource, error)
	// UpdateSnapshot stores the vendor's latest view of the resource.
	UpdateSnapshot(ctx context.Context, id uint, u NativeResourceSnapshot) error
	// SchedulePoll sets when the reconciler next looks at the row, and its
	// count of consecutive failed polls.
	SchedulePoll(ctx context.Context, id uint, next time.Time, failures int) error
	// Due returns up to limit rows the reconciler should look at now:
	// pending rows whose poll time has come (or was never set), and claimed
	// rows whose claim is older than lease.
	Due(ctx context.Context, now time.Time, lease time.Duration, limit int) ([]models.NativeResource, error)
	// Claim takes the accounting claim on the row for token: from pending,
	// or from a claim older than lease. It reports whether this call won.
	// Terminal rows (accounted, unaccountable, lost, none) are never claimed.
	// Claiming again with the token that holds the claim succeeds (and
	// renews it), so a claim retried after an ambiguous error is not lost.
	Claim(ctx context.Context, id uint, token string, now time.Time, lease time.Duration) (bool, error)
	// Release hands a claim held by token back to pending, so it is retried.
	Release(ctx context.Context, id uint, token string) (bool, error)
	// Settle moves a row claimed by token to a terminal state
	// (models.NativeAccountingAccounted, Unaccountable or Lost). It reports
	// false when token no longer holds the claim.
	Settle(ctx context.Context, id uint, token, state string, now time.Time) (bool, error)
	// Delete removes the row (hard delete: the vendor ID can be recorded
	// again).
	Delete(ctx context.Context, id uint) error
	// SweepExpired deletes settled rows whose results expired before
	// before. Unsettled rows stay for the reconciler to mark.
	SweepExpired(ctx context.Context, before time.Time) (int64, error)
}

NativeResourceStore is the node-local ledger of resources created through a native API extension (models.NativeResource). Every accounting transition is one conditional UPDATE (compare and set), so concurrent settlers on any replica or worker agree on a single winner without a read-then-write transaction.

Times are stored in UTC.

func NewNativeResourceStore added in v2.3.0

func NewNativeResourceStore(read, write *gorm.DB) NativeResourceStore

NewNativeResourceStore returns the ledger over read and write (write nil: read). It returns nil when read is nil.

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(ctx context.Context) (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. Cancelling ctx stops it between queries.

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 and Name are left out (Hidden set) for an object the caller cannot
	// see: an App or router in a Workspace their read does not cover.
	ID     uint      `json:"id,omitempty"`   // object id
	Name   string    `json:"name,omitempty"` // display name at the time of the query
	Change string    `json:"change"`         // created | updated | deleted
	At     time.Time `json:"at"`             // when that change happened
	// WorkspaceID is the Workspace that owns the object (a stored 0 reads
	// as the Default workspace); nil for types with no owning Workspace
	// (plugin, model_price, oauth_client, access_token).
	WorkspaceID   *uint  `json:"workspace_id"`
	WorkspaceName string `json:"workspace_name,omitempty"`
	// Hidden marks a change whose object the caller cannot see; its type,
	// kind, time and Workspace id are still reported.
	Hidden bool `json:"hidden,omitempty"`
}

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"`
	// ByWorkspace counts every pending change (not only the listed ones)
	// by owning Workspace; UnattributedTotal counts those with none.
	ByWorkspace       []PendingWorkspaceTotal `json:"by_workspace"`
	UnattributedTotal int                     `json:"unattributed_total"`
	// Set when asked about one Workspace (?workspace_id=): OutsideTotal
	// counts the changes foreign to it (PendingChangeIsForeign) and Stained
	// reports whether there are any, i.e. whether a push limited to that
	// Workspace would carry changes from outside it.
	WorkspaceID  *uint `json:"workspace_id,omitempty"`
	OutsideTotal *int  `json:"outside_total,omitempty"`
	Stained      *bool `json:"stained,omitempty"`
}

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

type PendingWorkspaceTotal added in v2.3.0

type PendingWorkspaceTotal struct {
	WorkspaceID uint   `json:"workspace_id"`
	Name        string `json:"name"`
	Total       int    `json:"total"`
}

PendingWorkspaceTotal counts the changes owned by one Workspace.

type PluginConfigMarkerError added in v2.3.0

type PluginConfigMarkerError struct {
	Path   string
	Reason string
}

PluginConfigMarkerError says a write used the redaction marker where the stored value cannot be kept. Path names the position; it never carries a submitted value.

func (*PluginConfigMarkerError) Error added in v2.3.0

func (e *PluginConfigMarkerError) Error() string

type PluginConfigSecrets added in v2.3.0

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

PluginConfigSecrets classifies the positions of a plugin configuration. The zero value (and nil) classify by key name.

func NewPluginConfigSecrets added in v2.3.0

func NewPluginConfigSecrets(schemaJSON string) *PluginConfigSecrets

NewPluginConfigSecrets builds the classifier for a plugin's configuration schema. An empty or unparseable schema, or one that is not an object, gives the key-name classifier.

func (*PluginConfigSecrets) BySchema added in v2.3.0

func (s *PluginConfigSecrets) BySchema() bool

BySchema reports whether the classifier reads a schema (false: key names).

func (*PluginConfigSecrets) RedactPluginConfig added in v2.3.0

func (s *PluginConfigSecrets) RedactPluginConfig(config map[string]interface{}) map[string]interface{}

RedactPluginConfig returns a copy of config with every secret value replaced by REDACTED_VALUE. config is not modified. A nil config stays nil.

func (*PluginConfigSecrets) RestorePluginConfig added in v2.3.0

func (s *PluginConfigSecrets) RestorePluginConfig(incoming, stored map[string]interface{}) (map[string]interface{}, error)

RestorePluginConfig returns incoming with every REDACTED_VALUE at a secret position replaced by the value stored at the same position, so a form that was loaded with redacted secrets and saved without retyping them keeps them. incoming and stored are not modified.

  • The marker at a secret position with no stored value stores nothing there: the literal marker is never persisted as a credential.
  • The marker anywhere else is refused (PluginConfigMarkerError). Putting it in a readable field must never copy a secret into that field.
  • Inside a list, an entry that contains the marker must equal the redacted form of the stored entry at the same index (and a list of secret strings must keep its length). Otherwise deleting or reordering entries would hand one entry's secret to another.

A nil incoming stays nil.

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) SetSourcePolicy added in v2.3.0

func (h *PluginManifestService) SetSourcePolicy(policy plugin_security.SourcePolicy)

SetSourcePolicy sets the plugin source policy, overriding the configured one.

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) ConfigSecretsForCommands added in v2.3.0

func (s *PluginService) ConfigSecretsForCommands(commands []string) map[string]*PluginConfigSecrets

ConfigSecretsForCommands returns, per plugin command, the classifier of secret configuration fields (see NewPluginConfigSecrets), built from the cached configuration schema of that command. It reads the cache only: a read of a plugin never starts or calls the plugin. A schema whose cache entry was invalidated is still used (the last schema the plugin declared is a better guide than key names). A command without a cached schema is absent from the map; callers then classify by key name.

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) SetSourcePolicy added in v2.3.0

func (h *PluginService) SetSourcePolicy(policy plugin_security.SourcePolicy)

SetSourcePolicy sets the plugin source policy, overriding the configured one.

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 PromptTemplateSource added in v2.3.0

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

PromptTemplateSource serves the approved templates of an app to the request guardrails (scripting.SetPromptTemplateSource), cached per app, and records their matches.

func (*PromptTemplateSource) ApprovedTemplates added in v2.3.0

func (p *PromptTemplateSource) ApprovedTemplates(ctx context.Context, appID uint) []*templates.Template

ApprovedTemplates returns the app's approved templates, nil when it has none or they cannot be read (the guardrails then score everything).

func (*PromptTemplateSource) Matched added in v2.3.0

func (p *PromptTemplateSource) Matched(t *templates.Template)

Matched records that a template matched a request, at most once per promptTemplateTouchEvery per template, off the request path.

type PromptTemplateSpec added in v2.3.0

type PromptTemplateSpec struct {
	Name             string
	Placement        *templates.Placement
	Parts            []templates.Part
	ExpiresAfterDays *int
}

PromptTemplateSpec is what a template is created or changed with. On an update nil fields are left as they are.

type PushStainedError added in v2.3.0

type PushStainedError struct {
	WorkspaceID uint
	Stained     []*PendingChanges
}

PushStainedError says what stains the push: for each stained target namespace, its pending changes (GetPendingChangesFor with the Workspace, so OutsideTotal and PendingChangeIsForeign tell the foreign ones).

func (*PushStainedError) Error added in v2.3.0

func (e *PushStainedError) Error() string

func (*PushStainedError) Unwrap added in v2.3.0

func (e *PushStainedError) 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 SecretHolder added in v2.3.0

type SecretHolder struct {
	Type string `json:"type"`
	ID   uint   `json:"id"`
	Name string `json:"name"`
	// WorkspaceID is the holder's stored workspace_id (0 is the Default).
	WorkspaceID uint `json:"workspace_id"`
}

SecretHolder is an object whose credential field references a secret.

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 SecretReferencedError added in v2.3.0

type SecretReferencedError struct {
	Holders []SecretHolder
	// Outside is true when the holders are outside the new secret's
	// Workspace (a create or rename onto a dangling name).
	Outside bool
}

SecretReferencedError refuses deleting or renaming a secret that objects reference, or taking a name objects outside the secret's Workspace reference.

func (*SecretReferencedError) Error added in v2.3.0

func (e *SecretReferencedError) Error() string

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
	// PluginSecurityService verifies OCI plugin signatures; every OCI client
	// gets it (NewOCIPluginClient). Nil when OCI is not configured.
	PluginSecurityService plugin_security.Service
	// 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
	// Workspaces management (ENT; CE: 402 stub). Use WorkspacesService(),
	// which also covers hand-built Services.
	Workspaces workspaces.Service
	// Entitlements applies license limits and App quotas (ENT); the CE stub
	// allows everything. Use EntitlementsService(), which also covers
	// hand-built Services.
	Entitlements entitlements.Service
	// Webhooks (Enterprise; set by InitWebhooks once the event bus is wired)
	Webhooks webhooks.Service
	// AgentTracing is Agent Call Tracing (Enterprise; set by InitAgentTracing)
	AgentTracing agenttracing.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, opts ...AppOption) error

AddDatasourceToApp adds a datasource to an app. Unless opts name a full administrator (WithCapabilityActor), it clears an attested guardrail capability.

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, opts ...AppOption) (*models.App, error)

AddToolToApp adds a tool to an app. Unless opts name a full administrator (WithCapabilityActor), it clears an attested guardrail capability; the returned App's GuardrailCapabilityReset says so.

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) ApproveAppPromptTemplate added in v2.3.0

func (s *Service) ApproveAppPromptTemplate(appID, id, adminID uint, contentHash string) (*models.AppPromptTemplate, error)

ApproveAppPromptTemplate approves a proposed version. contentHash is the models.AppPromptTemplate.ContentHash of the version the administrator reviewed: a proposed version changes in place, so an approval of anything else is refused (ErrPromptTemplateChanged), and one without it is invalid. The row saved is the one whose hash was checked, so the approved bytes are the reviewed bytes. The other approved versions of the same name are retired: one version of a name is trusted at a time. An app has at most templates.MaxApprovedPerApp approved.

func (*Service) ApproveGuardrailException added in v2.3.0

func (s *Service) ApproveGuardrailException(appID, id, adminID uint, contentHash string) (*models.GuardrailException, error)

ApproveGuardrailException approves a proposed exception. contentHash is the models.GuardrailException.ContentHash of the exception the administrator reviewed: an approval of anything else is refused (ErrGuardrailExceptionChanged), and one without it is invalid. The floor is checked again against the app's capability now. An app has at most models.MaxApprovedGuardrailExceptionsPerApp approved.

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) ApprovedAppPromptTemplates added in v2.3.0

func (s *Service) ApprovedAppPromptTemplates(appID uint) ([]*templates.Template, error)

ApprovedAppPromptTemplates returns the templates the guardrails of an app's requests match against. An approved template that has gone its expires_after_days without a match drops back to proposed here, and is left out.

func (*Service) ApprovedGuardrailExceptions added in v2.3.0

func (s *Service) ApprovedGuardrailExceptions(appID uint) ([]models.GuardrailException, guardrails.Capability, error)

ApprovedGuardrailExceptions returns the app's approved exceptions and its guardrail capability, for the runtime. An approved exception that has gone its expires_after_days without a hit drops back to proposed here and is left out. One outside the floor for the app's current capability is returned: the runtime ignores it and records that it did (guardrail.exception_ignored); it stays approved, so attesting the capability back restores it.

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) BackfillUnpricedHistory added in v2.3.0

func (s *Service) BackfillUnpricedHistory(id uint, from, to *time.Time) (int64, error)

BackfillUnpricedHistory prices the history a model price row never priced: the chat records it prices (see chatRecordsPricedBySQL) that were recorded at no cost, optionally only those with a time stamp in [from, to). Each is priced at the row's current price and multiplier, and takes its currency. Rows with a cost are left alone (PATCH /model-prices/:id/recalculate reprices them). It returns the number of rows priced.

func (*Service) BrandingFavicon added in v2.3.0

func (s *Service) BrandingFavicon() (*models.BrandingAsset, error)

BrandingFavicon returns the uploaded favicon, or nil when there is none.

func (s *Service) BrandingLogo() (*models.BrandingAsset, error)

BrandingLogo returns the uploaded logo, or nil when there is none.

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) CallToolOperationContext added in v2.3.0

func (s *Service) CallToolOperationContext(ctx context.Context, toolID uint, operationID string, params map[string][]string, payload map[string]interface{}, headers map[string][]string) (interface{}, error)

CallToolOperationContext is CallToolOperation bound to ctx: the upstream call is cancelled with its caller and carries the caller's trace context.

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) CheckLLMBudget added in v2.3.0

func (s *Service) CheckLLMBudget(llm *models.LLM) error

CheckLLMBudget reports whether llm's own monthly budget allows another call, for calls the gateway makes on its own account rather than an App's (a guardrail's judge): the LLM half of the proxy's budget check. No budget service (Community Edition) enforces nothing.

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) CloneDatasourceWithDB added in v2.3.0

func (s *Service) CloneDatasourceWithDB(db *gorm.DB, sourceDatasourceID uint) (*models.Datasource, error)

CloneDatasourceWithDB is CloneDatasource creating the copy on db (a transaction, or a connection carrying the Workspace the copy lands in).

func (*Service) CountApps

func (s *Service) CountApps(scopes ...func(*gorm.DB) *gorm.DB) (int64, error)

CountApps returns the total number of apps

func (*Service) CountAppsByUserID

func (s *Service) CountAppsByUserID(userID uint, scopes ...func(*gorm.DB) *gorm.DB) (int64, error)

CountAppsByUserID returns the total number of apps for a specific user

func (*Service) CountUnpricedHistory added in v2.3.0

func (s *Service) CountUnpricedHistory(prices models.ModelPrices) (map[uint]int64, error)

CountUnpricedHistory returns, for each of the given model price rows, the number of chat records it prices that were recorded at no cost (what BackfillUnpricedHistory would price). Rows with none are left out. It applies chatRecordsPricedBySQL's rule to one grouped scan of the unpriced records, rather than a scan per price row.

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) CreateAppPromptTemplate added in v2.3.0

func (s *Service) CreateAppPromptTemplate(appID, userID uint, spec PromptTemplateSpec) (*models.AppPromptTemplate, error)

CreateAppPromptTemplate proposes a template: version 1 of a new name, or the next version of an existing one.

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, workspaceID ...uint) (*models.Catalogue, error)

workspaceID, when given, is the Workspace the catalogue lands in (the API's landing rule); otherwise it lands in the Default workspace.

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, workspaceID ...uint) (*models.DataCatalogue, error)

workspaceID, when given, is the Workspace the catalogue lands in (the API's landing rule); otherwise it lands in the Default workspace.

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, workspaceID ...uint) (*models.FileStore, error)

CreateFileStore creates a new filestore entry with validity checks workspaceID, when given, is the Workspace the entry lands in (0 or omitted: the Default).

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) CreateGuardrailException added in v2.3.0

func (s *Service) CreateGuardrailException(appID uint, actor GuardrailExceptionActor, spec GuardrailExceptionSpec) (*models.GuardrailException, error)

CreateGuardrailException proposes an exception for an app, or creates it approved when the actor is a full administrator (recorded as both proposer and approver). A proposal notifies the administrators.

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, opts ...LLMOption) (*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, opts ...LLMOption) (*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; see CreateOrFillModelPrice.

func (*Service) CreateMultipleModelPrices

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

CreateMultipleModelPrices creates multiple model prices at once

func (*Service) CreateOrFillModelPrice added in v2.3.0

func (s *Service) CreateOrFillModelPrice(modelName, vendor string, cpt, cpit, cacheWritePT, cacheReadPT float64, currency string) (modelPrice *models.ModelPrice, filled bool, err error)

CreateOrFillModelPrice creates a model price. Traffic auto-creates an unpriced (all zero) row for every model it sees, so when the model and vendor already have one, it is filled in instead (filled is true). When they have a priced row, it returns a *ModelPriceExistsError naming it.

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) CreateSecret added in v2.3.0

func (s *Service) CreateSecret(secret *secrets.Secret) error

CreateSecret creates secret (secrets.CreateSecret: the value is encrypted) once its name is free (claimSecretName), in one transaction.

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, workspaceID ...uint) (*models.ToolCatalogue, error)

workspaceID, when given, is the Workspace the catalogue lands in (the API's landing rule); otherwise it lands in the Default workspace.

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) DefaultWorkspaceID added in v2.3.0

func (s *Service) DefaultWorkspaceID() (uint, error)

DefaultWorkspaceID returns the id of the Default workspace, loaded once per process. The Default is created at start-up under the migration lock and can never be deleted or replaced, so the id never changes and every replica reads the same value. A failed load is not cached.

func (*Service) DeleteApp

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

DeleteApp deletes an app

func (*Service) DeleteAppPromptTemplate added in v2.3.0

func (s *Service) DeleteAppPromptTemplate(appID, id uint) error

DeleteAppPromptTemplate removes a template version, whatever its status: the guardrails then score the text it covered.

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. The edges' hash is of the secret: it is taken from the row in the transaction that deletes it.

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) DeleteGuardrailException added in v2.3.0

func (s *Service) DeleteGuardrailException(appID, id uint) error

DeleteGuardrailException removes an exception, whatever its status.

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) DeleteSecret added in v2.3.0

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

DeleteSecret deletes the secret with id once nothing references its name. A missing secret is not an error (as secrets.DeleteSecretByID).

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) EntitlementsService added in v2.3.0

func (s *Service) EntitlementsService() entitlements.Service

EntitlementsService returns the entitlements service, building the edition-appropriate one when the Service was constructed by hand (tests).

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(scopes ...func(*gorm.DB) *gorm.DB) (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, scopes ...func(*gorm.DB) *gorm.DB) (models.Credentials, int64, int, error)

GetAllCredentials retrieves all credentials scopes narrow the list (the API's parent-App visibility); counts and pages follow them.

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, scopes ...func(*gorm.DB) *gorm.DB) ([]models.FileStore, int64, int, error)

GetAllFileStores retrieves all filestore entries with pagination scopes narrow the list (the API's Workspace filter).

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, scopes ...func(*gorm.DB) *gorm.DB) (*models.App, error)

GetAppByName retrieves an app by its name scopes narrow the lookup (the API's Workspace scope).

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) GetAppPromptTemplate added in v2.3.0

func (s *Service) GetAppPromptTemplate(appID, id uint) (*models.AppPromptTemplate, error)

GetAppPromptTemplate loads one template version of 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, scopes ...func(*gorm.DB) *gorm.DB) ([]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 the vector stores datasources can use in this build. The list must match data_session.AVAILABLE_VECTOR_STORES (the stores the datasource code implements); a test fails if they drift.

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, scopes ...func(*gorm.DB) *gorm.DB) (models.DataCatalogues, error)

func (*Service) GetDataCataloguesByTag

func (s *Service) GetDataCataloguesByTag(tagName string, scopes ...func(*gorm.DB) *gorm.DB) (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, filters ...func(*gorm.DB) *gorm.DB) (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 of a favicon uploaded before assets were stored in the database.

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, scopes ...func(*gorm.DB) *gorm.DB) (models.Catalogues, error)

func (*Service) GetGroupDataCatalogues

func (s *Service) GetGroupDataCatalogues(groupID uint, scopes ...func(*gorm.DB) *gorm.DB) (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, scopes ...func(*gorm.DB) *gorm.DB) (models.ToolCatalogues, int64, int, error)

GetGroupToolCatalogues pages a team's tool catalogues; scopes narrow them before the count (e.g. the caller's Workspaces).

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) GetGuardrailException added in v2.3.0

func (s *Service) GetGuardrailException(appID, id uint) (*models.GuardrailException, error)

GetGuardrailException loads one exception of an app.

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 of a logo uploaded before assets were stored in the database (what ImportBrandingFiles reads).

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. A model without a price row gets an unpriced (all zero) one.

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, filters ...func(*gorm.DB) *gorm.DB) ([]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) GuardrailExceptionHits added in v2.3.0

func (s *Service) GuardrailExceptionHits() *GuardrailExceptionHits

GuardrailExceptionHits returns the service's hit recorder.

func (*Service) GuardrailExceptionSource added in v2.3.0

func (s *Service) GuardrailExceptionSource() *GuardrailExceptionSource

GuardrailExceptionSource returns the service's exception source.

func (*Service) GuardrailsApplyToApp added in v2.3.0

func (s *Service) GuardrailsApplyToApp(appID uint) (bool, error)

GuardrailsApplyToApp reports whether a guardrail filter is attached to at least one of the App's LLMs (in any mode).

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) ImportBrandingFiles added in v2.3.0

func (s *Service) ImportBrandingFiles(basePath string) []string

ImportBrandingFiles copies a logo or favicon uploaded before assets were stored in the database from basePath (BRANDING_STORAGE_PATH) into it. An asset is imported when the settings name a custom one, the database holds none, and its file is on this replica's disk; so it happens once, on the first replica that has the file, and never after a reset. The files are left in place. It returns the kinds imported. Problems with one asset are logged and do not stop the other, or start-up.

func (*Service) InitAgentTracing added in v2.3.0

func (s *Service) InitAgentTracing(ctx context.Context, cfg config.AgentTracingConfig, nodeID, version string)

InitAgentTracing applies the Agent Call Tracing start gate (Enterprise implementation linked in, licence valid, AGENT_TRACING_ENABLED) and starts the service. Call after SetLicensingService. When the gate is closed the result is inert and the gateway's capture flag stays off.

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) InvalidateBrandingAssets added in v2.3.0

func (s *Service) InvalidateBrandingAssets()

InvalidateBrandingAssets drops this replica's in-memory copies of the logo and favicon; the next request reads them from the database. It runs when another replica signals replicas.SignalBranding.

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) ListAppPromptTemplates added in v2.3.0

func (s *Service) ListAppPromptTemplates(appID uint, status string) ([]models.AppPromptTemplate, error)

ListAppPromptTemplates lists an app's template versions; status filters when not empty.

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, scopes ...func(*gorm.DB) *gorm.DB) (models.Apps, int64, int, error)

ListAppsWithPagination returns a paginated list of apps scopes narrow the list (the API's Workspace scope and filter); counts and pages follow them.

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) ListFilterGuardrailExceptions added in v2.3.0

func (s *Service) ListFilterGuardrailExceptions(filterID uint, status string) ([]models.GuardrailException, error)

ListFilterGuardrailExceptions lists a filter's exceptions across apps; status filters when not empty.

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) ListGuardrailExceptions added in v2.3.0

func (s *Service) ListGuardrailExceptions(appID uint, status string) ([]models.GuardrailException, error)

ListGuardrailExceptions lists an app's exceptions; status filters when not empty.

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 (unless Filters are set: those need the query below). 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) NativeResourceStore added in v2.3.0

func (s *Service) NativeResourceStore() NativeResourceStore

NativeResourceStore returns the Studio's native resource ledger, or nil without a database.

func (*Service) NewOCIPluginClient added in v2.3.0

func (s *Service) NewOCIPluginClient(cfg *ociplugins.OCIConfig) (*ociplugins.OCIPluginClient, error)

NewOCIPluginClient creates an OCI plugin client wired to the shared plugin security service, for OCI clients built outside NewServiceWithOCI (the marketplace). Never call ociplugins.NewOCIPluginClient directly in Studio.

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) PromptTemplateSource added in v2.3.0

func (s *Service) PromptTemplateSource() *PromptTemplateSource

PromptTemplateSource returns the service's template source.

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) PublishGuardrailAlerts added in v2.3.0

func (s *Service) PublishGuardrailAlerts(events []*models.ComplianceEvent)

PublishGuardrailAlerts raises the alerts of stored compliance events (analytics.SetComplianceEventsStored). It never panics into the caller, the analytics writer.

func (*Service) PublishGuardrailEvents added in v2.3.0

func (s *Service) PublishGuardrailEvents(events []*models.ComplianceEvent)

PublishGuardrailEvents raises the alerts and outcome events of stored compliance events (analytics.SetComplianceEventsStored). It never panics into the caller, the analytics writer.

func (*Service) PublishGuardrailOutcomes added in v2.3.0

func (s *Service) PublishGuardrailOutcomes(events []*models.ComplianceEvent)

PublishGuardrailOutcomes raises the outcome events of stored compliance events. It never panics into the caller.

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) ReconcilePluginsAfterGap added in v2.3.0

func (s *Service) ReconcilePluginsAfterGap(since time.Time)

ReconcilePluginsAfterGap brings this replica's plugins in line with the database after it may have missed other replicas' plugin changes (it could not read the cluster event log for longer than events are kept). It reads the plugins once. Every plugin changed or deleted since `since` is applied as its change event would have been (ApplyPluginChangeFromReplica); of the others, only those whose running state contradicts the database: running although deleted or deactivated, or not running although Studio loads them at start. A plugin that is as the database says is left running, not restarted. It may take seconds per plugin; call it off the event reader's goroutine.

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, opts ...AppOption) error

RemoveDatasourceFromApp removes a datasource from an app. Unless opts name a full administrator (WithCapabilityActor), it clears an attested guardrail capability.

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, opts ...AppOption) error

RemoveToolFromApp removes a tool from an app. Unless opts name a full administrator (WithCapabilityActor), it clears an attested guardrail capability.

func (*Service) RemoveToolFromAppReportingReset added in v2.3.0

func (s *Service) RemoveToolFromAppReportingReset(appID, toolID uint, opts ...AppOption) (bool, error)

RemoveToolFromAppReportingReset is RemoveToolFromApp, reporting whether it cleared the App's guardrail capability visibly.

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) RequireSecretMovable added in v2.3.0

func (s *Service) RequireSecretMovable(secret *secrets.Secret) error

RequireSecretMovable refuses (ErrSecretDuplicateName) moving a secret whose name another live secret also has (a grandfathered duplicate).

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 and removes the uploaded logo and favicon.

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) RetireAppPromptTemplate added in v2.3.0

func (s *Service) RetireAppPromptTemplate(appID, id uint) (*models.AppPromptTemplate, error)

RetireAppPromptTemplate retires a version: it is kept for the record and never matched again.

func (*Service) RetireGuardrailException added in v2.3.0

func (s *Service) RetireGuardrailException(appID, id uint) (*models.GuardrailException, error)

RetireGuardrailException retires an exception: it is kept for the record and never applies again.

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) RotateLLMResourceSigningSecret added in v2.3.0

func (s *Service) RotateLLMResourceSigningSecret(id uint, grace time.Duration, userID uint) (*models.LLM, error)

RotateLLMResourceSigningSecret gives the LLM a new native API resource signing secret; the old key stays verifiable for grace (0 revokes it). It emits system.llm.updated, which marks edges pending so the new key reaches them with the next configuration push. A concurrent rotation of the same LLM fails with models.ErrResourceSigningConflict.

func (*Service) RunGuardrailExceptionSweeper added in v2.3.0

func (s *Service) RunGuardrailExceptionSweeper(ctx context.Context)

RunGuardrailExceptionSweeper sweeps lapsed exceptions until ctx ends, on the leader replica only (replicas.IsLeader; the sweep is idempotent, so a change of leader between sweeps is harmless).

func (*Service) SearchApps

func (s *Service) SearchApps(searchTerm string, pageSize, pageNumber int, all bool, sort string, scopes ...func(*gorm.DB) *gorm.DB) (models.Apps, int64, int, error)

SearchApps returns apps matching the given search term with pagination

func (*Service) SearchCataloguesByNameStub

func (s *Service) SearchCataloguesByNameStub(stub string, scopes ...func(*gorm.DB) *gorm.DB) (models.Catalogues, error)

SearchCataloguesByNameStub finds catalogues by name; scopes narrow the search (e.g. the caller's Workspaces).

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, scopes ...func(*gorm.DB) *gorm.DB) (models.DataCatalogues, error)

func (*Service) SearchDatasources

func (s *Service) SearchDatasources(query string, filters ...func(*gorm.DB) *gorm.DB) (models.Datasources, error)

func (*Service) SearchFileStores

func (s *Service) SearchFileStores(query string, scopes ...func(*gorm.DB) *gorm.DB) ([]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, scopes ...func(*gorm.DB) *gorm.DB) (models.ToolCatalogues, error)

func (*Service) SearchTools

func (s *Service) SearchTools(query string, filters ...func(*gorm.DB) *gorm.DB) ([]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) SecretHoldersOf added in v2.3.0

func (s *Service) SecretHoldersOf(name string) ([]SecretHolder, error)

SecretHoldersOf lists the live objects whose credential fields reference $SECRET/name: the recorded references (models.SecretReference: LLM key, endpoint and string metadata, tool auth key, datasource API key, embedder key and endpoint, which covers embedders created inline from a datasource) and, scanned directly because they are not recorded, a datasource's connection string and a guardrail filter's connection block.

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) SetAppGuardrailCapability added in v2.3.0

func (s *Service) SetAppGuardrailCapability(appID uint, value string, userID uint) (*models.App, error)

SetAppGuardrailCapability records the capability a full administrator attests for an app ("" clears it back to unattested). Only the column is written. The API restricts it to full administrators.

func (*Service) SetAppMCPServers

func (s *Service) SetAppMCPServers(appID uint, serverIDs []uint, opts ...AppOption) (*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. Unless opts name a full administrator (WithCapabilityActor), a change clears the App's attested guardrail capability; the returned App's GuardrailCapabilityReset says so.

func (*Service) SetAppPluginResources

func (s *Service) SetAppPluginResources(appID, resourceTypeID uint, instanceIDs []string, opts ...AppOption) error

SetAppPluginResources replaces all plugin resource associations for an app and a given resource type. This is a full replace (delete old, insert new). Unless opts name a full administrator (WithCapabilityActor), a change clears the App's attested guardrail capability.

func (*Service) SetAppPluginResourcesReportingReset added in v2.3.0

func (s *Service) SetAppPluginResourcesReportingReset(appID, resourceTypeID uint, instanceIDs []string, opts ...AppOption) (bool, error)

SetAppPluginResourcesReportingReset is SetAppPluginResources, reporting whether it cleared the App's guardrail capability visibly.

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) SetChatRenderImages added in v2.3.0

func (s *Service) SetChatRenderImages(chat *models.Chat, render bool) error

UpdateChat updates an existing chat SetChatRenderImages sets whether the chat UIs render images in the chat's responses ("Render images in responses"; off by default).

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) SetDatasourceAllowInternalHost added in v2.3.0

func (s *Service) SetDatasourceAllowInternalHost(id uint, allow bool) error

SetDatasourceAllowInternalHost sets the datasource's admin-only "Allow internal host" switch (w4e); the caller checks who may.

func (*Service) SetDatasourceTracingContentModeMax added in v2.3.0

func (s *Service) SetDatasourceTracingContentModeMax(id uint, mode string) error

SetDatasourceTracingContentModeMax sets a datasource's agent tracing content mode cap ("" removes it). CreateDatasource and UpdateDatasource take their attributes positionally, so the cap is written on its own: before UpdateDatasource (which reloads and saves the row, so its change event carries the cap) and after CreateDatasource (a new datasource is in no App yet, so no edge depends on it).

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) SuggestAppCapabilityFor added in v2.3.0

func (s *Service) SuggestAppCapabilityFor(app *models.App) (CapabilitySuggestion, error)

SuggestAppCapabilityFor suggests a capability for an App loaded with App.Get, reading its plugin resources too.

func (*Service) SweepLapsedGuardrailExceptions added in v2.3.0

func (s *Service) SweepLapsedGuardrailExceptions(now time.Time) (int, error)

SweepLapsedGuardrailExceptions returns every approved exception past its expiry (expires_after_days without a hit) to proposed and announces the change for each app, so edges become pending and drop it at the next push. ApprovedGuardrailExceptions lapses an app's exceptions when the hub serves its traffic; this covers apps whose traffic goes through edges only, which never ask the hub. It reports how many it lapsed.

func (*Service) SyncAgentTracingLicence added in v2.3.0

func (s *Service) SyncAgentTracingLicence()

SyncAgentTracingLicence keeps capture in step with the Enterprise licence after start-up (jyx.56): capture stops while the licence is not valid and resumes once a renewed one is (no restart). The standalone binaries exit when a periodic re-check fails, so this matters to an embedding host that keeps Studio running (Options.OnLicenceInvalid). Only a service the start gate started is affected; the stored traces and the API stay as they are.

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.

UpdateApp does not change an App's namespace. If that is ever added, the change must raise credential.changed for the App's key (s.appCredentialChanged): edges of the old namespace may hold a cached "valid" answer for it.

func (*Service) UpdateAppPromptTemplate added in v2.3.0

func (s *Service) UpdateAppPromptTemplate(appID, id, userID uint, spec PromptTemplateSpec) (*models.AppPromptTemplate, error)

UpdateAppPromptTemplate changes a template. A proposed version changes in place. A change to the parts or placement of an approved or retired one creates the next version, proposed, and leaves the old one as it was: its bytes were what was approved. Other fields change in place.

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)

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. A regenerated secret replaces the old key at once: edges are told about the old one (as deleted) as well as the new one. The old secret is read and replaced in one transaction, with the row locked on PostgreSQL, so the old key the event names is the one this write replaced.

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) UpdateGuardrailException added in v2.3.0

func (s *Service) UpdateGuardrailException(appID, id uint, actor GuardrailExceptionActor, spec GuardrailExceptionSpec) (*models.GuardrailException, error)

UpdateGuardrailException changes an exception. A retired one cannot change. A change to an approved exception returns it to proposed, unless the actor is a full administrator, whose change stays approved under their name.

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, opts ...LLMOption) (*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) UpdateSecret added in v2.3.0

func (s *Service) UpdateSecret(secret *secrets.Secret, oldName string, ws uint, encryptValue bool) error

UpdateSecret saves secret (secrets.UpdateSecret). When its name changes from oldName, the old name must be unreferenced and the new one free for a secret in Workspace ws (where it is after this update), in the same transaction (locks taken in name order).

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. The favicon is stored in the database (see branding_assets.go).

func (s *Service) UploadLogo(file multipart.File, header *multipart.FileHeader, isAdmin bool) (*models.BrandingSettings, error)

UploadLogo handles logo file upload. The logo is stored in the database (see branding_assets.go).

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).

func (*Service) WorkspaceExists added in v2.3.0

func (s *Service) WorkspaceExists(id uint) (bool, error)

WorkspaceExists reports whether id names a Workspace.

func (*Service) WorkspaceNames added in v2.3.0

func (s *Service) WorkspaceNames(ctx context.Context, ids []uint) map[uint]string

WorkspaceNames returns the names of the given Workspaces, read in one query; ids that name no Workspace are absent. On error it returns what it has (nothing) so callers show ids without names.

func (*Service) WorkspacesService added in v2.3.0

func (s *Service) WorkspacesService() workspaces.Service

WorkspacesService returns the Workspaces service; NewService sets it, and a hand-built Service (tests) gets one on first use.

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
	// WorkspaceID is the Workspace a created datasource, tool or MCP server
	// lands in (resolved by the API); 0 is the Default.
	WorkspaceID uint
}

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) GetPendingChangesFor added in v2.3.0

func (s *SyncStatusService) GetPendingChangesFor(namespace string, workspaceID *uint) (*PendingChanges, error)

GetPendingChangesFor is GetPendingChanges, also reporting, when workspaceID is set, how many changes are foreign to that Workspace (OutsideTotal, Stained): what a push limited to it would carry from outside it. The caller checks that the Workspace exists.

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)

func (*SyncStatusService) WorkspaceExists added in v2.3.0

func (s *SyncStatusService) WorkspaceExists(id uint) (bool, error)

WorkspaceExists reports whether a Workspace with the id exists.

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) EmitAppGuardrailExceptionsChanged added in v2.3.0

func (e *SystemEventEmitter) EmitAppGuardrailExceptionsChanged(appID uint)

EmitAppGuardrailExceptionsChanged emits an event when an App's guardrail exceptions change.

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) EmitAppPromptTemplatesChanged added in v2.3.0

func (e *SystemEventEmitter) EmitAppPromptTemplatesChanged(appID uint)

EmitAppPromptTemplatesChanged emits an event when an App's trusted prompt templates change.

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) EmitSecretChanged added in v2.3.0

func (e *SystemEventEmitter) EmitSecretChanged(topic, action string, objectID uint, userID uint)

EmitSecretChanged emits a secret event (TopicSecretCreated, Updated or Deleted) without the secret itself.

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

func (*SystemEventEmitter) PublishLocal added in v2.3.0

func (e *SystemEventEmitter) PublishLocal(topic string, payload interface{}) error

PublishLocal publishes payload on topic on this node's bus (DirLocal), for events that are not object CRUD (guardrail alerts).

func (*SystemEventEmitter) SetPluginSecrets added in v2.3.0

func (e *SystemEventEmitter) SetPluginSecrets(source func(commands []string) map[string]*PluginConfigSecrets)

SetPluginSecrets sets the source of the plugins' secret-field classifiers used to redact the plugin a plugin event carries.

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
	// TracingContentModeMax caps the agent tracing content mode for the
	// tool; nil or "" is no cap. Validated by the caller.
	TracingContentModeMax *string
	// AllowInternalHost is the admin-only "Allow internal host" switch;
	// the caller checks who sets it. Submissions never do.
	AllowInternalHost 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
	// AllowInternalHost: absent keeps the stored switch (admin-only).
	AllowInternalHost *bool `json:"allow_internal_host"`
}

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
	// AccountType is models.AccountTypeUser or models.AccountTypeService.
	// Set on create; an update that names a different type is refused.
	AccountType string
}

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 agenttracing is the edition seam for Agent Call Tracing (spec: enterprise/features/agenttracing/SPEC.md).
Package agenttracing is the edition seam for Agent Call Tracing (spec: enterprise/features/agenttracing/SPEC.md).
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 entitlements is the hook through which a license limits what a deployment may create: Apps, LLMs, users with admin or portal access, and edge namespaces, plus the per-user App quota of self-service creation.
Package entitlements is the hook through which a license limits what a deployment may create: Apps, LLMs, users with admin or portal access, and edge namespaces, plus the per-user App quota of self-service creation.
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.
Package workspaces manages Workspaces: the ownership boundary of objects (models.Workspace, models.WorkspaceStampedModels).
Package workspaces manages Workspaces: the ownership boundary of objects (models.Workspace, models.WorkspaceStampedModels).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL