jsplugin

package
v1.0.0-rc.27 Latest Latest
Warning

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

Go to latest
Published: Aug 29, 2026 License: AGPL-3.0 Imports: 34 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultCallTimeout = 5 * time.Second
	DefaultConcurrency = 8
)
View Source
const (
	ContextKeyPinnedPlugin    = "task_plugin_pinned_plugin"
	ContextKeyPinnedRoute     = "task_plugin_pinned_route"
	ContextKeyPinnedEndpoint  = "task_plugin_pinned_endpoint"
	ContextKeyRouteRequest    = "task_plugin_route_request"
	ContextKeyProtocolRequest = "task_plugin_protocol_request"
)
View Source
const APIVersion1 = 1

Variables

View Source
var DefaultRegistry = NewRegistry()
View Source
var ErrCallAdmissionTimeout = errors.New("plugin call admission timed out")

Functions

func NormalizeRoutePath

func NormalizeRoutePath(routePath string) (string, error)

NormalizeRoutePath validates the canonical path syntax used by plugin route declarations. A trailing slash is allowed and remains significant.

func PreflightRoutingConflict

func PreflightRoutingConflict(current *RoutingGeneration, candidate *LoadedPlugin) error

PreflightRoutingConflict reports whether admitting candidate into the current generation would collide on a channel type, native route, or protocol-model binding. A same-key entry is replaced first so re-uploading a plugin (or overriding a factory built-in) does not self-conflict.

func ResolveRouteAction

func ResolveRouteAction(route Route, resolvedAction string) string

func RunCLI

func RunCLI(args []string, stdout, stderr io.Writer) int

RunCLI implements the `new-api plugin` subcommand: linting a plugin source and replaying a golden fixture against it. It returns a process exit code.

func SupportsHostProtocol

func SupportsHostProtocol(protocol string) bool

SupportsHostProtocol reports whether the current host release has a concrete wire/state machine for an otherwise valid manifest endpoint.

func ValidateRequestURL

func ValidateRequestURL(requestURL, baseURL string, allowedHosts []string) error

ValidateRequestURL prevents plugins from directing a channel credential to hosts other than the configured base URL or an administrator-approved host.

func ValidateV1Meta

func ValidateV1Meta(meta Meta) error

ValidateV1Meta applies the metadata constraints published in docs/plugin-api/v1.schema.json to administrator uploads.

Types

type AuthMeta

type AuthMeta struct {
	Type string `json:"type"`
}

type AuthorMeta

type AuthorMeta struct {
	Name string `json:"name"`
	URL  string `json:"url,omitempty"`
}

type BodyKind

type BodyKind string
const (
	BodyNone      BodyKind = "none"
	BodyJSON      BodyKind = "json"
	BodyForm      BodyKind = "form"
	BodyMultipart BodyKind = "multipart"
)

type Engine

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

func Compile

func Compile(source string, options Options) (*Engine, error)

Compile performs upload-time syntax checks and compiles an ESM plugin once. All Sobek-specific module and runtime handling is intentionally kept here.

func (*Engine) Call

func (e *Engine) Call(ctx context.Context, exportName string, args ...any) (result any, err error)

Call invokes one named module export and returns its JSON-compatible value.

func (*Engine) CallMember

func (e *Engine) CallMember(ctx context.Context, exportName, memberName string, args ...any) (result any, err error)

CallMember invokes a function stored on an exported object, such as a renderer in the renderers export.

func (*Engine) CallPath

func (e *Engine) CallPath(ctx context.Context, exportName string, members []string, args ...any) (result any, err error)

CallPath invokes a function nested below an exported object. It is used for protocol hooks such as protocols.openai_responses.renderEvents.

func (*Engine) CallPathWithAdmissionTimeout

func (e *Engine) CallPathWithAdmissionTimeout(
	ctx context.Context,
	admissionTimeout time.Duration,
	exportName string,
	members []string,
	args ...any,
) (result any, err error)

CallPathWithAdmissionTimeout gives long-lived observers a separate bound for waiting on JavaScript capacity. Once admitted, the hook receives the engine's full execution timeout instead of inheriting time already spent in the semaphore queue.

func (*Engine) Export

func (e *Engine) Export(ctx context.Context, exportName string) (result any, err error)

Export returns one module export without exposing Sobek values outside the engine boundary. It is used for declarative exports such as meta.

func (*Engine) HasCallablePath

func (e *Engine) HasCallablePath(ctx context.Context, exportName string, members ...string) (found bool, err error)

HasCallablePath reports whether an exported value, or a nested member below it, exists and is callable.

func (*Engine) HasExport

func (e *Engine) HasExport(ctx context.Context, exportName string) (bool, error)

HasExport reports whether a module export exists. Optional contract hooks should be detected with this method instead of relying on engine errors.

type Fixture

type Fixture struct {
	UnixNow *int64        `json:"unixNow"`
	Cases   []FixtureCase `json:"cases"`
}

Fixture describes deterministic calls into a plugin. Arguments and expected values stay as JSON so fixtures remain portable across engine implementations.

type FixtureCase

type FixtureCase struct {
	Name          string            `json:"name"`
	Hook          string            `json:"hook"`
	Member        string            `json:"member,omitempty"`
	Path          []string          `json:"path,omitempty"`
	Args          []json.RawMessage `json:"args"`
	Expected      json.RawMessage   `json:"expected"`
	ExpectedError string            `json:"expectedError,omitempty"`
}

type FixtureReport

type FixtureReport struct {
	Total  int
	Passed int
}

func ReplayFixture

func ReplayFixture(ctx context.Context, source string, data []byte) (FixtureReport, error)

ReplayFixture compiles a plugin and runs every fixture case in declaration order. unixNow is fixed by the fixture to keep signing and timestamp hooks reproducible.

type HookError

type HookError struct {
	Hook    string
	Message string
	// contains filtered or unexported fields
}

HookError reports a JavaScript exception thrown by a plugin hook. Message is the sanitized JS error message with engine prefixes stripped; it is safe to surface to API callers.

func (*HookError) Error

func (e *HookError) Error() string

func (*HookError) Unwrap

func (e *HookError) Unwrap() error

type HostProtocolDefinition

type HostProtocolDefinition struct {
	Name       string
	Operations []HostProtocolOperation
}

func HostProtocol

func HostProtocol(name string) (HostProtocolDefinition, bool)

func HostProtocols

func HostProtocols() []HostProtocolDefinition

func (HostProtocolDefinition) DefinedModes

func (d HostProtocolDefinition) DefinedModes() []ProtocolMode

DefinedModes returns each distinct mode on the protocol in host-table order.

type HostProtocolOperation

type HostProtocolOperation struct {
	Name                    string
	Methods                 []string
	Path                    string
	BodyKinds               []BodyKind
	ModelField              string
	RequiredProtocolMembers []string
	Modes                   []ProtocolMode
	RequiredDriverHooks     []string
}

func LookupHostProtocolOperation

func LookupHostProtocolOperation(method, path string) (string, HostProtocolOperation, bool)

type LoadedPlugin

type LoadedPlugin struct {
	Meta   Meta
	Engine *Engine
}

func CompilePlugin

func CompilePlugin(source string, options Options) (*LoadedPlugin, error)

CompilePlugin validates a plugin without publishing it. Callers that refresh multiple plugins use this together with ReplaceOverrides so readers observe a single generation transition.

type LocalizedText

type LocalizedText map[string]string

LocalizedText is locale-keyed display copy. Plugin source may use a bare string (normalized to {"en": s}) or a map that must include "en". API responses always emit an object.

func (LocalizedText) MarshalJSON

func (t LocalizedText) MarshalJSON() ([]byte, error)

func (*LocalizedText) UnmarshalJSON

func (t *LocalizedText) UnmarshalJSON(data []byte) error

type Meta

type Meta struct {
	APIVersion    int                         `json:"apiVersion"`
	Key           string                      `json:"key"`
	Name          string                      `json:"name"`
	Icon          string                      `json:"icon,omitempty"`
	Description   LocalizedText               `json:"description,omitempty"`
	Version       string                      `json:"version"`
	Author        AuthorMeta                  `json:"author"`
	ChannelTypes  []int                       `json:"channelTypes,omitempty"`
	Models        []string                    `json:"models"`
	FetchMode     string                      `json:"fetchMode"`
	AllowedHosts  []string                    `json:"allowedHosts"`
	Routes        []Route                     `json:"routes"`
	Protocols     []ProtocolClaim             `json:"protocols"`
	UsageSchema   map[string]UsageFieldSchema `json:"usageSchema,omitempty"`
	UsageExamples []UsageExample              `json:"usageExamples,omitempty"`
	Auth          AuthMeta                    `json:"auth"`
}

func (Meta) ProtocolSupports

func (m Meta) ProtocolSupports(protocol, mode string) bool

ProtocolSupports reports whether the named protocol claim includes mode.

type Options

type Options struct {
	Key         string
	Version     string
	Timeout     time.Duration
	Concurrency int
	Now         func() time.Time
	Log         func(string)
}

type PinnedEndpoint

type PinnedEndpoint struct {
	Generation *RoutingGeneration
	Plugin     *LoadedPlugin
	Protocol   string
	Operation  HostProtocolOperation
	Model      string
	Candidates []ProtocolBinding
}

PinnedEndpoint carries the exact generation and endpoint candidates selected before distribution. Plugin initially names the deterministic request parser; distribution may rebind it to another candidate from the same generation when multiple legacy providers expose the same model.

type PinnedPlugin

type PinnedPlugin struct {
	Generation *RoutingGeneration
	Plugin     *LoadedPlugin
}

type PinnedRoute

type PinnedRoute struct {
	Generation *RoutingGeneration
	Plugin     *LoadedPlugin
	Route      Route
}

type PreparedRoutingGeneration

type PreparedRoutingGeneration struct {
	Generation *RoutingGeneration
	Errors     map[string]string
}

type ProtocolBinding

type ProtocolBinding struct {
	Plugin    *LoadedPlugin
	Protocol  string
	Operation HostProtocolOperation
	Model     string
}

type ProtocolClaim

type ProtocolClaim struct {
	Name     string   `json:"name"`
	Models   []string `json:"models,omitempty"`
	Supports []string `json:"supports,omitempty"`
	// contains filtered or unexported fields
}

ProtocolClaim is one entry of meta.protocols. Models narrows the protocol's endpoint bindings to a subset of meta.models; empty binds every model. Supports names the request forms a mode-bearing protocol accepts; decode and normalize rewrite it into host-table order.

type ProtocolMode

type ProtocolMode struct {
	Name string
	Hook string
}

ProtocolMode is one client request form a host protocol operation accepts and the plugin hook that implements it.

type ProtocolRequestContext

type ProtocolRequestContext struct {
	RouteRequestContext
	Protocol  string `json:"protocol"`
	Operation string `json:"operation"`
	Model     string `json:"model"`
	Stream    bool   `json:"stream"`
}

func (ProtocolRequestContext) JSValue

func (p ProtocolRequestContext) JSValue() map[string]any

type Registry

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

func NewRegistry

func NewRegistry() *Registry

func (*Registry) ActiveOverridePlugins

func (r *Registry) ActiveOverridePlugins() map[string]*LoadedPlugin

func (*Registry) Enabled

func (r *Registry) Enabled() bool

Enabled reports the master switch position. When false the published routing generation contains no plugins regardless of the other layers.

func (*Registry) Generation

func (r *Registry) Generation() *RoutingGeneration

func (*Registry) Get

func (r *Registry) Get(platform string) (*LoadedPlugin, bool)

func (*Registry) GetByChannelType

func (r *Registry) GetByChannelType(channelType int) (*LoadedPlugin, bool)

func (*Registry) LastRebuildError

func (r *Registry) LastRebuildError() string

func (*Registry) LastRebuildOutcome

func (r *Registry) LastRebuildOutcome() RoutingRebuildOutcome

func (*Registry) OverridePlugins

func (r *Registry) OverridePlugins() map[string]*LoadedPlugin

func (*Registry) Register

func (r *Registry) Register(source string, options Options) (*LoadedPlugin, error)

func (*Registry) RegisterFactory

func (r *Registry) RegisterFactory(source string, options Options) (*LoadedPlugin, error)

func (*Registry) ReplaceOverrides

func (r *Registry) ReplaceOverrides(plugins []*LoadedPlugin) error

ReplaceOverrides atomically publishes a complete override layer.

func (*Registry) RoutingErrors

func (r *Registry) RoutingErrors() map[string]string

func (*Registry) RoutingStatus

func (r *Registry) RoutingStatus() RoutingStatus

func (*Registry) SetDisabledFactoryKeys

func (r *Registry) SetDisabledFactoryKeys(keys []string)

func (*Registry) SetEnabled

func (r *Registry) SetEnabled(enabled bool)

func (*Registry) SetGenerationPreparer

func (r *Registry) SetGenerationPreparer(preparer RoutingGenerationPreparer) error

func (*Registry) SetOverrideEnabled

func (r *Registry) SetOverrideEnabled(enabled bool)

func (*Registry) Snapshot

func (r *Registry) Snapshot() RegistrySnapshot

func (*Registry) Unregister

func (r *Registry) Unregister(key string) error

type RegistrySnapshot

type RegistrySnapshot struct {
	Factory         []Meta
	Override        []Meta
	DisabledFactory []string
}

RegistrySnapshot is a read-only copy of the metadata currently stored in each registry layer.

type Route

type Route struct {
	Method      string    `json:"method"`
	Path        string    `json:"path"`
	Type        RouteType `json:"type"`
	Action      string    `json:"action,omitempty"`
	Decode      string    `json:"decode,omitempty"`
	Render      string    `json:"render,omitempty"`
	TaskIDParam string    `json:"taskIdParam,omitempty"`
	// Models restricts this route to the listed models. The host matches the
	// canonical top-level "model" body field before any JS hook runs; empty
	// means unrestricted. Must be a subset of meta.models.
	Models []string `json:"models,omitempty"`
}

type RouteBinding

type RouteBinding struct {
	Plugin *LoadedPlugin
	Route  Route
}

type RouteRequestContext

type RouteRequestContext struct {
	Path        string              `json:"path"`
	Method      string              `json:"method"`
	Params      map[string]string   `json:"params"`
	Query       map[string][]string `json:"query"`
	Body        any                 `json:"body"`
	Files       []map[string]any    `json:"-"`
	RequestBody any                 `json:"-"`
}

RouteRequestContext is the canonical request view exposed to declarative routing hooks. RequestBody contains decoded JSON or multipart text fields; raw binary and multipart file bytes remain host-owned.

func (RouteRequestContext) JSValue

func (r RouteRequestContext) JSValue() map[string]any

type RouteType

type RouteType string
const (
	RouteTypeSubmit  RouteType = "submit"
	RouteTypeQuery   RouteType = "query"
	RouteTypeDynamic RouteType = "dynamic"
)

type RoutingGeneration

type RoutingGeneration struct {
	Number      uint64
	PublishedAt time.Time
	// contains filtered or unexported fields
}

RoutingGeneration is an immutable, request-pinnable view of all effective plugins and their deterministic routing indexes.

func (*RoutingGeneration) Get

func (g *RoutingGeneration) Get(key string) (*LoadedPlugin, bool)

func (*RoutingGeneration) GetByChannelType

func (g *RoutingGeneration) GetByChannelType(channelType int) (*LoadedPlugin, bool)

func (*RoutingGeneration) GetByModel

func (g *RoutingGeneration) GetByModel(model string) (*LoadedPlugin, bool)

GetByModel returns the deterministic effective plugin metadata used for a model-level host concern such as billing. When multiple providers expose the same model name, the first plugin in generation order owns that shared metadata view.

func (*RoutingGeneration) LookupDeclaredRoute

func (g *RoutingGeneration) LookupDeclaredRoute(method, path string) (RouteBinding, bool)

LookupDeclaredRoute resolves a manifest path declaration. It does not match an incoming concrete URL; runtime matching is delegated to Gin.

func (*RoutingGeneration) LookupEndpoint

func (g *RoutingGeneration) LookupEndpoint(method, path, model string) (ProtocolBinding, bool)

func (*RoutingGeneration) LookupEndpointCandidates

func (g *RoutingGeneration) LookupEndpointCandidates(method, path, model string) []ProtocolBinding

LookupEndpointCandidates returns every legacy provider implementation that can serve one shared model endpoint. Candidate order is deterministic and the first binding is the parser used before channel distribution.

func (*RoutingGeneration) Plugins

func (g *RoutingGeneration) Plugins() []*LoadedPlugin

func (*RoutingGeneration) RebuildWithPlugins

func (g *RoutingGeneration) RebuildWithPlugins(plugins []*LoadedPlugin) (*RoutingGeneration, error)

RebuildWithPlugins creates a generation from the supplied exact plugin pointers. It is used when a rejected hot update must retain the incumbent runtime object for that key.

func (*RoutingGeneration) RetainsIncumbent

func (g *RoutingGeneration) RetainsIncumbent(key string) bool

func (*RoutingGeneration) Routes

func (g *RoutingGeneration) Routes() []RouteBinding

func (*RoutingGeneration) RuntimeHandler

func (g *RoutingGeneration) RuntimeHandler() http.Handler

RuntimeHandler is the inner router built for this exact generation. It is published in the same atomic pointer as the routing indexes.

func (*RoutingGeneration) WithRuntime

func (g *RoutingGeneration) WithRuntime(handler http.Handler) *RoutingGeneration

WithRuntime returns a shallow immutable copy carrying the prepared inner handler. Callers use it before publication; published generations must not be mutated.

type RoutingGenerationPreparer

type RoutingGenerationPreparer func(candidate, current *RoutingGeneration) (PreparedRoutingGeneration, error)

type RoutingRebuildOutcome

type RoutingRebuildOutcome struct {
	Status      string    `json:"status"`
	AttemptedAt time.Time `json:"attempted_at"`
	Generation  uint64    `json:"generation"`
	Error       string    `json:"error,omitempty"`
}

type RoutingStatus

type RoutingStatus struct {
	Generation  *RoutingGeneration
	LastRebuild RoutingRebuildOutcome
	Errors      map[string]string
}

type UsageExample

type UsageExample struct {
	Label string         `json:"label"`
	Facts map[string]any `json:"facts"`
}

UsageExample is a display-only pricing sample: a labeled complete vector over usageSchema. It never participates in billing.

type UsageFieldSchema

type UsageFieldSchema struct {
	Type        string        `json:"type,omitempty"`
	Unit        string        `json:"unit,omitempty"`
	Enum        []string      `json:"enum,omitempty"`
	Description LocalizedText `json:"description,omitempty"`
}

UsageFieldSchema declares how one usage fact is validated before it can influence billing. Numeric facts use one of the host-owned canonical units; boolean facts are flags; enum facts constrain non-numeric pricing selectors.

Jump to

Keyboard shortcuts

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