Documentation
¶
Index ¶
- Constants
- Variables
- func ASCIIFold(s string) string
- func CloneUsageSchema(schema map[string]UsageFieldSchema) map[string]UsageFieldSchema
- func DecodeIconDataURI(icon string) (string, []byte, error)
- func FileReference(field string, index int) string
- func HasCapability(name string) bool
- func NormalizeRoutePath(routePath string) (string, error)
- func ParseFileReference(ref string) (field string, index int, ok bool)
- func PreflightRoutingConflict(current *RoutingGeneration, candidate *LoadedPlugin) error
- func ResolveRouteAction(route Route, resolvedAction string) string
- func RunCLI(args []string, stdout, stderr io.Writer) int
- func SupportsHostProtocol(protocol string) bool
- func UsesSubmitEventDelta(meta Meta, engine *Engine) bool
- func ValidPluginKey(key string) bool
- func ValidateIconImage(mediaType string, data []byte) error
- func ValidateRequestHeaders(headers map[string]string) error
- func ValidateRequestURL(requestURL, baseURL string, allowedHosts []string) error
- func ValidateV1Meta(meta Meta) error
- func WithFetcher(ctx context.Context, fetcher Fetcher) context.Context
- type AuthMeta
- type AuthorMeta
- type BodyKind
- type Engine
- func (e *Engine) Call(ctx context.Context, exportName string, args ...any) (result any, err error)
- func (e *Engine) CallInto(ctx context.Context, target any, exportName string, args ...any) error
- func (e *Engine) CallJSONInto(ctx context.Context, target any, exportName string, args ...any) error
- func (e *Engine) CallMember(ctx context.Context, exportName, memberName string, args ...any) (result any, err error)
- func (e *Engine) CallPath(ctx context.Context, exportName string, members []string, args ...any) (result any, err error)
- func (e *Engine) CallPathInto(ctx context.Context, target any, exportName string, members []string, ...) error
- func (e *Engine) CallPathWithAdmissionTimeout(ctx context.Context, admissionTimeout time.Duration, exportName string, ...) (result any, err error)
- func (e *Engine) CallPathWithMemberJSON(ctx context.Context, admissionTimeout time.Duration, member string, ...) (result any, text json.RawMessage, err error)
- func (e *Engine) Export(ctx context.Context, exportName string) (any, error)
- func (e *Engine) HasCallablePath(ctx context.Context, exportName string, members ...string) (bool, error)
- func (e *Engine) HasExport(exportName string) bool
- type FetchRequest
- type FetchResponse
- type Fetcher
- type Fixture
- type FixtureCase
- type FixtureReport
- type HookError
- type HostProtocolDefinition
- type HostProtocolOperation
- type JSONState
- type LoadedPlugin
- type LocalizedText
- type Meta
- func (m Meta) AcceptsAutoDuration() bool
- func (m Meta) JSONTextMember(member string) string
- func (m Meta) PreservesJSONOrder() bool
- func (m Meta) ProtocolSupports(protocol, mode string) bool
- func (m Meta) SupportsUpstream(kind string) bool
- func (m Meta) UsageForModel(model string) (map[string]UsageFieldSchema, []UsageExample)
- func (m Meta) UsageForModels(models ...string) (map[string]UsageFieldSchema, []UsageExample)
- type Options
- type PinnedEndpoint
- type PinnedPlugin
- type PinnedRoute
- type PreparedRoutingGeneration
- type ProtocolBinding
- type ProtocolClaim
- type ProtocolMode
- type ProtocolRequestContext
- type RawJSON
- type Registry
- func (r *Registry) ActiveOverridePlugins() map[string]*LoadedPlugin
- func (r *Registry) Enabled() bool
- func (r *Registry) Generation() *RoutingGeneration
- func (r *Registry) Get(platform string) (*LoadedPlugin, bool)
- func (r *Registry) GetByChannelType(channelType int) (*LoadedPlugin, bool)
- func (r *Registry) LastRebuildError() string
- func (r *Registry) LastRebuildOutcome() RoutingRebuildOutcome
- func (r *Registry) OverridePlugins() map[string]*LoadedPlugin
- func (r *Registry) Register(source string, options Options) (*LoadedPlugin, error)
- func (r *Registry) RegisterFactory(source string, options Options) (*LoadedPlugin, error)
- func (r *Registry) ReplaceOverrides(plugins []*LoadedPlugin) error
- func (r *Registry) RoutingErrors() map[string]string
- func (r *Registry) RoutingStatus() RoutingStatus
- func (r *Registry) SetDisabledFactoryKeys(keys []string)
- func (r *Registry) SetEnabled(enabled bool)
- func (r *Registry) SetGenerationPreparer(preparer RoutingGenerationPreparer) error
- func (r *Registry) Snapshot() RegistrySnapshot
- func (r *Registry) Unregister(key string) error
- type RegistrySnapshot
- type ResultError
- type Route
- type RouteBinding
- type RouteRequestContext
- type RouteType
- type RoutingGeneration
- func (g *RoutingGeneration) CanonicalModel(model string) (string, bool)
- func (g *RoutingGeneration) Get(key string) (*LoadedPlugin, bool)
- func (g *RoutingGeneration) GetByChannelType(channelType int) (*LoadedPlugin, bool)
- func (g *RoutingGeneration) GetByModel(model string) (*LoadedPlugin, bool)
- func (g *RoutingGeneration) LookupDeclaredRoute(method, path string) (RouteBinding, bool)
- func (g *RoutingGeneration) LookupEndpoint(method, path, model string) (ProtocolBinding, bool)
- func (g *RoutingGeneration) LookupEndpointCandidates(method, path, model string) []ProtocolBinding
- func (g *RoutingGeneration) Plugins() []*LoadedPlugin
- func (g *RoutingGeneration) PluginsByModel(model string) []*LoadedPlugin
- func (g *RoutingGeneration) RebuildWithPlugins(plugins []*LoadedPlugin) (*RoutingGeneration, error)
- func (g *RoutingGeneration) RetainsIncumbent(key string) bool
- func (g *RoutingGeneration) Routes() []RouteBinding
- func (g *RoutingGeneration) RuntimeHandler() http.Handler
- func (g *RoutingGeneration) SharedModel(model string) bool
- func (g *RoutingGeneration) WithRuntime(handler http.Handler) *RoutingGeneration
- type RoutingGenerationPreparer
- type RoutingRebuildOutcome
- type RoutingStatus
- type UnknownMetaFieldError
- type UsageExample
- type UsageFieldSchema
- type UsageProfile
Constants ¶
const ( DefaultCallTimeout = 5 * time.Second DefaultConcurrency = 8 )
const ( CapabilityJSONClone = "json-clone@1" CapabilitySubmitSSEDelta = "submit-sse-delta@1" CapabilityJSONOrder = "json-order@1" CapabilityDurationAuto = "duration-auto@1" MaxJSONToolBytes = 1 << 20 )
const ( UpstreamKindVendor = "vendor" UpstreamKindNewAPI = "new_api" )
Upstream kinds a plugin driver can address. Every driver speaks to its vendor; a driver that also builds its own native-route URLs when the channel points at another New API gateway declares UpstreamKindNewAPI in meta.upstreams, which is what makes it bindable to a type-60 channel.
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" // ContextKeyRequestBodyText holds, for a plugin that preserves JSON // order, the decoded requestBody as JSON text (json.RawMessage) beside // the Go value in task_request. ContextKeyRequestBodyText = "task_plugin_request_body_text" )
const APIVersion1 = 1
const (
MaxFetchBodyBytes = 1 << 20
)
The utils.fetch limits are part of the published plugin contract (docs/plugin-api/v1.md). A fetcher reads at most MaxFetchBodyBytes+1 bytes so that the engine can reject a longer body.
const MaxIconDataURIBytes = 512 * 1024
MaxIconDataURIBytes bounds an uploaded plugin logo. It is deliberately generous: the plugin source itself is capped at 1 MiB, so this only keeps a logo from dwarfing the plugin it decorates.
const MaxMetaBaseURLLength = 191
MaxMetaBaseURLLength bounds a normalized plugin default base URL. The value is persisted into channel.base_url, which the pinned MySQL driver creates as varchar(191); a longer default would store on SQLite and PostgreSQL but fail on MySQL.
const ProtocolOpenAIImage = "openai_image"
ProtocolOpenAIImage is the host protocol that serves the OpenAI Images API (`POST /v1/images/generations` and `POST /v1/images/edits`) from a plugin.
Variables ¶
var DefaultRegistry = NewRegistry()
var ErrCallAdmissionTimeout = errors.New("plugin call admission timed out")
Functions ¶
func CloneUsageSchema ¶
func CloneUsageSchema(schema map[string]UsageFieldSchema) map[string]UsageFieldSchema
CloneUsageSchema copies schema fields and localized metadata for independent readers.
func DecodeIconDataURI ¶
DecodeIconDataURI parses a plugin logo shipped as a sidecar icon.svg or icon.png file and re-encoded by the uploader as data:image/png;base64,... or data:image/svg+xml;base64,.... It returns the media type and the raw image bytes. The admin UI renders logos only through <img>, which already blocks scripts and external loads; the SVG checks here are defense in depth so a hostile payload is rejected at upload instead of being stored.
func FileReference ¶
FileReference returns the opaque ref of the index-th uploaded file in a multipart field. The first file keeps the historical `request_file:<field>` spelling; later files in the same repeated field (`image[]`, `image[]`) append `#<index>` so a plugin can address each of them.
func HasCapability ¶
HasCapability describes host APIs independently of a plugin's mutable globals.
func NormalizeRoutePath ¶
NormalizeRoutePath validates the canonical path syntax used by plugin route declarations. A trailing slash is allowed and remains significant.
func ParseFileReference ¶
ParseFileReference resolves a ref produced by FileReference back to the multipart field and the zero-based file index within that field.
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 RunCLI ¶
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 ¶
SupportsHostProtocol reports whether the current host release has a concrete wire/state machine for an otherwise valid manifest endpoint.
func UsesSubmitEventDelta ¶
UsesSubmitEventDelta reports whether SSE submissions go through parseSubmitEventDelta: the plugin declares submit-sse-delta@1, or exports parseSubmitEventDelta without parseSubmitEvent. A plugin that exports both and declares nothing keeps the snapshot hook, as before.
func ValidPluginKey ¶
ValidPluginKey checks the canonical identifier accepted by plugin manifests.
func ValidateIconImage ¶
ValidateIconImage checks raw PNG or SVG bytes for a plugin logo. PNG must carry the PNG signature. SVG must be well-formed XML rooted at svg without script or foreignObject elements, event-handler attributes, directives, javascript: values, or absolute http(s) references.
func ValidateRequestHeaders ¶
ValidateRequestHeaders rejects plugin-chosen headers that the host transport owns or that change how a request is framed or proxied, and bounds their number and size.
func ValidateRequestURL ¶
ValidateRequestURL prevents plugins from directing a channel credential to hosts other than the configured base URL or an administrator-approved host.
func ValidateV1Meta ¶
ValidateV1Meta applies the metadata constraints published in docs/plugin-api/v1.schema.json to administrator uploads.
Types ¶
type AuthorMeta ¶
type Engine ¶
type Engine struct {
// contains filtered or unexported fields
}
func Compile ¶
Compile performs upload-time syntax checks and compiles an ESM plugin once. All engine-specific module and runtime handling is intentionally kept here.
func (*Engine) CallInto ¶
CallInto invokes one named module export and stores its result in target as the host codec decodes the encoding of the value Call returns, without that round trip for plain results. A result the codec cannot encode or target's type rejects is a *ResultError, and target may then hold part of it.
func (*Engine) CallJSONInto ¶
func (e *Engine) CallJSONInto(ctx context.Context, target any, exportName string, args ...any) error
CallJSONInto is CallInto with the semantics of JSON.stringify's text of the result instead of the host codec's encoding: objects keep their member order, which a json.RawMessage in target receives as text, members whose value is undefined are left out and toJSON runs.
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) CallPathInto ¶
func (e *Engine) CallPathInto(ctx context.Context, target any, exportName string, members []string, args ...any) error
CallPathInto is CallInto for a function nested below an exported object.
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) CallPathWithMemberJSON ¶
func (e *Engine) CallPathWithMemberJSON( ctx context.Context, admissionTimeout time.Duration, member string, exportName string, members []string, args ...any, ) (result any, text json.RawMessage, err error)
CallPathWithMemberJSON is CallPathWithAdmissionTimeout that also returns the result's member as the text JSON.stringify writes for it, which keeps the member order of its objects. The text is nil when member is empty or the result has no such member.
func (*Engine) Export ¶
Export returns one module export without exposing engine 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) (bool, error)
HasCallablePath reports whether an exported value, or a nested member below it, exists and is callable.
func (*Engine) HasExport ¶
HasExport reports whether a module export was defined when the plugin loaded: an export that was undefined then counts as absent, and a later assignment is not seen. Optional contract hooks should be detected with this method instead of relying on engine errors. It runs no JavaScript, so it neither waits for nor takes a call slot.
type FetchRequest ¶
type Fetcher ¶
type Fetcher func(ctx context.Context, request FetchRequest) (FetchResponse, error)
Fetcher sends one utils.fetch request for the hook call whose context carries it. The host binds it to the executing channel; the engine passes a context already bounded by the call's fetch budget, so the fetcher only sends.
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 ¶
func ReplayFixture ¶
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 ¶
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.
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 JSONState ¶
type JSONState struct {
// contains filtered or unexported fields
}
JSONState owns a request-local JSON result. Appended strings stay in Go and are materialized only when the stream finishes, independently of JS runtimes.
func NewJSONState ¶
type LoadedPlugin ¶
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 ¶
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 {
RequiredCapabilities []string `json:"requiredCapabilities,omitempty"`
SubmitResponseTypes []string `json:"submitResponseTypes,omitempty"`
SortPriority int `json:"sortPriority,omitempty"`
Website string `json:"website,omitempty"`
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"`
BaseURL string `json:"baseUrl,omitempty"`
ChannelTypes []int `json:"channelTypes,omitempty"`
Models []string `json:"models"`
FetchMode string `json:"fetchMode"`
AllowedHosts []string `json:"allowedHosts"`
Upstreams []string `json:"upstreams,omitempty"`
Routes []Route `json:"routes"`
Protocols []ProtocolClaim `json:"protocols"`
UsageSchema map[string]UsageFieldSchema `json:"usageSchema,omitempty"`
UsageExamples []UsageExample `json:"usageExamples,omitempty"`
UsageProfiles []UsageProfile `json:"usageProfiles,omitempty"`
Auth AuthMeta `json:"auth"`
}
func (Meta) AcceptsAutoDuration ¶
AcceptsAutoDuration reports whether the plugin declared duration-auto@1: request validation lets a duration of -1, the vendor's "the model picks the length", through to its hooks. The plugin reserves the longest duration the model can produce and settles the task on the usage the vendor reports.
func (Meta) JSONTextMember ¶
JSONTextMember names the member of a hook result (a decoded requestBody, a request descriptor's body) that the host also takes as JSON text, for a plugin that preserves JSON order; it is empty for other plugins.
func (Meta) PreservesJSONOrder ¶
PreservesJSONOrder reports whether the plugin declared json-order@1: its hooks receive JSON request bodies with members in the order the client sent them, and its JSON request bodies go upstream as JSON.stringify writes them. Other plugins keep the cheaper Go-map path, whose members enumerate sorted.
func (Meta) ProtocolSupports ¶
ProtocolSupports reports whether the named protocol claim includes mode.
func (Meta) SupportsUpstream ¶
SupportsUpstream reports whether the driver handles channels of the given upstream kind. The vendor kind is implied for every plugin.
func (Meta) UsageForModel ¶
func (m Meta) UsageForModel(model string) (map[string]UsageFieldSchema, []UsageExample)
UsageForModel returns read-only usage metadata for a declared model. Aliases must be resolved by the host first; an unknown or ambiguous model uses the plugin defaults. Profile examples never inherit the default examples.
func (Meta) UsageForModels ¶
func (m Meta) UsageForModels(models ...string) (map[string]UsageFieldSchema, []UsageExample)
UsageForModels returns the usage metadata of the first candidate that a profile declares. Runtime callers pass the final upstream model before the client-facing model, so a channel mapping that sends a declared model to a vendor endpoint ID keeps the declared model's profile. When no candidate is profiled, the plugin defaults apply.
type PinnedEndpoint ¶
type PinnedEndpoint struct {
Generation *RoutingGeneration
Plugin *LoadedPlugin
Protocol string
Operation HostProtocolOperation
Model string
MappedModel 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 ¶
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"`
// UpstreamModel is the declared machine identity when Model is a
// channel-mapping alias; empty otherwise. Decode hooks that key rate
// tables or request shaping by model must use it over Model.
UpstreamModel string `json:"upstreamModel,omitempty"`
Stream bool `json:"stream"`
}
func (ProtocolRequestContext) JSValue ¶
func (p ProtocolRequestContext) JSValue() map[string]any
func (ProtocolRequestContext) JSValueFor ¶
func (p ProtocolRequestContext) JSValueFor(meta Meta) map[string]any
JSValueFor is RouteRequestContext.JSValueFor with the protocol fields.
type RawJSON ¶
type RawJSON []byte
RawJSON is a hook argument given as JSON text: the hook receives JSON.parse of it, members in order, whether it is an argument or inside one, with no Go values built in between; text nested too deep for JSON.parse is decoded with the host codec instead. The engine parses the bytes in place, without the copy ParseJSON makes, and strings of the call's result may share them, so the caller must never change them once passed.
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 ¶
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) GetByChannelType ¶
func (r *Registry) GetByChannelType(channelType int) (*LoadedPlugin, bool)
func (*Registry) LastRebuildError ¶
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 (*Registry) RoutingStatus ¶
func (r *Registry) RoutingStatus() RoutingStatus
func (*Registry) SetDisabledFactoryKeys ¶
func (*Registry) SetEnabled ¶
func (*Registry) SetGenerationPreparer ¶
func (r *Registry) SetGenerationPreparer(preparer RoutingGenerationPreparer) error
func (*Registry) Snapshot ¶
func (r *Registry) Snapshot() RegistrySnapshot
func (*Registry) Unregister ¶
type RegistrySnapshot ¶
RegistrySnapshot is a read-only copy of the metadata currently stored in each registry layer.
type ResultError ¶
type ResultError struct {
// contains filtered or unexported fields
}
ResultError reports a hook result that CallInto could not store: one the host codec cannot encode (a NaN, an infinity, a cycle) or one the target's type rejects. Its message is the codec's.
func (*ResultError) Error ¶
func (e *ResultError) Error() string
func (*ResultError) Unwrap ¶
func (e *ResultError) Unwrap() error
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"`
// RetainResult, when explicitly false on a submit or dynamic route, tells
// the host not to persist the upstream snapshot of an immediate terminal
// result and to treat the task as not found on every retrieval surface
// afterwards. nil means the route did not declare it (retain).
RetainResult *bool `json:"retainResult,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:"-"`
// BodyText is the JSON body as the client sent it, which JSValueFor
// gives to plugins that preserve JSON order; Body stays the Go value the
// host reads. Body storage never changes these bytes, which the engine
// parses in place.
BodyText json.RawMessage `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
JSValue shares the request with hooks without copying it: the engine never writes JavaScript changes back into Go values, so the request must only stay unchanged while a hook runs. Missing params and query still reach hooks as empty objects rather than null.
func (RouteRequestContext) JSValueFor ¶
func (r RouteRequestContext) JSValueFor(meta Meta) map[string]any
JSValueFor is JSValue for the decode hooks of the plugin meta describes. A plugin that preserves JSON order receives a JSON body as its text, which the engine parses in place, members in the client's order: a decoder reads the body, so it is parsed for every call.
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) CanonicalModel ¶
func (g *RoutingGeneration) CanonicalModel(model string) (string, bool)
CanonicalModel returns the declared spelling for model. An exact byModel hit wins and returns the input unchanged; otherwise the ASCII-folded index is consulted. Miss and nil-receiver return ("", false).
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 plugin that can serve a shared model endpoint, in ascending key order. Each candidate decodes before distribution.
func (*RoutingGeneration) Plugins ¶
func (g *RoutingGeneration) Plugins() []*LoadedPlugin
func (*RoutingGeneration) PluginsByModel ¶
func (g *RoutingGeneration) PluginsByModel(model string) []*LoadedPlugin
PluginsByModel returns all plugins declaring model, in ascending key order.
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) SharedModel ¶
func (g *RoutingGeneration) SharedModel(model string) bool
SharedModel reports whether multiple plugins declare a model without copying its provider list on the relay hot path.
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 RoutingStatus ¶
type RoutingStatus struct {
Generation *RoutingGeneration
LastRebuild RoutingRebuildOutcome
Errors map[string]string
}
type UnknownMetaFieldError ¶
type UnknownMetaFieldError struct {
Field string
}
UnknownMetaFieldError identifies a manifest field unsupported by this host.
func (*UnknownMetaFieldError) Error ¶
func (e *UnknownMetaFieldError) Error() string
type UsageExample ¶
UsageExample is a display-only pricing sample: a labeled complete vector over usageSchema. It never participates in billing.
func CloneUsageExamples ¶
func CloneUsageExamples(examples []UsageExample) []UsageExample
CloneUsageExamples copies example facts for independent readers.
type UsageFieldSchema ¶
type UsageFieldSchema struct {
Type string `json:"type,omitempty"`
Unit string `json:"unit,omitempty"`
UnitLabel LocalizedText `json:"unitLabel,omitempty"`
Enum []string `json:"enum,omitempty"`
Description LocalizedText `json:"description,omitempty"`
EnumLabels map[string]LocalizedText `json:"enumLabels,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.
type UsageProfile ¶
type UsageProfile struct {
Models []string `json:"models"`
Schema map[string]UsageFieldSchema `json:"schema"`
Examples []UsageExample `json:"examples,omitempty"`
}
UsageProfile replaces the plugin's default usage metadata for its models.