luaplugin

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2026 License: MIT Imports: 28 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
	// ProxyLocation is an optional ISO country code the upstream expects
	// requests to originate from (proxy preference).
	ProxyLocation string
	// ProxyForceOnMismatch marks providers that require a proxy whenever the
	// server location differs from ProxyLocation (e.g. region-locked APIs).
	ProxyForceOnMismatch bool
	// 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"`
	// ProxyLocation and ProxyForceOnMismatch mirror the manifest proxy tags.
	ProxyLocation        string `json:"proxy_location,omitempty"`
	ProxyForceOnMismatch bool   `json:"proxy_force_on_mismatch,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 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.

Geo-rotation: a region-locked answer through a proxy demotes it (exec records the outcome) and the handler re-runs against the next pooled proxy — silently, until the pool is exhausted. Direct calls never loop.

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

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

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

func (*Service) Delete

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

Delete removes a plugin and its storage entries.

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

func (s *Service) SetProxyOutcomeReporter(fn func(proxyID, typeKey string, ok bool, latencyMs int64))

SetProxyOutcomeReporter wires per-provider proxy health feedback.

func (*Service) SetProxyResolver

func (s *Service) SetProxyResolver(fn func(rec *PluginRecord, providerConfig map[string]any) (proxyID, proxyURL string, err error))

SetProxyResolver wires pool-based proxy selection for plugin HTTP calls. Resolution is lazy per request; a non-nil error fails the request loudly (e.g. manual mode with no usable proxy, or a geo-forced provider with an empty pool).

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.

Jump to

Keyboard shortcuts

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