luaplugin

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2026 License: MIT Imports: 29 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

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.

Functions

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 CheckRouterVersion

func CheckRouterVersion(manifest *Manifest, current string) error

CheckRouterVersion rejects plugins requiring a newer router.

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.

Types

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 LogEntry

type LogEntry struct {
	At      time.Time `json:"at"`
	Message string    `json:"message"`
}

LogEntry is one print() line captured from a plugin.

type Manifest

type Manifest struct {
	Plugin        string
	Author        string
	Version       string
	RouterVersion string
	Description   string
	License       string
	AllowHosts    []string
	// Unsafe is true when the plugin requests a wildcard allow_host.
	Unsafe bool
	// ProxyLocations is the whitelist of ISO country codes the upstream
	// expects requests to originate from. Empty allows any location.
	ProxyLocations []string
	// ProxyDefaultOption is the default proxy mode for providers registered
	// from this plugin: disabled, auto or manual. Empty means disabled.
	ProxyDefaultOption string
	// ProxySource marks this plugin as a proxy-list source with a
	// fetch_proxies handler instead of a provider backend.
	ProxySource 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 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"`
	RouterVersion string   `json:"router_version"`
	Description   string   `json:"description"`
	License       string   `json:"license"`
	AllowHosts    []string `json:"allow_hosts"`
	Unsafe        bool     `json:"unsafe"`
	// ProxyLocations and ProxyDefaultOption mirror the manifest proxy tags.
	ProxyLocations []string `json:"proxy_locations,omitempty"`
	// ProxyDefaultOption is the default proxy mode for providers registered
	// from this plugin. Empty means disabled.
	ProxyDefaultOption string `json:"proxy_default_option,omitempty"`
	// ProxySourceKeys lists registered proxy-list sources in this plugin.
	ProxySourceKeys []string                `json:"proxy_source_keys,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 BucketPlugins.

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"`
}

PluginVersionSnapshot is one rollback entry.

type ProxyEvent added in v0.0.7

type ProxyEvent struct {
	ProxyID     string
	Provider    string
	RateLimited bool
	ResetsAt    time.Time
	Blocked     bool
	BlockReason string
}

ProxyEvent is a rate-limit or block outcome for a proxy-provider pair.

type ProxyPick added in v0.0.7

type ProxyPick struct {
	ID  string
	URL string
}

ProxyPick is one ordered proxy candidate for a plugin call.

type ProxyResolution

type ProxyResolution struct {
	ProxyID  string
	ProxyURL string
}

ProxyResolution is the resolver result for one plugin call.

type Service

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

Service owns the plugin lifecycle, the type key registry and handler calls.

func New

func New(database *db.DB, logger *slog.Logger) (*Service, error)

New loads all enabled plugins into the in-memory registry.

func (*Service) AuthInitiate

func (s *Service) AuthInitiate(goCtx context.Context, typeKey, flowID string) (*models.AuthFlowResult, error)

AuthInitiate calls auth_initiate. Missing handler reports ErrHandlerNotFound so the dashboard uses the single-step credential_schema form.

func (*Service) AuthStep

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

AuthStep calls auth_step with {action, values}.

func (*Service) Complete

func (s *Service) Complete(
	goCtx context.Context,
	typeKey string,
	cred *models.Credential,
	req *models.ChatCompletionRequest,
	providerConfig map[string]any,
) (*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) CompletePool added in v0.0.6

func (s *Service) CompletePool(
	ctx context.Context,
	typeKey string,
	creds []*models.Credential,
	req *models.ChatCompletionRequest,
	providerConfig map[string]any,
) (*models.ChatCompletionResponse, error)

CompletePool tries the credential pool in order through the complete handler, at most once per credential.

func (*Service) CompleteStream

func (s *Service) CompleteStream(
	goCtx context.Context,
	typeKey string,
	cred *models.Credential,
	req *models.ChatCompletionRequest,
	w io.Writer,
	providerConfig map[string]any,
) 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) CompleteStreamPool added in v0.0.6

func (s *Service) CompleteStreamPool(
	ctx context.Context,
	typeKey string,
	creds []*models.Credential,
	req *models.ChatCompletionRequest,
	w io.Writer,
	providerConfig map[string]any,
) error

CompleteStreamPool tries the credential pool in order through the complete_stream handler, at most once per credential.

func (*Service) Crashes

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

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

func (*Service) DefaultProxyMode added in v0.0.7

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

DefaultProxyMode returns the manifest default proxy mode for typeKey. Empty and unknown values mean disabled.

func (*Service) Delete

func (s *Service) Delete(id string) error

Delete removes a plugin and its storage entries.

func (*Service) Embed added in v0.0.5

func (s *Service) Embed(
	goCtx context.Context,
	typeKey string,
	cred *models.Credential,
	req *models.EmbeddingsRequest,
	providerConfig map[string]any,
) (*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) EmbedPool added in v0.0.6

func (s *Service) EmbedPool(
	ctx context.Context,
	typeKey string,
	creds []*models.Credential,
	req *models.EmbeddingsRequest,
	providerConfig map[string]any,
) (*models.EmbeddingsResponse, error)

EmbedPool tries the credential pool in order through the embed handler, at most once per credential.

func (*Service) FetchProxies

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

FetchProxies invokes the fetch_proxies handler of a proxy source plugin.

func (*Service) GenerateImage added in v0.0.5

func (s *Service) GenerateImage(
	goCtx context.Context,
	typeKey string,
	cred *models.Credential,
	req *models.ImageGenerationRequest,
	providerConfig map[string]any,
) (*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) GenerateImagePool added in v0.0.6

func (s *Service) GenerateImagePool(
	ctx context.Context,
	typeKey string,
	creds []*models.Credential,
	req *models.ImageGenerationRequest,
	providerConfig map[string]any,
) (*models.ImageGenerationResponse, error)

GenerateImagePool tries the credential pool in order through the generate_image handler, at most once per credential.

func (*Service) Get

func (s *Service) Get(id string) (*PluginRecord, error)

Get returns a plugin record by composite ID.

func (*Service) GetModelInfos

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

GetModelInfos calls get_model_infos. Missing handler reports ErrHandlerNotFound so callers apply the fixed fallback.

func (*Service) HasHandler

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

HasHandler reports whether a type key declares a handler.

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

func (s *Service) Install(source []byte, origin PluginOrigin) (*PluginRecord, error)

Install validates source and stores it as a new or updated plugin. An update pushes the previous version onto History for rollback.

func (*Service) List

func (s *Service) List() ([]*PluginRecord, error)

List returns all installed plugin records.

func (*Service) Logs

func (s *Service) Logs(pluginID string) []LogEntry

Logs returns recent print() lines for a plugin, never nil.

func (*Service) Lookup

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

Lookup returns the plugin record serving typeKey.

func (*Service) NeedsRefresh

func (s *Service) NeedsRefresh(typeKey string, cred *models.Credential) (bool, error)

NeedsRefresh calls needs_refresh. Missing handler means not refreshable.

func (*Service) ProxySourceKeys

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

ProxySourceKeys lists proxy-list sources registered by installed plugins.

func (*Service) ProxyWhitelist added in v0.0.7

func (s *Service) ProxyWhitelist(typeKey string) []string

ProxyWhitelist returns the manifest location whitelist for typeKey. Empty means any location is allowed.

func (*Service) RefreshCredential

func (s *Service) RefreshCredential(
	goCtx context.Context,
	typeKey string,
	cred *models.Credential,
) (map[string]any, error)

RefreshCredential calls refresh_credential and returns the new data map. Missing handler reports ErrHandlerNotFound (not refreshable).

func (*Service) Registered

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

Registered returns all enabled type keys, sorted.

func (*Service) Rollback

func (s *Service) Rollback(id string) (*PluginRecord, error)

Rollback restores the most recent previous version. The rolled-back-from version is pushed back onto History, so rollback toggles forward again.

func (*Service) Schema

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

Schema calls config_schema or credential_schema. Missing handler reports ErrHandlerNotFound so the dashboard falls back to raw JSON input.

func (*Service) SetLogger

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

SetLogger wires structured logging.

func (*Service) SetOnChanged

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

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

func (*Service) SetProxyEventReporter added in v0.0.7

func (s *Service) SetProxyEventReporter(fn func(ev ProxyEvent))

SetProxyEventReporter wires proxy-provider pair outcome feedback.

func (*Service) SetProxyResolver

func (s *Service) SetProxyResolver(fn func(ctx context.Context, rec *PluginRecord, providerConfig map[string]any) ([]ProxyPick, error))

SetProxyResolver wires pool-based proxy selection for plugin HTTP calls. Resolution is lazy per request; a non-nil error fails the request loudly (manual mode with no usable proxy pooled, settled pool with none).

func (*Service) SetUsageTracker added in v0.0.6

func (s *Service) SetUsageTracker(t UsageTracker)

SetUsageTracker wires per-credential usage accounting for pool calls. Unset (nil) disables accounting; attempts still run.

func (*Service) Speech added in v0.0.5

func (s *Service) Speech(
	goCtx context.Context,
	typeKey string,
	cred *models.Credential,
	req *models.SpeechRequest,
	providerConfig map[string]any,
) (*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) SpeechPool added in v0.0.6

func (s *Service) SpeechPool(
	ctx context.Context,
	typeKey string,
	creds []*models.Credential,
	req *models.SpeechRequest,
	providerConfig map[string]any,
) (*models.SpeechResponse, error)

SpeechPool tries the credential pool in order through the speech handler, at most once per credential.

func (*Service) Transcribe added in v0.0.5

func (s *Service) Transcribe(
	goCtx context.Context,
	typeKey string,
	cred *models.Credential,
	req *models.TranscriptionRequest,
	providerConfig map[string]any,
) (*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) TranscribePool added in v0.0.6

func (s *Service) TranscribePool(
	ctx context.Context,
	typeKey string,
	creds []*models.Credential,
	req *models.TranscriptionRequest,
	providerConfig map[string]any,
) (*models.TranscriptionResponse, error)

TranscribePool tries the credential pool in order through the transcribe handler, at most once per credential.

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.

type UsageTracker added in v0.0.6

type UsageTracker interface {
	UpdateUsage(id string, success bool) error
	MarkQuotaExceeded(id string, resetAt time.Time) error
}

UsageTracker records per-credential outcomes. It is implemented by the credential pool service and injected via SetUsageTracker, keeping this package free of import cycles.

Jump to

Keyboard shortcuts

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