luaplugin

package
v0.6.5 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 41 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultHealthCooldown = 5 * time.Minute
	MinHealthCooldown     = time.Minute
	MaxHealthCooldown     = 24 * time.Hour
)

Health-check cooldown bounds for the healthcheck_cooldown registration value. Absent means DefaultHealthCooldown.

View Source
const (
	InitializeReasonInstall = "install"
	InitializeReasonUpdate  = "update"
	InitializeReasonStartup = "startup"
	InitializeReasonEnable  = "enable"
)

Lifecycle hook reasons. initialize runs once per plugin event; ctx carries reason only. deinitialize with reason "disable" for a provider transition additionally carries the disabled provider identity (provider_id plus provider_config); the plugin-disable path reuses "disable" with reason only and no provider identity.

View Source
const (
	DeinitializeReasonDelete   = "delete"
	DeinitializeReasonUpdate   = "update"
	DeinitializeReasonShutdown = "shutdown"
	DeinitializeReasonDisable  = "disable"
)
View Source
const (
	LocaleEnglish = "en"
	LocaleRussian = "ru"
)

Supported widget locales. English is the fallback for missing keys.

Variables

View Source
var (
	// ErrUnsupportedLuaType marks functions, userdata and threads.
	ErrUnsupportedLuaType = errors.New("luaplugin: unsupported lua value type")
	// ErrNonStringKey marks tables keyed by non-strings in object position.
	ErrNonStringKey = errors.New("luaplugin: non-string table key")
	// ErrMixedTable marks tables mixing array and object parts.
	ErrMixedTable = errors.New("luaplugin: mixed array/object table")
	// ErrSparseArray marks array tables with holes in 1..n.
	ErrSparseArray = errors.New("luaplugin: sparse array table")
)

Conversion sentinels: Lua values that cannot cross into JSON.

View Source
var ErrHandlerNotFound = errors.New("luaplugin: handler not declared")

ErrHandlerNotFound is returned when a plugin does not declare the requested handler. Callers apply the fixed fallback behavior per handler.

View Source
var ErrPluginDisabled = errors.New("luaplugin: plugin is disabled")

ErrPluginDisabled is returned when a type key belongs to an installed but disabled plugin. Disabled plugins stay inventoried; the registry serves enabled types only. Callers map it to provider_disabled, never to a missing-backend outcome.

View Source
var ErrTypeKeyConflict = errors.New("luaplugin: type key already registered by another plugin")

ErrTypeKeyConflict is returned when installing a plugin whose type key is already served by a different plugin. The registry is a single source of truth: one type key maps to exactly one plugin.

View Source
var PluginAPIVersion = version.Version{Major: 1, Minor: 6}

PluginAPIVersion is the plugin API contract served by this router. Format x.y: x breaks, y extends without breaking.

Functions

func AllHandlerNames added in v0.1.2

func AllHandlerNames() []string

AllHandlerNames lists every handler slot, required first.

func BuildID

func BuildID(origin PluginOrigin, manifest *Manifest) (string, error)

BuildID derives the composite plugin ID from origin and manifest. Repo installs use the file basename: <repo>/<author>/<basename>. Manual uploads use: manual/<author>/<slug-of-plugin-name>.

func CheckPluginAPI added in v0.3.8

func CheckPluginAPI(manifest *Manifest) error

CheckPluginAPI compares the plugin @plugin_api major against the served contract. Minor is informational only. Missing tag reports no_api_version.

func CompareVersions

func CompareVersions(a, b string) (int, error)

CompareVersions compares two MAJOR.MINOR.PATCH versions. Returns -1, 0 or 1 when a is older, equal or newer than b.

func NegotiateLocale added in v0.4.0

func NegotiateLocale(queryValue, acceptLanguage string) string

NegotiateLocale selects the widget locale for one dashboard request. The explicit query value wins so the dashboard language override applies even when it differs from the browser header. The Accept-Language first tag serves as fallback. Empty input resolves to English.

func NormalizeLocale added in v0.4.0

func NormalizeLocale(value string) string

NormalizeLocale maps a raw locale tag to the supported set. Russian tags resolve to ru, everything else resolves to en.

func OptionalHandlerNames added in v0.1.2

func OptionalHandlerNames() []string

OptionalHandlerNames lists every non-required handler slot.

func QualifiedSourceKey added in v0.1.2

func QualifiedSourceKey(recordID, name string) string

QualifiedSourceKey names one plugin's proxy-list source globally: <recordID>/<declared>. Declared names are unique per plugin but not across plugins, so the bare name cannot serve as an identity.

func ResolveUINodes added in v0.4.0

func ResolveUINodes(nodes []*models.UINode, locales PluginLocales, locale string) []*models.UINode

ResolveUINodes returns a copy of nodes with localizable strings resolved for locale. Stored trees stay untouched. Option values stay data; option labels resolve as display text.

Types

type APICompatError added in v0.3.8

type APICompatError struct {
	Reason    string
	RouterAPI version.Version
	PluginAPI version.Version
}

APICompatError reports a plugin API mismatch with a machine-readable Reason for the dashboard toast: "too_new", "too_old", "no_api_version".

func (*APICompatError) Error added in v0.3.8

func (e *APICompatError) Error() string

type CrashEntry

type CrashEntry struct {
	At      time.Time `json:"at"`
	TypeKey string    `json:"type_key"`
	Cause   string    `json:"cause"`
}

CrashEntry is one recorded PluginInternalError.

type Handler added in v0.1.2

type Handler string

Handler names a Lua-callable function slot of llm_router.register. Static schema tables (credential_schema, config_schema, settings_schema, proxy_schema) and colocated job specs are not handlers: they are validated at install, never invoked.

const (
	HandlerInitialize   Handler = "initialize"
	HandlerDeinitialize Handler = "deinitialize"
)

Lifecycle hooks: optional one-time handlers. initialize runs once per plugin event (install, update, router startup); deinitialize runs before plugin removal, replacement, provider disable and router shutdown. Both are optional and run only when the plugin declares them.

const (
	HandlerCompleteStream      Handler = "complete_stream"
	HandlerTranscribe          Handler = "transcribe"
	HandlerSpeech              Handler = "speech"
	HandlerGenerateImage       Handler = "generate_image"
	HandlerEmbed               Handler = "embed"
	HandlerModerate            Handler = "moderate"
	HandlerGenerateVideo       Handler = "generate_video"
	HandlerPollVideo           Handler = "poll_video"
	HandlerVideoContent        Handler = "video_content"
	HandlerValidateCredentials Handler = "validate_credentials"
	HandlerGetModelInfos       Handler = "get_model_infos"
	HandlerCheckHealth         Handler = "check_health"
	HandlerCheckModel          Handler = "check_model"
	HandlerAuthInitiate        Handler = "auth_initiate"
	HandlerAuthStep            Handler = "auth_step"
)

Optional handlers: declared per type, validated as functions when present.

const HandlerComplete Handler = "complete"

Required handler: every registered type serves it.

type HandlerMeta added in v0.1.2

type HandlerMeta struct {
	ProviderID         string
	TypeKey            string
	Credential         *models.Credential
	Model              models.ModelId
	ProviderConfig     map[string]any
	AllowedCredentials []string
	// contains filtered or unexported fields
}

HandlerMeta carries request identity into handler calls: which provider instance and type serve the request, which model was requested, the provider config, and the token allow-list of credential IDs the plugin may use. A nil allow-list means unrestricted (admin probes); virtual fan-out recomputes it per member from the token snapshot in ctx.

type HealthStatus added in v0.3.8

type HealthStatus string

HealthStatus is the verdict of a check_health handler call.

const (
	HealthHealthy   HealthStatus = "healthy"
	HealthUnhealthy HealthStatus = "unhealthy"
	HealthUnknown   HealthStatus = "unknown"
)

Health verdicts: healthy keeps the credential, unhealthy disables it, unknown (and any handler failure) changes nothing.

type HealthTrigger added in v0.3.8

type HealthTrigger interface {
	SuspectFailed(pluginID, typeKey, credentialID string)
}

HealthTrigger receives failed attempt identities for detached health-check dispatch. Implemented by the healthcheck service; kept as an interface here so the call direction never cycles.

type JobSpec added in v0.3.8

type JobSpec struct {
	IntervalSeconds int64 `json:"interval_seconds"`
	RunOnStartup    bool  `json:"run_on_startup"`
	TimeoutMs       int   `json:"timeout_ms"`
}

JobSpec is the validated schedule of one colocated plugin job.

type LogEntry

type LogEntry struct {
	At       time.Time         `json:"at"`
	Severity int               `json:"severity"`
	Message  string            `json:"message"`
	Keys     map[string]string `json:"keys"`
}

LogEntry is one plugin log line read back from the events database.

type Manifest

type Manifest struct {
	Plugin      string
	Author      string
	Version     string
	PluginAPI   string
	Description string
	License     string
	AllowHosts  []string
	// Unsafe is true when the plugin requests a wildcard allow_host.
	Unsafe bool
}

Manifest is the parsed "--- @tag value" header of a plugin file.

func ParseManifest

func ParseManifest(source []byte) (*Manifest, error)

ParseManifest parses the leading "---" header block. The header is the contiguous run of "---"-prefixed lines at the very start of the file.

type ModelHealth added in v0.4.0

type ModelHealth struct {
	Status   ModelStatus
	Message  string
	Response string
}

ModelHealth is the validated check_model verdict.

type ModelStatus added in v0.4.0

type ModelStatus string

ModelStatus is the verdict of a check_model handler call.

const (
	ModelHealthy       ModelStatus = "healthy"
	ModelQuotaExceeded ModelStatus = "quota_exceeded"
	ModelUnhealthy     ModelStatus = "unhealthy"
	ModelUnknown       ModelStatus = "unknown"
)

Model verdicts: healthy keeps serving, quota_exceeded marks temporary exhaustion, unhealthy reports a dead model, unknown changes nothing.

type PluginLocales added in v0.4.0

type PluginLocales map[string]map[string]string

PluginLocales holds per-type widget translations: locale code -> widget key -> localized text.

func ParseLocales added in v0.4.0

func ParseLocales(value lua.LValue, typeKey string) (PluginLocales, error)

ParseLocales validates one registration locales table. A nil value means the type declares no translations.

type PluginOrigin

type PluginOrigin struct {
	RepoID string `json:"repo_id"`
	Path   string `json:"path"`
	Manual bool   `json:"manual"`
}

PluginOrigin describes where a plugin was installed from.

type PluginRecord

type PluginRecord struct {
	ID          string   `json:"id"`
	DisplayName string   `json:"display_name"`
	Author      string   `json:"author"`
	Version     string   `json:"version"`
	PluginAPI   string   `json:"plugin_api_version"`
	Description string   `json:"description"`
	License     string   `json:"license"`
	AllowHosts  []string `json:"allow_hosts"`
	Unsafe      bool     `json:"unsafe"`
	Disabled    bool     `json:"disabled"`
	// ProxySourceKeys lists registered proxy-list feeds in this plugin.
	ProxySourceKeys []string `json:"proxy_source_keys,omitempty"`
	// ModelSpecifications holds per-type pinned model rows from the registration
	// model_specs table, merged over discovered rows in GetModelInfos.
	ModelSpecifications map[string]map[string]models.ModelInfo `json:"model_specs,omitempty"`
	// HealthCooldown holds per-type healthcheck_cooldown values in seconds
	// from the registration table. Absent means DefaultHealthCooldown.
	HealthCooldown map[string]int64 `json:"health_cooldown,omitempty"`
	// Schemas holds per-type static UI tables: credential_schema,
	// config_schema, settings_schema, proxy_schema. A missing table means
	// the surface stays hidden.
	Schemas map[string]map[string][]*models.UINode `json:"schemas,omitempty"`
	// Locales holds per-type widget translations: locale code -> widget
	// key -> localized text. Absent means widgets serve stored text.
	Locales map[string]PluginLocales `json:"locales,omitempty"`
	// Jobs holds per-type colocated job schedules. Function bodies live in
	// plugin source and load fresh on every run.
	Jobs        map[string]map[string]JobSpec `json:"jobs,omitempty"`
	TypeKeys    []string                      `json:"type_keys"`
	Handlers    map[string][]string           `json:"handlers"`
	Icons       map[string]string             `json:"icons"`
	Source      []byte                        `json:"source"`
	History     []PluginVersionSnapshot       `json:"history"`
	Origin      PluginOrigin                  `json:"origin"`
	InstalledAt time.Time                     `json:"installed_at"`
	UpdatedAt   time.Time                     `json:"updated_at"`
}

PluginRecord is the stored plugin row in the plugins table.

type PluginVersionSnapshot

type PluginVersionSnapshot struct {
	Version             string                                 `json:"version"`
	Source              []byte                                 `json:"source"`
	TypeKeys            []string                               `json:"type_keys"`
	Handlers            map[string][]string                    `json:"handlers"`
	Icons               map[string]string                      `json:"icons"`
	ModelSpecifications map[string]map[string]models.ModelInfo `json:"model_specs,omitempty"`
	HealthCooldown      map[string]int64                       `json:"health_cooldown,omitempty"`
	ProxySourceKeys     []string                               `json:"proxy_source_keys,omitempty"`
	Schemas             map[string]map[string][]*models.UINode `json:"schemas,omitempty"`
	Locales             map[string]PluginLocales               `json:"locales,omitempty"`
	Jobs                map[string]map[string]JobSpec          `json:"jobs,omitempty"`
}

PluginVersionSnapshot is one rollback entry.

type Service

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

Service owns the plugin lifecycle, the type key registry and handler calls. Plugin rows live in SQLite; the in-memory registry rebuilds from it after every lifecycle mutation.

func New

func New(sqliteDatabase *db.Database, logger *slog.Logger) (*Service, error)

New constructs a SQLite-backed plugin Service and loads the in-memory registry from the plugin rows. Construction reads storage once so handler lookups never touch the database.

func (*Service) AuthInitiate

func (s *Service) AuthInitiate(goCtx context.Context, typeKey, flowID string, providerConfig map[string]any, locale string) (*models.AuthFlowResult, error)

AuthInitiate calls auth_initiate. Missing handler reports ErrHandlerNotFound so the dashboard uses the single-step credential_schema form. Render trees resolve through the type locales for locale.

func (*Service) AuthStep

func (s *Service) AuthStep(goCtx context.Context, typeKey, flowID, action string, values map[string]any, providerConfig map[string]any, locale string) (*models.AuthFlowResult, error)

AuthStep calls auth_step with {action, values}. Render trees resolve through the type locales for locale.

func (*Service) CheckHealth added in v0.3.8

func (s *Service) CheckHealth(goCtx context.Context, typeKey string, credential *models.Credential) (HealthStatus, string, error)

CheckHealth invokes the check_health handler for one credential and returns its verdict. Missing handler reports ErrHandlerNotFound (the type never health-checks). Invalid verdict shapes become PluginInternalError and change nothing: only an explicit "unhealthy" may disable.

func (*Service) CheckModel added in v0.4.0

func (s *Service) CheckModel(goCtx context.Context, metadata HandlerMeta, endpoint string) (ModelHealth, error)

CheckModel invokes the check_model handler for one model and returns its verdict. Missing handler reports ErrHandlerNotFound (the type never model-checks). Invalid verdict shapes become PluginInternalError and change nothing: only an explicit status maps to a probe outcome.

func (*Service) Complete

func (s *Service) Complete(
	goCtx context.Context,
	handlerMetadata HandlerMeta,
	request *models.ChatCompletionRequest,
) (*models.ChatCompletionResponse, error)

Complete invokes the complete handler and validates the response shape. Proxy retries belong to the higher-level retry engine: one handler call uses one ordered pick list, and transport failover stays inside it.

func (*Service) CompleteRouted added in v0.2.0

func (s *Service) CompleteRouted(
	goCtx context.Context,
	handlerMetadata HandlerMeta,
	request *models.ChatCompletionRequest,
) (*models.ChatCompletionResponse, string, error)

CompleteRouted is Complete plus the redacted proxy host:port of the call ("" = direct).

func (*Service) CompleteStream

func (s *Service) CompleteStream(
	goCtx context.Context,
	handlerMetadata HandlerMeta,
	request *models.ChatCompletionRequest,
	w io.Writer,
) error

CompleteStream invokes complete_stream with an emit callback. When the plugin does not declare complete_stream, the stream is emulated with a single chunk produced by complete plus [DONE].

func (*Service) CompleteStreamRouted added in v0.2.0

func (s *Service) CompleteStreamRouted(
	goCtx context.Context,
	handlerMetadata HandlerMeta,
	request *models.ChatCompletionRequest,
	w io.Writer,
) (string, error)

CompleteStreamRouted is CompleteStream plus the redacted proxy host:port of the call ("" = direct).

func (*Service) Crashes

func (s *Service) Crashes(pluginID string) []CrashEntry

Crashes returns recent recorded crashes for a plugin, never nil.

func (*Service) CredentialsEnabled added in v0.3.8

func (s *Service) CredentialsEnabled(typeKey string) bool

CredentialsEnabled reports whether a type key serves credentials: a credential_schema table or an auth_initiate handler is present.

func (*Service) DeletePluginStorageSQLite added in v0.4.0

func (service *Service) DeletePluginStorageSQLite(ctx context.Context, pluginID string) error

DeletePluginStorageSQLite removes every storage entry for one plugin from both handles in one transaction each. Durable deletes cascade from the base row; this helper serves explicit storage resets plus the cache slice, which references the plugin softly.

func (*Service) DeleteSQLite added in v0.4.0

func (service *Service) DeleteSQLite(ctx context.Context, pluginID string) error

DeleteSQLite removes one plugin row. Allow host, version and durable storage rows cascade from the base delete; TTL storage rows reference the plugin softly from the cache file and clear explicitly after the durable delete succeeds. A zero-row delete reports the not-found sentinel through the WithResult tracker. The registry rebuilds and notifies the removed type keys.

func (*Service) DeleteStorageSQLite added in v0.4.0

func (service *Service) DeleteStorageSQLite(ctx context.Context, pluginID string, scope string, key string) error

DeleteStorageSQLite removes one plugin storage entry from both handles in one transaction each. A miss is not an error, matching the previous delete.

func (*Service) Embed added in v0.0.5

func (s *Service) Embed(
	goCtx context.Context,
	handlerMetadata HandlerMeta,
	request *models.EmbeddingsRequest,
) (*models.EmbeddingsResponse, error)

Embed invokes the embed handler. A missing handler reports ErrHandlerNotFound so the router maps it to a clean "endpoint not supported" error.

func (*Service) EmbedRouted added in v0.2.0

func (s *Service) EmbedRouted(
	goCtx context.Context,
	handlerMetadata HandlerMeta,
	request *models.EmbeddingsRequest,
) (*models.EmbeddingsResponse, string, error)

EmbedRouted is Embed plus the redacted proxy host:port of the call ("" = direct).

func (*Service) FetchProxies

func (s *Service) FetchProxies(goCtx context.Context, sourceKey string) ([]proxypool.Candidate, error)

FetchProxies invokes the fetch_proxies handler of an enabled proxy source plugin. sourceKey is qualified; the owning record is resolved exactly, and the routed call uses the declared name the plugin registered. Disabled sources behave as missing.

func (*Service) GenerateImage added in v0.0.5

func (s *Service) GenerateImage(
	goCtx context.Context,
	handlerMetadata HandlerMeta,
	request *models.ImageGenerationRequest,
) (*models.ImageGenerationResponse, error)

GenerateImage invokes the generate_image handler. A missing handler reports ErrHandlerNotFound so the router maps it to a clean "endpoint not supported" error.

func (*Service) GenerateImageRouted added in v0.2.0

func (s *Service) GenerateImageRouted(
	goCtx context.Context,
	handlerMetadata HandlerMeta,
	request *models.ImageGenerationRequest,
) (*models.ImageGenerationResponse, string, error)

GenerateImageRouted is GenerateImage plus the redacted proxy host:port of the call ("" = direct).

func (*Service) GetModelInfos

func (s *Service) GetModelInfos(
	goCtx context.Context,
	providerID string,
	typeKey string,
	providerConfig map[string]any,
) ([]models.ModelInfo, error)

GetModelInfos calls get_model_infos with the provider config in ctx. The plugin selects its own credential for discovery from the provider's scope: providerID threads into the call so credentials.list() sees the provider's rows. Missing handler reports ErrHandlerNotFound so callers apply the fixed fallback.

func (*Service) GetSQLite added in v0.4.0

func (service *Service) GetSQLite(ctx context.Context, pluginID string) (*PluginRecord, error)

GetSQLite returns one plugin record with hosts and history assembled from the child tables in one transaction. A miss reports the not-found sentinel.

func (*Service) GetStorageSQLite added in v0.4.0

func (service *Service) GetStorageSQLite(ctx context.Context, pluginID string, scope string, key string) (any, error)

GetStorageSQLite returns one plugin storage entry in one transaction per handle. The durable database answers first; the cache answers second with the expiry check. Expired rows read as missing and are removed in the same transaction, matching the previous envelope behavior. A miss returns nil without an error.

func (*Service) HasHandler

func (s *Service) HasHandler(typeKey, handler string) bool

HasHandler reports whether a type key declares a handler.

func (*Service) HealthCooldown added in v0.3.8

func (s *Service) HealthCooldown(typeKey string) time.Duration

HealthCooldown resolves the health-check cooldown for one type key: the per-type registration value when present, DefaultHealthCooldown otherwise. Unknown types fall back to the default: a struggling store never blocks traffic.

func (*Service) Icon

func (s *Service) Icon(typeKey string) string

Icon returns the icon declared by a type key, or empty when none.

func (*Service) InstallSQLite added in v0.4.0

func (service *Service) InstallSQLite(ctx context.Context, source []byte, origin PluginOrigin) (*PluginRecord, error)

InstallSQLite validates plugin source outside the transaction and persists the plugin row plus allow host and version child rows in one transaction. Lua execution stays outside the transaction; the transaction uses its handle only.

func (*Service) Jobs added in v0.3.8

func (s *Service) Jobs(typeKey string) map[string]JobSpec

Jobs returns the stored job schedules for a type key, or nil.

func (*Service) ListSQLite added in v0.4.0

func (service *Service) ListSQLite(ctx context.Context) ([]*PluginRecord, error)

ListSQLite returns every plugin record ordered by identifier with hosts and history assembled per row in one transaction.

func (*Service) Logs

func (s *Service) Logs(ctx context.Context, pluginID string) ([]LogEntry, error)

Logs returns recent plugin log lines from the events database, newest first, capped at 100 rows. It fails when persistence is not wired.

func (*Service) Lookup

func (s *Service) Lookup(typeKey string) (*PluginRecord, error)

Lookup returns the plugin record serving typeKey. Types owned by a disabled plugin fail with ErrPluginDisabled; unknown types fail without the sentinel so callers keep the missing-backend path.

func (*Service) Moderate added in v0.3.8

func (s *Service) Moderate(
	goCtx context.Context,
	handlerMetadata HandlerMeta,
	request *models.ModerationRequest,
) (*models.ModerationResponse, error)

Moderate invokes the moderate handler. A missing handler reports ErrHandlerNotFound so the router maps it to a clean "endpoint not supported" error.

func (*Service) ModerateRouted added in v0.3.8

func (s *Service) ModerateRouted(
	goCtx context.Context,
	handlerMetadata HandlerMeta,
	request *models.ModerationRequest,
) (*models.ModerationResponse, string, error)

ModerateRouted is Moderate plus the redacted proxy host:port of the call ("" = direct).

func (*Service) NotifyProviderDisabled added in v0.4.0

func (s *Service) NotifyProviderDisabled(instance *models.ProviderInstance)

NotifyProviderDisabled fires deinitialize with reason disable for the types served by one provider snapshot. It is the single entry point for provider-disable lifecycle events: the provider service calls it exactly when a provider transitions from enabled to disabled or is deleted while enabled. Lookup misses (built-in Go backends, uninstalled plugins) and types without the slot skip silently. Execution runs detached and never blocks the caller.

func (*Service) PollVideo added in v0.3.8

func (s *Service) PollVideo(
	goCtx context.Context,
	handlerMetadata HandlerMeta,
	model models.ModelId,
	upstreamJobID string,
) (*models.VideoGenerationResponse, error)

PollVideo invokes the poll_video handler for one upstream job ID.

func (*Service) PollVideoRouted added in v0.3.8

func (s *Service) PollVideoRouted(
	goCtx context.Context,
	handlerMetadata HandlerMeta,
	model models.ModelId,
	upstreamJobID string,
) (*models.VideoGenerationResponse, string, error)

PollVideoRouted is PollVideo plus the redacted proxy host:port of the call ("" = direct).

func (*Service) ProxiesEnabled added in v0.3.8

func (s *Service) ProxiesEnabled(typeKey string) bool

ProxiesEnabled reports whether a type key serves proxy settings: a proxy_schema table is present (empty tables enable defaults).

func (*Service) ProxySourceKeys

func (s *Service) ProxySourceKeys() ([]string, error)

ProxySourceKeys lists proxy-list sources registered by enabled plugins, one qualified key per (record, declared name), first-seen order. Reads storage: source-only plugins carry no type key, so the type-keyed in-memory registry never holds them and a registry read would report no sources after every startup. Disabled plugins stay skipped.

func (*Service) PruneExpiredStorageSQLite added in v0.4.0

func (service *Service) PruneExpiredStorageSQLite(ctx context.Context) (int64, error)

PruneExpiredStorageSQLite removes every expired storage entry from the cache handle in one transaction and returns the removed count. The indexed expiry column drives the condition; null expiries live in the durable database and never match.

func (*Service) Registered

func (s *Service) Registered() []string

Registered returns all enabled type keys, sorted.

func (*Service) RollbackSQLite added in v0.4.0

func (service *Service) RollbackSQLite(ctx context.Context, pluginID string) (*PluginRecord, error)

RollbackSQLite restores the most recent previous version. Reads for the Lua fallback happen outside the transaction on the base handle; the single transaction holds the read-modify-write for the plugin row, host replacement, version delete and version insert. The rolled-back-from version returns to history so rollback toggles forward again, matching the previous discipline.

func (*Service) RunDeinitialize added in v0.4.0

func (s *Service) RunDeinitialize(goCtx context.Context, record *PluginRecord, reason, providerID string, providerConfig map[string]any) error

RunDeinitialize runs the deinitialize slot of every declaring type in a plugin record with one reason. providerID and providerConfig travel only for the disable reason; every other reason passes empty values. Calls fan out concurrently; the call waits for all of them. Detach (go) at call sites that must not wait: delete, disable and shutdown paths.

func (*Service) RunInitialize added in v0.4.0

func (s *Service) RunInitialize(goCtx context.Context, record *PluginRecord, reason string) error

RunInitialize runs the initialize slot of every declaring type in a plugin record with one reason. Calls fan out concurrently; the call waits for all of them. Detach (go) at call sites that must not wait: install, update and rollback handlers. Unknown reasons fail closed before any hook runs.

func (*Service) RunJob added in v0.3.8

func (s *Service) RunJob(goCtx context.Context, typeKey, name, reason, providerID string, providerConfig map[string]any) error

RunJob invokes the colocated run function of one job specification. Reason is one of "tick", "startup" or "manual". The job owns its iteration: list credentials, refresh what is stale, persist through credentials.update.

func (*Service) RunShutdownDeinitializers added in v0.4.0

func (s *Service) RunShutdownDeinitializers(goCtx context.Context) error

RunShutdownDeinitializers runs deinitialize with reason shutdown for every enabled plugin type that declares it. Disabled plugins stay skipped: they already ran deinitialize on disable. The caller bounds the whole sweep with its gate context; shutdown proceeds when the gate expires.

func (*Service) RunStartupInitializers added in v0.4.0

func (s *Service) RunStartupInitializers(goCtx context.Context) error

RunStartupInitializers runs initialize with reason startup for every enabled plugin type that declares it. Disabled plugins stay skipped: they left the registry on disable and re-enter on enable. The caller bounds the whole sweep with its gate context (the server startup gate); slow hooks cancel with it.

func (*Service) Schema

func (s *Service) Schema(typeKey, kind, locale string) ([]*models.UINode, error)

Schema serves static UI tables from the stored record: credential_schema, config_schema, settings_schema or proxy_schema. Missing tables report ErrHandlerNotFound so callers hide the surface instead of rendering it. Stored widget keys resolve through the type locales for locale.

func (*Service) Schemas added in v0.3.8

func (s *Service) Schemas(typeKey string) map[string][]*models.UINode

Schemas returns the stored static UI tables for a type key, or nil when the plugin declares none.

func (*Service) SetCredentialAccess added in v0.3.8

func (s *Service) SetCredentialAccess(
	list func(ctx context.Context, providerID string) ([]*models.Credential, error),
	get func(ctx context.Context, id string) (*models.Credential, error),
	update func(ctx context.Context, id string, data map[string]any) error,
)

SetCredentialAccess wires credential list/get (request and job contexts) and update (job contexts only) for plugins.

func (*Service) SetCredentialLifecycle added in v0.3.8

func (s *Service) SetCredentialLifecycle(
	disable func(ctx context.Context, id string, reason string) error,
	enable func(ctx context.Context, id string) error,
	automationOn func(providerID string) bool,
)

SetCredentialLifecycle wires plugin disable/enable writes plus the automation-switch gate for the shared disabled state.

func (*Service) SetCredentialParks added in v0.3.8

func (s *Service) SetCredentialParks(
	park func(ctx context.Context, id string, ttl time.Duration, reason string) error,
	unpark func(ctx context.Context, id string) error,
	parked func(ctx context.Context, id string) (*models.ParkEntry, error),
)

SetCredentialParks wires the unified cooldown park store for plugins.

func (*Service) SetDisabled added in v0.4.0

func (service *Service) SetDisabled(ctx context.Context, pluginID string, disabled bool) (*PluginRecord, error)

SetDisabled flips the operator-owned disabled flag for one plugin row. The flag persists across restarts, reinstalls, and rollbacks; history never versions it. Enabling re-enters the type registry, disabling leaves it. A no-op returns the stored record without lifecycle hooks. Disable fires deinitialize with reason disable; enable fires initialize with reason enable. Both run detached and never block the caller. One transaction holds the read-modify-write on the transaction handle only.

func (*Service) SetHealthTrigger added in v0.3.8

func (s *Service) SetHealthTrigger(trigger HealthTrigger)

SetHealthTrigger wires detached health-check dispatch for failed attempts that carry a credential identity.

func (*Service) SetLogger

func (s *Service) SetLogger(logger *slog.Logger)

SetLogger wires structured logging.

func (*Service) SetMarkDead added in v0.3.8

func (s *Service) SetMarkDead(mark func(url, reason string) bool)

SetMarkDead wires proxy exclusion for structural TLS faults observed by the plugin HTTP client.

func (*Service) SetMinimumLevel added in v0.4.0

func (s *Service) SetMinimumLevel(level slog.Level)

SetMinimumLevel bounds plugin log persistence: severities mapping below the level never reach the events database.

func (*Service) SetOnChanged

func (s *Service) SetOnChanged(callback func(typeKey string))

SetOnChanged registers a callback fired with every affected type key after install/update/rollback/delete/enable/disable.

func (*Service) SetProxyQuery added in v0.3.8

func (s *Service) SetProxyQuery(query func(pool, country string, limit int) ([]models.ProxyView, error))

SetProxyQuery wires the read-only proxy pool query for plugins.

func (*Service) SetProxyRequire added in v0.3.8

func (s *Service) SetProxyRequire(require func(ctx context.Context, request models.ProxyRequire) (models.ProxyRequireResult, error))

SetProxyRequire wires the demand-driven proxy acquisition for plugins.

func (*Service) SetStorageSQLite added in v0.4.0

func (service *Service) SetStorageSQLite(ctx context.Context, pluginID string, scope string, key string, value any, timeToLive time.Duration) error

SetStorageSQLite persists one plugin storage entry in one transaction. Entries with a TTL live in the cache file; durable entries live in the durable database. The write targets the routed handle first, then removes the same key from the other handle, so an interrupted write leaves a duplicate instead of a loss. The composite primary key replaces the NUL-separated bucket string; the value column holds JSON bytes and the indexed expiry column carries the TTL deadline. Validation mirrors the previous backend so plugin-visible shapes stay identical.

func (*Service) Speech added in v0.0.5

func (s *Service) Speech(
	goCtx context.Context,
	handlerMetadata HandlerMeta,
	request *models.SpeechRequest,
) (*models.SpeechResponse, error)

Speech invokes the speech handler. The plugin returns {audio_b64, format}: the JSON return path cannot carry raw bytes, so audio crosses the boundary base64-encoded. A missing handler reports ErrHandlerNotFound so the router maps it to a clean "endpoint not supported" error.

func (*Service) SpeechRouted added in v0.2.0

func (s *Service) SpeechRouted(
	goCtx context.Context,
	handlerMetadata HandlerMeta,
	request *models.SpeechRequest,
) (*models.SpeechResponse, string, error)

SpeechRouted is Speech plus the redacted proxy host:port of the call ("" = direct).

func (*Service) SubmitVideo added in v0.3.8

func (s *Service) SubmitVideo(
	goCtx context.Context,
	handlerMetadata HandlerMeta,
	request *models.VideoGenerationRequest,
) (*models.VideoGenerationResponse, error)

SubmitVideo invokes the generate_video handler. A missing handler reports ErrHandlerNotFound so the router maps it to a clean "endpoint not supported" error.

func (*Service) SubmitVideoRouted added in v0.3.8

func (s *Service) SubmitVideoRouted(
	goCtx context.Context,
	handlerMetadata HandlerMeta,
	request *models.VideoGenerationRequest,
) (*models.VideoGenerationResponse, string, error)

SubmitVideoRouted is SubmitVideo plus the redacted proxy host:port of the call ("" = direct).

func (*Service) Transcribe added in v0.0.5

func (s *Service) Transcribe(
	goCtx context.Context,
	handlerMetadata HandlerMeta,
	request *models.TranscriptionRequest,
) (*models.TranscriptionResponse, error)

Transcribe invokes the transcribe handler. A missing handler reports ErrHandlerNotFound so the router maps it to a clean "endpoint not supported" error.

func (*Service) TranscribeRouted added in v0.2.0

func (s *Service) TranscribeRouted(
	goCtx context.Context,
	handlerMetadata HandlerMeta,
	request *models.TranscriptionRequest,
) (*models.TranscriptionResponse, string, error)

TranscribeRouted is Transcribe plus the redacted proxy host:port of the call ("" = direct).

func (*Service) TypeDisabled added in v0.4.0

func (s *Service) TypeDisabled(typeKey string) bool

TypeDisabled reports whether typeKey belongs to an installed but disabled plugin. Enabled and unknown types report false.

func (*Service) ValidateCredentials

func (s *Service) ValidateCredentials(typeKey string, data map[string]any) (bool, error)

ValidateCredentials calls validate_credentials. Missing handler accepts any data. Returns valid=false with a ProviderError on rejection.

func (*Service) VideoContent added in v0.3.8

func (s *Service) VideoContent(
	goCtx context.Context,
	handlerMetadata HandlerMeta,
	model models.ModelId,
	upstreamJobID string,
	index int,
) (*models.VideoContentResponse, error)

VideoContent invokes the video_content handler for one upstream job ID and asset index. Video bytes cross the boundary base64-encoded like speech audio. A missing handler reports ErrHandlerNotFound.

func (*Service) VideoContentRouted added in v0.3.8

func (s *Service) VideoContentRouted(
	goCtx context.Context,
	handlerMetadata HandlerMeta,
	model models.ModelId,
	upstreamJobID string,
	index int,
) (*models.VideoContentResponse, string, error)

VideoContentRouted is VideoContent plus the redacted proxy host:port of the call ("" = direct).

type StorageKey added in v0.3.8

type StorageKey struct {
	PluginID string
	Scope    string
	Key      string
}

StorageKey identifies one plugin storage entry.

Directories

Path Synopsis
Package statepool holds idle Lua states in per-key buckets.
Package statepool holds idle Lua states in per-key buckets.

Jump to

Keyboard shortcuts

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