pluginkit

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: AGPL-3.0 Imports: 47 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Task plugin API v1

Task plugins are single-file synchronous ECMAScript modules. The plugin contract is currently unreleased; v1.schema.json and v1.d.ts are the authoritative v1 contract.

Contract and lifecycle

Every plugin exports meta, buildSubmitRequest, parseSubmitResponse, and parseTaskResult. A per_task plugin also exports buildQueryRequest; a batch plugin exports buildBatchQueryRequest and parseBatchResult. meta.author.name is required and meta.author.url, when present, must be an absolute HTTP(S) URL. This is self-declared attribution; a future marketplace's verified publisher identity is a separate host-owned record. Plugins may declare authenticated vendor-native meta.routes and claim host-owned names through meta.protocols. Submit and dynamic routes name a native decoder and presenter; query routes name only a presenter. Protocol bindings are registered once by the host registry, and protocol decoders receive the host-parsed body union plus the pinned model. Shared protocol hooks are synchronous transformations; Go owns connections and wire framing.

The host selects a channel, invokes the request-building hook, validates the returned URL against the channel host, performs HTTP, and gives the decoded response to the matching parse hook. It owns persistence, retries, polling, billing, and settlement. Plugins only transform data and report usage facts. See v1.d.ts for signatures and v1.schema.json for machine-readable shapes.

Plugins that expose task outputs export listArtifacts(task) and buildContentRequest(ctx) together. Artifacts are projected on explicit reads from persisted Task.Data; they are never stored as a second source of truth. The list contains only stable key, type, and optional mimeType fields. The content hook receives the selected key, raw decoded task data, the explicit private upstream task id, the producer plugin version, channel authentication, and a safe client Range/conditional-header subset. Its URL and headers exist only for that proxy request.

When a Responses observation reaches persisted SUCCESS, the host also runs the pinned plugin's listArtifacts and injects a read-only ctx.artifacts[key] = {key, type, mimeType?, url} map into renderEvents or renderFinal. Each url is a long-lived host-signed capability URL, never the provider URL from Task.Data. Nonterminal and failed tasks receive no artifact map. Capability construction or rendering failure fails only that Responses observation; it cannot change the task, billing settlement, or refunds. The absolute URL uses TaskPublicAddress, falling back only to ServerAddress; multi-node deployments must share the effective CRYPTO_SECRET. Dashboard artifact reads return each content_url (or the legacy legacy_content_url) directly, without a temporary URL exchange. Capability generation and verification are stateless and have no expiry; after verification the host still loads the task, owner, and plugin needed to serve the artifact. Rotating CRYPTO_SECRET invalidates issued URLs. The access query is redacted before request logging. Deployment boundaries and concurrency environment variables are documented in v1.md.

The host requires protocols.openai_video.render to return a JSON object and preserves provider extensions, including output URLs and metadata. Plugins may return task.data to expose the latest persisted upstream snapshot. The host still overwrites id, object, model, status, progress, created_at, and completed_at, and removes legacy task_id. This is field-level projection, not byte-for-byte HTTP forwarding: known private task IDs are replaced before rendering, polling may redact inline video data, and retrieval reads the latest saved snapshot rather than issuing a new upstream request. Artifact content endpoints remain available for proxied downloads.

Provider-authenticated content URLs must use the channel base host or a plugin-declared meta.allowedHosts entry. A public dynamic CDN URL may instead set credentialless: true; the host then permits only GET/HEAD with no plugin-supplied headers or body and applies SSRF checks to the initial URL and every redirect.

Registry publication is generation-atomic. A request pins one plugin generation for its full lifetime, while background polling may use a later active plugin version. New versions must continue parsing responses for in-flight tasks. Root administrators can inspect the local node with GET /api/plugin/task/runtime/status. The response includes the node-local generation, a deterministic revision of the active database overrides, the latest rebuild outcome, and plugin-level compile or routing errors. Generation numbers are local to a node; compare database revisions when diagnosing rollout lag between nodes. If the database snapshot is temporarily unavailable, the endpoint keeps serving node-local state and the last known revision with database_error set.

For live diagnosis, start the process with DEBUG=true and filter logs on task_plugin. Plugin registry, routing, endpoint ownership, channel selection, submit durability, polling adapters, and protocol observation emit safe key/value lifecycle events. Request-context events carry the request id; scheduled, background, and context-less work is labeled SYSTEM. Plugin console.log output is also forwarded in DEBUG mode. Hook-time output is prefixed with plugin key/version; module-initialization output may have an empty identity during initial upload validation. Do not print credentials, headers, request bodies, upstream payloads, or private URLs from plugin code; free-form console output cannot be redacted by the host.

Fixtures and dry runs

A fixture case is {name?, hook, member?, args, expected?, expectedError?}. Keep deterministic cases for every exported hook, its main error branch, batch behavior, renderers, usage, and content requests. Run a fixture locally with:

new-api plugin lint plugin.js
new-api plugin test plugin.js --fixture golden.json

Root administrators can open the plugin detail Sandbox tab, choose a hook, and submit an args JSON array. POST /api/plugin/task/:key/dryrun compiles the active database source or factory source in a temporary registry and invokes only that synchronous function. Dry runs never execute a request descriptor and therefore never contact an upstream service.

Upload and release

Upload from the root-only task plugin page or POST /api/plugin/task with {"source":"...","remark":"..."}. The server compiles the module, validates v1 metadata and required exports, and rejects invalid source before saving it. Use semantic plugin versions. Reusing a key/version with different source is rejected; activate or roll back a stored version through the management page.

For a third-party platform, create a channel of type Task Plugin, select the plugin key, provide an explicit base URL, and configure models. Clients may use the plugin's declared native routes. The generic management surface remains POST /v1/tasks/:pluginKey, GET /v1/tasks/:taskId, and GET /v1/tasks/:taskId/artifacts plus GET|HEAD /v1/tasks/:taskId/artifacts/:key/content.

Security boundary

Plugins have no global fetch, filesystem, require, imports, async functions, code compiled from strings (eval and the Function constructors throw an EvalError), or environment access. A few driver hooks may read upstream data with utils.fetch: GET or HEAD only, to the hosts a request descriptor may address. The host limits execution time, concurrency, input size, allowed request hosts, and resolves OAuth credentials outside JavaScript. Multipart files enter JavaScript only as opaque references.

This is not a hard memory-isolation boundary. A plugin sees data needed for the current request and can influence an authenticated upstream request. Uploading a plugin is an administrator-level trust decision equivalent to configuring a channel credential. Review source and version diffs before activation. Never run untrusted plugins merely because they compile.

Usage hooks may return facts such as seconds, resolution, or upstream units, but must never calculate prices or attempt quota settlement. The host owns all pricing and clamps billing conversions.

Documentation

Index

Constants

View Source
const (
	DefaultCallTimeout = 5 * time.Second
	DefaultConcurrency = 8
)
View Source
const (
	ChannelTypeNewAPI     = 60
	ChannelTypeTaskPlugin = 61
)

New API channel types a plugin may not declare in meta.channelTypes: a type-61 channel binds a plugin by key, and a type-60 New API channel extends with plugins through its own setting.

View Source
const (
	MaxUsageSeconds = 3600
	MaxUsageCount   = dto.MaxImageN
	MaxUsageQuota   = math.MaxInt32
)

Bounds of the usage facts a plugin reports and of its usage examples: second facts at most MaxUsageSeconds, count facts at most MaxUsageCount, token and credit facts at most MaxUsageQuota.

View Source
const (
	CapabilityJSONClone      = "json-clone@1"
	CapabilitySubmitSSEDelta = "submit-sse-delta@1"
	CapabilityJSONOrder      = "json-order@1"
	CapabilityDurationAuto   = "duration-auto@1"
	MaxJSONToolBytes         = 1 << 20 // Encoded JSON held by the submit SSE accumulator.

)
View Source
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.

View Source
const (
	// MaxLoginSessionBytes bounds the session a login step hands to the next
	// call. The host keeps it in the login flow; it never reaches the browser.
	MaxLoginSessionBytes = 16 << 10
	// MaxCredentialBytes bounds one stored credential line.
	MaxCredentialBytes = 64 << 10
	// MaxRejectedBodyBytes is how much of an upstream error body
	// credentialRejected reads.
	MaxRejectedBodyBytes = 64 << 10

	// MaxCheckKeyMessageRunes bounds the message checkKey shows the
	// administrator saving a channel.
	MaxCheckKeyMessageRunes = 512
)
View Source
const (
	LoginStepRedirect = "redirect"
	LoginStepPaste    = "paste"
	LoginStepDevice   = "device"
	LoginStepPending  = "pending"
	LoginStepFields   = "fields"
	LoginStepDone     = "done"
)

Login step types.

View Source
const (
	MaxSubmitStateBytes        = 1 << 20
	MaxSubmitControlStateBytes = 64 << 10
)

MaxSubmitStateBytes bounds the JSON state of a submission stream and the result parseSubmitEventDelta accumulates; MaxSubmitControlStateBytes bounds the control state parseSubmitEventDelta passes to its next event.

View Source
const (
	TransformErrorThrow    = "throw"
	TransformErrorTimeout  = "timeout"
	TransformErrorMemory   = "memory"
	TransformErrorCanceled = "canceled"
	TransformErrorResult   = "invalid_result"
	TransformErrorFailed   = "error"
)

Classes of a TransformError.

View Source
const APIVersion1 = 1
View Source
const CredentialType = "plugin_credential"

CredentialType marks a channel key line that holds a plugin credential.

View Source
const (
	MaxFetchBodyBytes = 1 << 20
)

The utils.fetch limits are part of the published plugin contract (v1.md). MaxFetchBodyBytes applies to the POST body before the host expands media references.

View Source
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.

View Source
const MaxMediaTextChars = 128 << 10

MaxMediaTextChars is the most text utils.mediaText returns for one attachment, in UTF-16 code units, and its default.

View Source
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.

View Source
const MaxPluginKeyLength = 30

MaxPluginKeyLength is the longest plugin key, in bytes.

View Source
const MaxTaskArtifacts = 64

MaxTaskArtifacts is the most artifacts listArtifacts may return.

View Source
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.

View Source
const ProviderConverter = "plugin"

ProviderConverter is the relay converter whose request and response the plugin's convertRequest, convertResponse and convertStreamEvent convert; on the model list route convertResponse alone runs. Only manifests accept it; Advanced Custom channel settings reject it.

View Source
const ReplyHook = "reply"

ReplyHook is the export that reads the model's answer as it reaches the client and may stop it or mask parts of it, never write into it. It gives a plugin a request processing part, as a stage hook does.

View Source
const ReportHook = "report"

ReportHook is the export that receives a finished request, off the request path. It gives a plugin a request processing part, as a stage hook does, but it is not a stage: it runs once per request and has no effects.

Variables

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

ErrCallTimeout is what interrupts a hook that runs past the call timeout.

View Source
var ErrMemoryLimit = moejs.ErrMemoryLimit

ErrMemoryLimit is what stops a hook whose JavaScript keeps more memory than Host.MemoryLimit allows.

View Source
var ErrSubmitClientResponse = errors.New("parseSubmitResponse must not return clientResponse")

ErrSubmitClientResponse is the error of a parseSubmitResponse result that carries the removed clientResponse member.

View Source
var ProviderHooks = []string{"login", "refresh", "revoke", "signRequest", "prepareRequest", "credentialRejected", "convertRequest", "convertResponse", "convertStreamEvent", "exchangeKey", "checkKey", "buildBalanceRequest", "parseBalance", "scheduled"}

ProviderHooks are the optional credential, relay and channel exports of a plugin.

View Source
var SchemaV1 []byte

SchemaV1 is the JSON Schema of the API v1 manifest (v1.schema.json).

View Source
var TransformStages = []string{"ingress", "request", "outbound", "egress"}

TransformStages are the stage hooks of the request processing part, in the order a request meets them.

View Source
var TypesV1 []byte

TypesV1 is the TypeScript declaration of API v1 (v1.d.ts).

Functions

func ASCIIFold

func ASCIIFold(s string) string

ASCIIFold is the exported form of asciiFold for consumers outside this package.

func ChannelConfigURL

func ChannelConfigURL(config json.RawMessage, name string) string

ChannelConfigURL returns the url property name of a channel plugin config, empty when it has no value.

func ClientRequestHeaders

func ClientRequestHeaders(header http.Header) map[string]string

ClientRequestHeaders is the client's request headers as decoders and driver hooks receive them: the first value of each under its canonical name, without the headers that carry gateway credentials, and with Content-Type and Accept always present.

func CloneUsageSchema

func CloneUsageSchema(schema map[string]UsageFieldSchema) map[string]UsageFieldSchema

CloneUsageSchema copies schema fields and localized metadata for independent readers.

func Configure

func Configure(host Host)

Configure sets the host for every plugin. A host calls it at startup, before it compiles plugins; the namespaces and keys apply to plugins compiled after the call.

func DecodeIconDataURI

func DecodeIconDataURI(icon string) (string, []byte, error)

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 EncodeFilePlaceholders

func EncodeFilePlaceholders(body any, form *multipart.Form, limit int64) (any, error)

EncodeFilePlaceholders replaces, in body itself, each file placeholder of a JSON request descriptor body with the encoded bytes of the uploaded file it names, and returns the result. limit bounds each file and all of them together. body must be the host's own copy: its maps and slices change.

func FileReference

func FileReference(field string, index int) string

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

func HasCapability(name string) bool

HasCapability describes host APIs independently of a plugin's mutable globals.

func HookHTTPResponse

func HookHTTPResponse(resp *http.Response) map[string]any

HookHTTPResponse is the {status, headers} argument of the parse hooks for an upstream reply: the first value of each header.

func NewAPIReservedKeys

func NewAPIReservedKeys() []string

NewAPIReservedKeys returns, sorted, the plugin keys new-api refuses because they collide with its own paths, for another host that warns authors of plugins meant for new-api too. Each call returns a new slice.

func NormalizeRouteMethod

func NormalizeRouteMethod(method string) (string, error)

NormalizeRouteMethod returns the canonical spelling of a plugin route method, rejecting methods routes may not use.

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 ParseFileReference

func ParseFileReference(ref string) (field string, index int, ok bool)

ParseFileReference resolves a ref produced by FileReference back to the multipart field and the zero-based file index within that field.

func RedactCredentialLines

func RedactCredentialLines(key string) string

RedactCredentialLines replaces every credential line of a channel key with its summary, so the key can be shown to an administrator.

func ResolveRouteAction

func ResolveRouteAction(route Route, resolvedAction string) string

func RoutePathShape

func RoutePathShape(routePath string) (string, error)

RoutePathShape is a route path with every parameter name left out (":" for a parameter, "*" for a catch-all): two routes of one method and shape match the same requests.

func SetParamOverrideFunc

func SetParamOverrideFunc(fn ParamOverrideFunc)

SetParamOverrideFunc sets the function utils.paramOverride calls and keeps the rest of the host; nil removes it.

func SplitProviderConverter

func SplitProviderConverter(converter string) (hostConverter string, hooks bool)

SplitProviderConverter returns the converter the host runs for a route converter and whether the plugin's convert hooks run too: "plugin" is "none" with the hooks, "<converter>+plugin" that converter with the hooks, and any other value itself without them.

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 UTF16Len

func UTF16Len(text string) int

UTF16Len is the length of text in UTF-16 code units, as JavaScript counts a string.

func UsesSubmitEventDelta

func UsesSubmitEventDelta(meta Meta, engine *Engine) bool

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 ValidArtifactKey

func ValidArtifactKey(key string) bool

ValidArtifactKey reports whether key may name a task artifact.

func ValidPluginKey

func ValidPluginKey(key string) bool

ValidPluginKey checks the canonical identifier accepted by plugin manifests.

func ValidateIconImage

func ValidateIconImage(mediaType string, data []byte) error

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 ValidateJSONPath

func ValidateJSONPath(path []any) error

ValidateJSONPath checks a path into a JSON document by the rules of a JSON change path: at most 32 segments, each a string key or a non-negative integer array index.

func ValidateRequestHeaders

func ValidateRequestHeaders(headers map[string]string) error

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

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 ValidateServiceURL

func ValidateServiceURL(requestURL string, hosts []string) error

ValidateServiceURL checks a utils.fetch URL of a hook that runs without a channel: its host must be one of hosts, each `host` or `host:port`.

func ValidateV1Meta

func ValidateV1Meta(meta Meta) error

ValidateV1Meta applies the metadata constraints published in v1.schema.json to administrator uploads.

func WithFetcher

func WithFetcher(ctx context.Context, fetcher Fetcher) context.Context

WithFetcher makes utils.fetch available to the hook called with ctx.

Types

type Artifact

type Artifact struct {
	Key      string
	Type     string
	MimeType string
}

Artifact is one artifact listArtifacts names.

type Attachment

type Attachment struct {
	Ref        string
	Kind       string
	Mime       string
	Size       int
	Filename   string
	URL        string
	Path       string
	Rewritable bool
}

Attachment is one entry of utils.attachments. Ref is "" for a file that is not in the request: a file id, a file URL or a remote URL, which URL holds when the body gives one. Path is the JSON Pointer of the attachment in the body a hook reads, or the field name of a multipart file. Rewritable marks a text file a media.text effect may rewrite.

type AuthMeta

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

type AuthorMeta

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

type BalanceResult

type BalanceResult struct {
	Amount    *float64        `json:"amount"`
	Currency  string          `json:"currency"`
	Unlimited bool            `json:"unlimited"`
	Windows   []BalanceWindow `json:"windows"`
}

BalanceResult is a channel balance: the amount in currency, null when the vendor reports none, unlimited, and the quota windows of the account.

type BalanceStep

type BalanceStep struct {
	Balance *BalanceResult
	Next    *ConvertedRequest
	State   json.RawMessage
}

BalanceStep is a parseBalance result: the balance, or the Next request with the State its parse reads.

type BalanceWindow

type BalanceWindow struct {
	Name    LocalizedText `json:"name"`
	Used    float64       `json:"used"`
	Limit   float64       `json:"limit"`
	Unit    string        `json:"unit,omitempty"`
	ResetAt int64         `json:"resetAt,omitempty"`
}

BalanceWindow is one quota window: what is used of the limit in unit, and when it resets in unix seconds, 0 when the vendor does not say.

type BatchResultItem

type BatchResultItem struct {
	TaskID     string `json:"taskId"`
	Action     string `json:"action"`
	Status     string `json:"status"`
	Progress   string `json:"progress"`
	Reason     string `json:"reason"`
	URL        string `json:"url"`
	SubmitTime int64  `json:"submitTime"`
	StartTime  int64  `json:"startTime"`
	FinishTime int64  `json:"finishTime"`
	Data       any    `json:"data"`
	State      any    `json:"state"`
}

BatchResultItem is one task of a parseBatchResult result. State is the hook's value, which may be a host value.

type BodyKind

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

type ConfigSchema

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

ConfigSchema is meta.configSchema, the schema of the config of a request processing instance, or meta.channelConfig, the schema of a channel's plugin config. It is decoded once when the plugin loads and never changes; its JSON is the normalized schema, with properties in the order the plugin declares them.

func (*ConfigSchema) KeywordFields

func (s *ConfigSchema) KeywordFields() []string

KeywordFields returns the names of the keywords format properties.

func (*ConfigSchema) MarshalJSON

func (s *ConfigSchema) MarshalJSON() ([]byte, error)

type ConvertInput

type ConvertInput struct {
	Path   string
	Body   []byte
	Form   *RequestForm
	Model  string
	Stream bool
}

ConvertInput is the client request convertRequest converts: its JSON body, or Form for a multipart form. Path is the client path of its route.

type ConvertedForm

type ConvertedForm struct {
	Fields map[string][]string
	Files  []ConvertedFormFile
}

ConvertedForm is the multipart form of a convertRequest result.

type ConvertedFormFile

type ConvertedFormFile struct {
	Field       string
	From        string
	Filename    string
	ContentType string
}

ConvertedFormFile is a client file sent as Field of a converted form. From is the file's reference; an empty Filename or ContentType keeps the client file's.

type ConvertedRequest

type ConvertedRequest struct {
	Body        []byte
	Form        *ConvertedForm
	File        string
	ContentType string
	Path        string
	URL         string
	// Method is empty for the default: the client's method for the first
	// request, POST for a next request with a body and GET for one without.
	Method  string
	Headers map[string]string
	// Stream is the plugin's choice of reading the response as a stream, nil
	// when it leaves it to the host.
	Stream *bool
	// NativeResponse hands a 2xx response to the route's handler as it came,
	// as a response of the route's upstream protocol, without convertResponse
	// or convertStreamEvent.
	NativeResponse bool
	// State is the ctx.state of the hooks that read the response, nil when
	// the result sets none.
	State     json.RawMessage
	WebSocket *WebSocketRequest
	// Delay is the wait before a next request is sent.
	Delay time.Duration
}

ConvertedRequest is a request a hook asks the host to send: the first request of a convertRequest result, a next request of a chain, or the buildBalanceRequest result. At most one of Body, Form, File and WebSocket is set: the upstream body, a multipart form the host writes, the reference of the client file that is the whole body, or an upstream WebSocket session. ContentType is empty for the default; Path or URL replaces the route's upstream address, both empty to keep it.

func (ConvertedRequest) HasBody

func (r ConvertedRequest) HasBody() bool

HasBody reports whether the request carries a body, a form or a file.

type ConvertedResponse

type ConvertedResponse struct {
	Body        []byte
	ContentType string
	Next        *ConvertedRequest
	State       json.RawMessage
	Tools       map[string]int
}

ConvertedResponse is a convertResponse result: the body the client gets and its content type, or the Next request of a chain with the State the next call reads. Tools are the tool calls the response counts.

type Credential

type Credential struct {
	Type       string            `json:"type"`
	Plugin     string            `json:"plugin"`
	Data       json.RawMessage   `json:"data"`
	Headers    map[string]string `json:"headers"`
	Query      map[string]string `json:"query"`
	ExpiresAt  int64             `json:"expires_at"`
	AccountID  string            `json:"account_id"`
	Label      string            `json:"label"`
	NeedsLogin bool              `json:"needs_login"`
}

Credential is one plugin credential, stored as a compact JSON line of a channel key. Data is opaque to the host and reaches only the plugin's own credential hooks; Headers and Query go upstream with every request.

func ParseCredential

func ParseCredential(line string) (*Credential, bool)

ParseCredential reads one channel key line as a plugin credential. Any other line is a static key.

func (Credential) ExpiresWithin

func (c Credential) ExpiresWithin(now time.Time, margin time.Duration) bool

ExpiresWithin reports whether the credential has an expiry and reaches it within margin of now.

func (Credential) Line

func (c Credential) Line() (string, error)

Line encodes the credential as one compact JSON line.

func (Credential) Summary

func (c Credential) Summary() CredentialSummary

Summary returns the credential without its data, headers and query.

type CredentialContext

type CredentialContext struct {
	BaseURL    string
	Credential json.RawMessage
	APIKey     string
	Config     json.RawMessage
	Token      json.RawMessage
}

CredentialContext is the ctx of a hook that may read the channel's credential: Credential is the wrapper's data, or APIKey a static key line. Config is the channel's plugin config as ChannelConfigFor returns it, and Token the exchangeKey token of a static key line, nil without one.

type CredentialResult

type CredentialResult struct {
	Credential json.RawMessage
	Headers    map[string]string
	Query      map[string]string
	ExpiresAt  int64
	AccountID  string
	Label      string
	// Relogin is refresh's answer that only a new login can restore access.
	Relogin bool
}

CredentialResult is what a finished login and refresh return.

type CredentialSummary

type CredentialSummary struct {
	Type       string `json:"type"`
	Plugin     string `json:"plugin"`
	AccountID  string `json:"account_id"`
	Label      string `json:"label"`
	ExpiresAt  int64  `json:"expires_at"`
	NeedsLogin bool   `json:"needs_login"`
}

CredentialSummary is the part of a credential an administrator may see.

type DecodedRequest

type DecodedRequest struct {
	// Value is the hook's result and Result the same value when it is an
	// object, else nil.
	Value  any
	Result map[string]any
	// RequestBodyText is the JSON.stringify text of the result's
	// requestBody for a plugin that preserves JSON order, else nil.
	RequestBodyText json.RawMessage
}

DecodedRequest is what a decoder returns: a native route's decode hook or a protocol's decodeRequest.

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 engine-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) CallInto

func (e *Engine) CallInto(ctx context.Context, target any, exportName string, args ...any) error

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

func (e *Engine) CallPathJSONInto(ctx context.Context, target any, exportName string, members []string, args ...any) error

CallPathJSONInto is CallJSONInto for a function nested below an exported object, such as native.render: objects keep their member order.

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

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

CallPathWithMembersJSON is CallPathWithMemberJSON for a result that may carry its JSON value at one of several places: it returns the text of the first of paths the result has. A path names nested members with dots, such as "next.body".

func (*Engine) Export

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

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

func (e *Engine) HasExport(exportName string) bool

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 ExchangedToken

type ExchangedToken struct {
	Token     json.RawMessage
	ExpiresAt int64
}

ExchangedToken is an exchangeKey result: the token the relay hooks get as ctx.token, and when it expires in unix seconds, 0 for no expiry.

type FetchRequest

type FetchRequest struct {
	Hook    string // the calling hook, filled by the engine for logs and errors
	URL     string
	Method  string
	Headers map[string]string
	// Body is the text a POST sends; only postFetchHooks may POST.
	Body string
	// BodyStream, when set, is what the POST sends instead of Body: Body
	// with the media refs it names replaced by their data URLs, BodySize
	// bytes long.
	BodyStream io.Reader
	BodySize   int64
	// contains filtered or unexported fields
}

func (FetchRequest) ResponseBodyLimit

func (r FetchRequest) ResponseBodyLimit() int64

ResponseBodyLimit is the number of response bytes this fetch can accept.

type FetchResponse

type FetchResponse struct {
	Status  int
	Headers map[string]string
	Body    []byte
}

type Fetcher

type Fetcher func(ctx context.Context, request FetchRequest) (FetchResponse, error)

Fetcher sends one utils.fetch request with the network deadline in ctx. It reads at most request.ResponseBodyLimit()+1 bytes and returns any bytes it read before an error so the engine can count them.

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.

func ReplayFixtureWith

func ReplayFixtureWith(ctx context.Context, compile func(source string, options Options) (*LoadedPlugin, error), source string, data []byte) (FixtureReport, error)

ReplayFixtureWith is ReplayFixture with the host's own admission: compile loads the plugin, for example CompilePlugin followed by the host's route checks.

type HookContext

type HookContext struct {
	BaseURL string
	Path    string
	Config  json.RawMessage
	Token   json.RawMessage
	State   json.RawMessage
}

HookContext is the ctx of a relay hook: the channel base URL, the client path of the route, the channel's plugin config, the exchangeKey token of a static key line and, for the hooks that read a response, the state the plugin carries through a chain or a stream.

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 Host

type Host struct {
	// MemoryLimit is the memory, in bytes, the JavaScript of one hook call
	// may keep; 0 or less means no limit. Nil keeps 512 MiB. It is read when
	// a runtime is created.
	MemoryLimit func() int64
	// MaxRequestBodyBytes bounds a request a converter builds; 0 or less
	// keeps 128 MiB. It is read on every conversion.
	MaxRequestBodyBytes func() int
	// MaxStreamEventBytes bounds a converter's state and the event data of
	// one call; 0 or less keeps 128 MiB. It is read on every conversion.
	MaxStreamEventBytes func() int
	// ReservedRouteNamespaces are host paths a plugin route may not enter,
	// such as "/v1/tasks". A key may not be the first segment of one.
	ReservedRouteNamespaces []string
	// ReservedKeys are other keys a plugin may not take, such as "api".
	ReservedKeys []string
	// ParamOverride runs utils.paramOverride; nil leaves the utility
	// unavailable on this host.
	ParamOverride ParamOverrideFunc
	// Debug receives the console output of plugins and other debug lines;
	// nil discards them.
	Debug func(ctx context.Context, format string, args ...any)
}

Host is what the gateway running the plugins sets for all of them. A zero member keeps the default the API v1 document gives.

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

func NewJSONState(limit int) *JSONState

func (*JSONState) Apply

func (s *JSONState) Apply(ctx context.Context, changes any) (err error)

Apply accepts a bounded batch of set, append and appendText operations. Failure invalidates the stream: callers must discard the state rather than continue after an error. No partially updated result may be published.

func (*JSONState) Value

func (s *JSONState) Value() (any, error)

Value returns the final ordinary JSON tree and verifies the incremental byte accounting against the configured codec before callers can persist it.

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.

func (*LoadedPlugin) CallBuildBalanceRequest

func (p *LoadedPlugin) CallBuildBalanceRequest(ctx context.Context, hookCtx CredentialContext) (ConvertedRequest, error)

CallBuildBalanceRequest runs buildBalanceRequest(ctx): the first request of a balance query, with the state parseBalance starts from.

func (*LoadedPlugin) CallCheckKey

func (p *LoadedPlugin) CallCheckKey(ctx context.Context, baseURL string, config json.RawMessage, key string) (LocalizedText, error)

CallCheckKey runs checkKey(ctx, key) on a static key line an administrator saves. It returns nil for a good key, or the plugin's message for the administrator.

func (*LoadedPlugin) CallConvertRequest

func (p *LoadedPlugin) CallConvertRequest(ctx context.Context, hookCtx HookContext, input ConvertInput) (ConvertedRequest, error)

CallConvertRequest runs convertRequest(ctx, {body, model, stream}), or convertRequest(ctx, {form, model, stream}) for a multipart client request.

func (*LoadedPlugin) CallConvertResponse

func (p *LoadedPlugin) CallConvertResponse(ctx context.Context, hookCtx HookContext, status int, headers map[string]string, body []byte) (ConvertedResponse, *UpstreamError, error)

CallConvertResponse runs convertResponse(ctx, {status, headers, body}) on an upstream response of the route at hookCtx.Path, with bodyBase64 in place of body when the body is not text, and hookCtx.State as ctx.state. It returns the reply in the client protocol, the next request of a chain, or the error the plugin made of the response.

func (*LoadedPlugin) CallConvertStreamEvent

func (p *LoadedPlugin) CallConvertStreamEvent(ctx context.Context, hookCtx HookContext, event *StreamEvent, done bool) (StreamResult, json.RawMessage, *UpstreamError, error)

CallConvertStreamEvent runs convertStreamEvent(ctx, {event?, data}) on the stream of the route at hookCtx.Path, {dataBase64} for a binary frame, or with done the final call ({done: true}). hookCtx.State is ctx.state; the returned state replaces it only when the result carries one. A result with an error returns that error and keeps the state.

func (*LoadedPlugin) CallCredentialRejected

func (p *LoadedPlugin) CallCredentialRejected(ctx context.Context, hookCtx HookContext, status int, headers map[string]string, body string) (bool, error)

CallCredentialRejected runs credentialRejected(ctx, {status, headers, body}) for a non-2xx response.

func (*LoadedPlugin) CallExchangeKey

func (p *LoadedPlugin) CallExchangeKey(ctx context.Context, hookCtx CredentialContext) (ExchangedToken, *UpstreamError, error)

CallExchangeKey runs exchangeKey(ctx) for a static key line: hookCtx has the base URL, the plugin config and the key. It returns the token or the error the plugin made of the vendor's answer.

func (*LoadedPlugin) CallListArtifacts

func (p *LoadedPlugin) CallListArtifacts(ctx context.Context, task map[string]any) ([]Artifact, error)

CallListArtifacts runs listArtifacts with the artifact context of a task and validates the list. An invalid list is a *ResultError; other errors are the hook's.

func (*LoadedPlugin) CallLogin

func (p *LoadedPlugin) CallLogin(ctx context.Context, baseURL string, login LoginContext, credential json.RawMessage, input any) (LoginStep, error)

CallLogin runs login(ctx, input). credential is the wrapper data when the administrator logs in again on an existing credential.

func (*LoadedPlugin) CallParseBalance

func (p *LoadedPlugin) CallParseBalance(ctx context.Context, hookCtx CredentialContext, state json.RawMessage, response UpstreamResponse) (BalanceStep, error)

CallParseBalance runs parseBalance(ctx, {status, headers, body}). A returned {error} is an error with the plugin's message.

func (*LoadedPlugin) CallParseBatchResult

func (p *LoadedPlugin) CallParseBatchResult(ctx context.Context, batch map[string]any, body any, response map[string]any) ([]BatchResultItem, error)

CallParseBatchResult runs parseBatchResult with the batch query context, the upstream body and HookHTTPResponse. A result of the wrong shape is a *ResultError; other errors are the hook's.

func (*LoadedPlugin) CallParseSubmitResponse

func (p *LoadedPlugin) CallParseSubmitResponse(ctx context.Context, driver map[string]any, response SubmitResponse) (SubmitResult, error)

CallParseSubmitResponse runs parseSubmitResponse with the driver context. A result of the wrong shape, without a taskId or with clientResponse (ErrSubmitClientResponse) is a *ResultError; other errors are the hook's.

func (*LoadedPlugin) CallParseTaskResult

func (p *LoadedPlugin) CallParseTaskResult(ctx context.Context, query map[string]any, body any, response map[string]any) (TaskResult, error)

CallParseTaskResult runs parseTaskResult with the task query context, the upstream body (parsed JSON, else text) and HookHTTPResponse. A result of the wrong shape is a *ResultError; other errors are the hook's.

func (*LoadedPlugin) CallPrepareRequest

func (p *LoadedPlugin) CallPrepareRequest(ctx context.Context, hookCtx HookContext, input PrepareInput) (PreparedRequest, error)

CallPrepareRequest runs prepareRequest(ctx, req).

func (*LoadedPlugin) CallProtocolDecode

func (p *LoadedPlugin) CallProtocolDecode(ctx context.Context, admissionTimeout time.Duration, protocol string, request ProtocolRequestContext) (DecodedRequest, error)

CallProtocolDecode runs protocols[protocol].decodeRequest on the request of a host protocol.

func (*LoadedPlugin) CallRefresh

func (p *LoadedPlugin) CallRefresh(ctx context.Context, hookCtx CredentialContext) (CredentialResult, error)

CallRefresh runs refresh(ctx).

func (*LoadedPlugin) CallReply

func (p *LoadedPlugin) CallReply(ctx context.Context, tctx TransformContext, stream bool, outputs []ReplyOutput) (ReplyResult, error)

CallReply runs the reply hook with tctx.Stage "reply" on outputs and checks the result: each mask names an output of the call and lies within its text. utils.fetch uses the Fetcher of ctx. Every error is a *TransformError.

func (*LoadedPlugin) CallReport

func (p *LoadedPlugin) CallReport(ctx context.Context, tctx TransformContext, record json.RawMessage) error

CallReport runs the report hook with tctx.Stage "report" on record, the JSON of a finished request. The return value is ignored. utils.fetch uses the Fetcher of ctx. Every error is a *TransformError.

func (*LoadedPlugin) CallRequestDescriptor

func (p *LoadedPlugin) CallRequestDescriptor(ctx context.Context, hook string, args ...any) (RequestDescriptor, error)

CallRequestDescriptor runs a request-building hook. A plugin that preserves JSON order has its descriptor decoded from the JSON.stringify text of the result, with the body kept as that text (BodyText) for the upstream.

func (*LoadedPlugin) CallRevoke

func (p *LoadedPlugin) CallRevoke(ctx context.Context, hookCtx CredentialContext) error

CallRevoke runs revoke(ctx). Its result is ignored.

func (*LoadedPlugin) CallRouteDecode

func (p *LoadedPlugin) CallRouteDecode(ctx context.Context, admissionTimeout time.Duration, decode string, request RouteRequestContext) (DecodedRequest, error)

CallRouteDecode runs native[decode] on the request of a native route. admissionTimeout is as for Engine.CallPathWithAdmissionTimeout; 0 is the default.

func (*LoadedPlugin) CallScheduled

func (p *LoadedPlugin) CallScheduled(ctx context.Context, hookCtx ScheduledContext) (ScheduledResult, error)

CallScheduled runs scheduled(ctx). The caller checks the stored credential line's size and applies the result while holding the channel lock.

func (*LoadedPlugin) CallSignRequest

func (p *LoadedPlugin) CallSignRequest(ctx context.Context, hookCtx CredentialContext, method, requestURL string, headers map[string]string, bodySHA256 string) (SignResult, error)

CallSignRequest runs signRequest(ctx, {method, url, headers, bodySha256}).

func (*LoadedPlugin) CallSubmitEvent

func (p *LoadedPlugin) CallSubmitEvent(ctx context.Context, hook string, driver map[string]any, event SubmitEvent, previous any) (SubmitEventResult, error)

CallSubmitEvent runs hook, parseSubmitEvent or parseSubmitEventDelta (see UsesSubmitEventDelta), on one event with the previous state, and checks the result's shape and state size. Errors are those of the hook or of an invalid result.

func (*LoadedPlugin) CallTransform

CallTransform runs one stage hook, tctx.Stage, and validates the result shape. tctx.Config, req.Body and req.Headers are passed to JavaScript without copies, so the caller must not change them afterwards. Every error is a *TransformError. utils.fetch uses the Fetcher of ctx in ingress and egress; request and outbound have no network.

func (*LoadedPlugin) CallUsage

func (p *LoadedPlugin) CallUsage(ctx context.Context, hook string, args ...any) (map[string]any, error)

CallUsage runs a usage hook (extractUsage, extractUsageOnSubmit, extractUsageOnComplete) and returns its facts as the plugin reported them: nil for a null or undefined result. The host validates and bounds them. A result that is not an object is a *ResultError; other errors are the hook's.

func (*LoadedPlugin) ChannelConfigFor

func (p *LoadedPlugin) ChannelConfigFor(stored json.RawMessage) json.RawMessage

ChannelConfigFor returns a channel's stored plugin config as its hooks get it: the properties meta.channelConfig declares, with the defaults of absent ones applied. A stored value the schema no longer accepts, after a plugin update, reaches the plugin as stored, as a request processing instance's config does; the next save checks it again. Without a schema it is {}.

func (*LoadedPlugin) ConfigURLHosts

func (p *LoadedPlugin) ConfigURLHosts(config json.RawMessage) []string

ConfigURLHosts returns the host, with its port when it has one, of every non-empty url format value of an instance config: the hosts utils.fetch may address besides meta.allowedHosts. config is a validated config.

func (*LoadedPlugin) HasProviderHook

func (p *LoadedPlugin) HasProviderHook(name string) bool

HasProviderHook reports whether the plugin exports a provider hook. It runs no JavaScript.

func (*LoadedPlugin) TransformHooks

func (p *LoadedPlugin) TransformHooks() []string

TransformHooks returns the stage hooks the plugin exports, in TransformStages order, then ReplyHook and ReportHook when it exports them; nil when it has no request processing part.

func (*LoadedPlugin) ValidateChannelConfig

func (p *LoadedPlugin) ValidateChannelConfig(config json.RawMessage) (json.RawMessage, error)

ValidateChannelConfig checks the plugin config an administrator saves on a channel against meta.channelConfig and returns what the channel stores: the config without the top-level properties the schema does not declare and without the defaults of absent ones, which apply when it is read. An empty config reads as {}; without a schema the result is always {}.

func (*LoadedPlugin) ValidateConfig

func (p *LoadedPlugin) ValidateConfig(config json.RawMessage) (json.RawMessage, error)

ValidateConfig checks an instance config against meta.configSchema and returns it with the defaults of absent properties applied. Without a schema only {} is valid; an empty config reads as {}. When the plugin exports validateConfig, it then runs on that result, and its throw is the error.

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

func (t LocalizedText) Text(lang string) string

Text returns the text for lang: its own locale, then the bare language, then the first regional locale of that language in sorted order, then en.

func (*LocalizedText) UnmarshalJSON

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

type LoginContext

type LoginContext struct {
	State         string
	Nonce         string
	CodeVerifier  string
	CodeChallenge string
	RedirectURI   string
	Session       json.RawMessage
	Config        json.RawMessage
}

LoginContext is ctx.login: the values the host generated for this login. Config is not part of it: it is ctx.config, the channel's plugin config.

type LoginField

type LoginField struct {
	Name        string        `json:"name"`
	Label       LocalizedText `json:"label"`
	Type        string        `json:"type"`
	Required    bool          `json:"required"`
	Placeholder LocalizedText `json:"placeholder,omitempty"`
	Description LocalizedText `json:"description,omitempty"`
}

LoginField is one input of a fields step.

type LoginStep

type LoginStep struct {
	Type                    string
	URL                     string
	Issuer                  string
	Hint                    LocalizedText
	UserCode                string
	VerificationURI         string
	VerificationURIComplete string
	Interval                int
	ExpiresIn               int
	Fields                  []LoginField
	// Session is nil when the step returned none, which keeps the current
	// session; JSON null clears it.
	Session json.RawMessage
	Result  *CredentialResult
}

LoginStep is one result of login: the next step, or done with the credential.

type MediaInfo

type MediaInfo struct {
	Kind       string
	Mime       string
	Size       int
	Filename   string
	Width      int
	Height     int
	Rewritable bool
}

MediaInfo is the result of utils.media; Width and Height are 0 when the media is not an image the host reads.

type MediaSource

type MediaSource interface {
	// Attachments lists the request's attachments in body order.
	Attachments() []Attachment
	// Media describes the media ref names; false when ref is not one of
	// the call's.
	Media(ref string) (MediaInfo, bool)
	// MediaText reads the text of the media ref names, at most maxChars
	// UTF-16 code units; false when ref is not one of the call's.
	MediaText(ctx context.Context, ref string, maxChars int) (MediaText, bool)
	// FetchBody returns body with each JSON string that equals a ref of the
	// call replaced by that media's data URL, and its length; a nil reader
	// when body names no ref.
	FetchBody(body string) (io.Reader, int64, error)
}

MediaSource is a stage hook's access to the attachments of its request: the inline media and multipart files a hook reads as "[media:N]" refs, and the files the body names by id or URL. utils.attachments, utils.media and utils.mediaText read it, and utils.fetch sends the refs a body names. The host sets one per hook call in TransformContext.Media; the bytes never reach JavaScript.

type MediaText

type MediaText struct {
	Text      string
	Truncated bool
	Unchecked string
}

MediaText is the result of utils.mediaText: Text, cut short when Truncated, or the reason the text was not read in Unchecked.

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"`
	NameI18n             LocalizedText               `json:"name_i18n,omitempty"` // the locales of a name given as an object; Name is its en text
	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"`
	// Relay is the provider part: the Advanced Custom routes a type-61
	// channel bound to the plugin serves.
	Relay []dto.AdvancedCustomRoute `json:"relay,omitempty"`
	// ConfigSchema is the schema of a request processing instance's config.
	ConfigSchema *ConfigSchema `json:"configSchema,omitempty"`
	// ChannelConfig is the schema of the plugin config of a type-61 channel
	// bound to the plugin, stored in its settings as plugin_config.
	ChannelConfig *ConfigSchema `json:"channelConfig,omitempty"`
	// KeyHint is the hint and example of the channel key field.
	KeyHint LocalizedText `json:"keyHint,omitempty"`
	// Optional lets a request skip an instance of the plugin that fails at a
	// stage; without it the failure stops the request.
	Optional bool `json:"optional,omitempty"`
	// Scope is the range of requests the plugin is made for, which an
	// administrator confirms once to run an instance there.
	Scope *TransformScope `json:"scope,omitempty"`
	// Samples are the requests the request plugin editor offers to try the
	// plugin with.
	Samples []Sample `json:"samples,omitempty"`
	// contains filtered or unexported fields
}

func (Meta) ChannelConfigSchemaJSON

func (m Meta) ChannelConfigSchemaJSON() json.RawMessage

ChannelConfigSchemaJSON returns meta.channelConfig as normalized JSON text, nil when the plugin declares none.

func (Meta) ChannelRelayConfig

func (m Meta) ChannelRelayConfig(config []byte) *dto.AdvancedCustomConfig

ChannelRelayConfig is RelayConfig for a channel: an upstream_path that starts with {config.<name>} starts with that address of the channel's plugin config instead, or is relative to the channel base URL when the address is empty. config is the config as ChannelConfigFor returns it.

func (Meta) Clone

func (m Meta) Clone() Meta

Clone returns a copy of m that shares no slice or map with it.

func (Meta) ConfigSchemaJSON

func (m Meta) ConfigSchemaJSON() json.RawMessage

ConfigSchemaJSON returns meta.configSchema as normalized JSON text, nil when the plugin declares none.

func (Meta) HasProviderPart

func (m Meta) HasProviderPart() bool

HasProviderPart reports whether the plugin declares relay routes.

func (Meta) HasTaskPart

func (m Meta) HasTaskPart() bool

HasTaskPart reports whether the plugin is a task driver: it exports buildSubmitRequest.

func (Meta) HasTransformPart

func (m Meta) HasTransformPart() bool

HasTransformPart reports whether the plugin exports a stage hook.

func (Meta) JSONTextMember

func (m Meta) JSONTextMember(member string) string

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

func (m Meta) ModelListRoute() (dto.AdvancedCustomRoute, bool)

ModelListRoute returns the /v1/models relay route, with the converter as the manifest declares it.

func (Meta) PreservesJSONOrder

func (m Meta) PreservesJSONOrder() bool

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

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

ProtocolSupports reports whether the named protocol claim includes mode.

func (Meta) RelayConfig

func (m Meta) RelayConfig() *dto.AdvancedCustomConfig

RelayConfig returns the relay routes as the Advanced Custom configuration of one request. A plugin-converter route reaches the Advanced Custom code as a native route of its client protocol, and a chained one as a route of its registered converter; the provider adaptor converts around it.

func (Meta) RelayRoute

func (m Meta) RelayRoute(requestPath, model string) (dto.AdvancedCustomRoute, bool)

RelayRoute returns the relay route serving requestPath for model, with the converter as the manifest declares it.

func (Meta) RelaysModel

func (m Meta) RelaysModel(model string) bool

RelaysModel reports whether a relay route accepts model for client requests: the plugin serves the model on chat paths, not only as a task. The model list and balance routes accept every model and serve none.

func (Meta) ServesResponsesWebSocket

func (m Meta) ServesResponsesWebSocket(model string) bool

ServesResponsesWebSocket reports whether a Responses WebSocket session for model may run on the relay routes: the /v1/responses route serving it has no converter, so the session forwards native events as Advanced Custom does. An empty model asks whether any route of that path qualifies.

func (Meta) SupportsUpstream

func (m Meta) SupportsUpstream(kind string) bool

SupportsUpstream reports whether the driver handles channels of the given upstream kind. The vendor kind is implied for every plugin.

func (Meta) TransformHooks

func (m Meta) TransformHooks() []string

TransformHooks returns the stage hooks the plugin exports, in TransformStages order, then ReplyHook and ReportHook when it exports them; nil when it has no request processing part.

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 Options

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

type ParamOverrideFunc

type ParamOverrideFunc func(ctx TransformContext, body json.RawMessage, override json.RawMessage) (result json.RawMessage, err error)

ParamOverrideFunc runs the host parameter override for utils.paramOverride with the calling hook's context. result is the JSON text utils.paramOverride returns to JS: {body, headers?} or {reject}.

type PrepareInput

type PrepareInput struct {
	Path         string
	UpstreamPath string
	Model        string
	Stream       bool
	Body         []byte
	Headers      map[string]string
}

PrepareInput is the request prepareRequest sees.

type PreparedRequest

type PreparedRequest struct {
	Effects json.RawMessage
	Path    string
	URL     string
}

PreparedRequest is a prepareRequest result: the JSON text of its effects, nil when it returned none, and the path or address the request goes to in place of the route's, both empty to keep it.

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"`
	// 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 ReplyMask

type ReplyMask struct {
	Index    int
	Start    int
	End      int
	Category string
}

ReplyMask is a span of one output's Text to replace, in UTF-16 code units.

type ReplyOutput

type ReplyOutput struct {
	Index  int
	Text   string
	Offset int
	Final  bool
}

ReplyOutput is one answer a reply hook reads: Text is what this instance has not passed on yet, Offset the UTF-16 code units of the answer it passed on before Text, and Final that no more text follows.

type ReplyResult

type ReplyResult struct {
	Action   string // "continue", "pass" or "stop"
	Masks    []ReplyMask
	Hold     int
	Findings []TransformFinding
	Notice   LocalizedText
	Code     string
	Message  string
}

ReplyResult is a reply hook result whose shape CallReply checked.

type RequestDescriptor

type RequestDescriptor struct {
	ResponseType   string            `json:"responseType"`
	URL            string            `json:"url"`
	Method         string            `json:"method"`
	Headers        map[string]string `json:"headers"`
	Body           any               `json:"body"`
	Credentialless bool              `json:"credentialless"`
	Action         string            `json:"action"`
	Model          string            `json:"model"`
	RewriteModel   string            `json:"rewriteModel"`
	BodyType       string            `json:"bodyType"`
	Parts          []RequestPart     `json:"parts"`

	// ContentPath and MimeType are read from buildContentRequest only: the
	// artifact's bytes are a base64 string at that path of the JSON reply.
	ContentPath []any  `json:"contentPath"`
	MimeType    string `json:"mimeType"`
	// BodyText is the body as JSON.stringify wrote it, for a plugin that
	// preserves JSON order: the upstream gets the members in that order.
	BodyText json.RawMessage `json:"-"`
}

RequestDescriptor is the request a request-building hook returns (buildSubmitRequest, buildQueryRequest, buildBatchQueryRequest, buildContentRequest).

type RequestFile

type RequestFile struct {
	Field       string
	Filename    string
	ContentType string
	Size        int64
}

RequestFile is one uploaded file of a multipart client request.

type RequestForm

type RequestForm struct {
	Fields map[string][]string
	Files  []RequestFile
}

RequestForm is a multipart client request as convertRequest sees it: its fields, and its files without their content.

type RequestPart

type RequestPart struct {
	Name     string `json:"name"`
	Value    any    `json:"value"`
	FileRef  string `json:"fileRef"`
	Filename string `json:"filename"`
}

RequestPart is one part of a multipart request descriptor.

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

func (Route) TaskIDInQuery

func (r Route) TaskIDInQuery() bool

TaskIDInQuery reports whether a query route reads its task id from the query string, as the MiniMax v1 query does (?task_id=): the route's path has no parameter named taskIdParam.

type RouteBinding

type RouteBinding struct {
	Plugin    *LoadedPlugin
	Route     Route
	Pinned    bool
	OwnPrefix bool
}

RouteBinding is one address a plugin serves. Besides each declared route the host registers its copy under /{key} (Pinned), which always reaches this plugin. A declared route whose first segment is the key, or a proper prefix of it (/ali for alibaba, /suno for sunoapi), already does (OwnPrefix) and gets no copy.

func PluginRouteBindings

func PluginRouteBindings(plugin *LoadedPlugin) []RouteBinding

PluginRouteBindings returns the addresses plugin serves: each declared route and, unless the route lives under the plugin's own prefix, its /{key} copy. A plugin that declares the copy's address itself (TypeSafe 1.2.0 declares /v1/systemone and /typesafe/v1/systemone) serves it by that declaration.

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"`
	// Headers is the client's request headers without gateway credentials,
	// which hooks read as requestHeaders.
	Headers     map[string]string `json:"-"`
	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, query and headers 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 RouteType

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

type Sample

type Sample struct {
	Name LocalizedText `json:"name"`
	// Lang is the base language of the sample text, "" for any language.
	Lang   string          `json:"lang,omitempty"`
	Format string          `json:"format"`
	Body   json.RawMessage `json:"body"`
	// Reply is a sample assistant answer for a plugin's reply check.
	Reply string `json:"reply,omitempty"`
}

Sample is one entry of meta.samples: a request the request plugin editor offers to try the plugin with. Body is the request body as the plugin wrote it, members in their order. Samples carry text only; the console supplies images.

type ScheduledContext

type ScheduledContext struct {
	CredentialContext
	Reason         string
	KeyStatus      string
	DisabledReason string
}

ScheduledContext is the current key and the trigger of scheduled.

type ScheduledResult

type ScheduledResult struct {
	Next       time.Duration
	Credential json.RawMessage
	Balance    *BalanceResult
	KeyStatus  string
	Notify     LocalizedText
}

ScheduledResult is the next interval and the changes scheduled requests for its current key. A nil Credential keeps its data; JSON null replaces it.

type SignResult

type SignResult struct {
	Headers map[string]string
	Query   map[string]string
}

SignResult is what signRequest adds to a request.

type StreamEvent

type StreamEvent struct {
	Event  string
	Data   string
	Binary []byte
}

StreamEvent is one server-sent event, or one line of a line-delimited stream when Event is empty. Event of a decoded AWS event stream message is its :event-type or :exception-type. Binary is a binary WebSocket frame, which convertStreamEvent gets as {dataBase64}; it is nil for text.

type StreamResult

type StreamResult struct {
	Events      []StreamEvent
	Chunks      [][]byte
	ContentType string
	Body        []byte
	HasBody     bool
	Send        []WebSocketMessage
	Close       bool
	Tools       map[string]int
}

StreamResult is a convertStreamEvent result besides its state: events for a streaming client, or Chunks of the binary body of a non-streaming one with their ContentType, or the whole Body of a non-streaming client (HasBody), which ends the stream. Send are messages for an upstream WebSocket and Close asks the host to close it. Tools are the tool calls the event counts.

type SubmitEvent

type SubmitEvent struct {
	Event string
	ID    string
	Data  string
}

SubmitEvent is one server-sent event of a submission stream.

type SubmitEventResult

type SubmitEventResult struct {
	State     any
	StateJSON json.RawMessage
	Done      bool
	Changes   any
}

SubmitEventResult is what parseSubmitEvent or parseSubmitEventDelta returns. State is the hook's value, which may be a host value, and StateJSON its encoding. Changes is set by parseSubmitEventDelta only.

type SubmitResponse

type SubmitResponse struct {
	StatusCode int
	Headers    map[string][]string
	Body       any
}

SubmitResponse is the upstream reply parseSubmitResponse reads.

type SubmitResult

type SubmitResult struct {
	TaskID    string
	TaskData  any
	Immediate *TaskResult
	// State is the JSON of the returned state; nil when the result has
	// none, a null one or one that does not encode.
	State json.RawMessage
}

SubmitResult is what parseSubmitResponse returns. TaskData is the hook's value, which may be a host value.

type TaskResult

type TaskResult struct {
	Code             int     `json:"code"`
	TaskID           string  `json:"taskId"`
	Status           string  `json:"status"`
	Progress         string  `json:"progress"`
	Reason           string  `json:"reason"`
	URL              string  `json:"url"`
	RemoteURL        string  `json:"remoteUrl"`
	CompletionTokens float64 `json:"completionTokens"`
	TotalTokens      float64 `json:"totalTokens"`
	// State is the JSON of the returned state; nil when the result has
	// none, a null one or one that does not encode.
	State json.RawMessage `json:"-"`
}

TaskResult is the task state parseTaskResult returns, and the immediate result of parseSubmitResponse. The token counts are the plugin's numbers, unbounded; the host converts them.

type TransformChannel

type TransformChannel struct {
	ID   int `json:"id"`
	Type int `json:"type"`
}

type TransformContext

type TransformContext struct {
	Stage         string `json:"stage"`
	Format        string `json:"format"`
	Path          string `json:"path"`
	Model         string `json:"model"`
	UpstreamModel string `json:"upstreamModel,omitempty"`
	// Group and User are left zero by a host without user groups or users,
	// and hooks then receive no ctx.group or ctx.user.
	Group   string            `json:"group,omitempty"`
	Channel *TransformChannel `json:"channel,omitempty"`
	Attempt int               `json:"attempt"`
	User    TransformUser     `json:"user,omitzero"`
	// Token is nil when the request has none.
	Token *TransformToken `json:"token,omitempty"`
	// Client and Session are host-specific: the client the host recognized
	// (empty, or "unknown", when none) and the client session (nil when
	// none). new-api leaves them unset.
	Client   string            `json:"client,omitempty"`
	Session  *TransformSession `json:"session,omitempty"`
	Instance TransformInstance `json:"instance"`
	Config   json.RawMessage   `json:"config"`
	// Media gives the hook's utils the request's attachments; nil when the
	// stage offers none.
	Media MediaSource `json:"-"`
	// contains filtered or unexported fields
}

TransformContext is the ctx a stage hook receives. Config is the instance config with the schema defaults applied (ValidateConfig).

type TransformError

type TransformError struct {
	Plugin string
	Hook   string
	Class  string
	// Thrown is the message a throwing hook threw. It may quote the request,
	// so it is not part of Error; only an administrator's dry run shows it.
	Thrown string
	// contains filtered or unexported fields
}

TransformError is a failed CallTransform. Its text names the plugin, the hook, the class and, for an invalid result, the member at fault, never a value: stage hooks read request bodies, and errors reach logs.

func (*TransformError) Error

func (e *TransformError) Error() string

func (*TransformError) Unwrap

func (e *TransformError) Unwrap() error

type TransformFinding

type TransformFinding struct {
	Rule     string `json:"rule"`
	Category string `json:"category,omitempty"`
	Path     string `json:"path,omitempty"`
	Count    int    `json:"count"`
}

type TransformInstance

type TransformInstance struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

type TransformMedia

type TransformMedia struct {
	Index    int    `json:"index"`
	Path     string `json:"path"`
	MimeType string `json:"mimeType"`
	Bytes    int    `json:"bytes"`
	Width    int    `json:"width,omitempty"`
	Height   int    `json:"height,omitempty"`
}

type TransformRequest

type TransformRequest struct {
	Body    json.RawMessage   `json:"body"`
	Headers map[string]string `json:"headers,omitempty"`
	Media   []TransformMedia  `json:"media,omitempty"`
	Summary *TransformSummary `json:"summary,omitempty"`
	// Form marks a Body that holds the text fields of a multipart form body.
	Form bool `json:"form,omitempty"`
}

TransformRequest is the req a stage hook receives.

type TransformResult

type TransformResult struct {
	Action   string          // "continue" or "reject"
	Effects  json.RawMessage // raw JSON array, nil when absent; the caller decodes per stage
	Findings []TransformFinding
	Code     string
	Message  string
	RuleID   string
	// Notice is the plugin's plain explanation of what it did, which the host
	// shows users in the log; nil when absent.
	Notice LocalizedText
}

TransformResult is a stage hook result whose shape CallTransform checked.

type TransformScope

type TransformScope struct {
	Models       []string `json:"models,omitempty"`
	ChannelTypes []int    `json:"channelTypes,omitempty"`
}

TransformScope is the range of requests a request processing plugin is made for: its models and the channel types its requests go through. An empty list leaves that side open; a scope always names at least one model or channel type, so a plugin cannot ask for every request.

type TransformSession

type TransformSession struct {
	ID   string `json:"id"`
	Turn int    `json:"turn"`
}

TransformSession is the client session a request belongs to, on a host that recognizes sessions.

type TransformSummary

type TransformSummary struct {
	MessageCount       int    `json:"messageCount"`
	ToolCount          int    `json:"toolCount"`
	LastUserTextLength int    `json:"lastUserTextLength"`
	TotalTextLength    int    `json:"totalTextLength"`
	HasImages          bool   `json:"hasImages"`
	ReasoningEffort    string `json:"reasoningEffort"`
}

type TransformToken

type TransformToken struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
}

TransformToken is the API token a request comes with.

type TransformUser

type TransformUser struct {
	ID       int    `json:"id"`
	Username string `json:"username"`
}

TransformUser is the user a request comes from.

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 UpstreamError

type UpstreamError struct {
	Status  int
	Message string
	Type    string
	Code    string
}

UpstreamError is the gateway error convertResponse or convertStreamEvent made of a vendor error. Status is 0 when the hook left it to the host.

func (*UpstreamError) Error

func (e *UpstreamError) Error() string

type UpstreamResponse

type UpstreamResponse struct {
	Status  int
	Headers map[string]string
	Body    []byte
}

UpstreamResponse is an upstream response as a response hook reads it.

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.

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.

type WebSocketMessage

type WebSocketMessage struct {
	Text     string
	Binary   []byte
	IsBinary bool
}

WebSocketMessage is one message sent upstream: text, or Binary when IsBinary is set.

type WebSocketRequest

type WebSocketRequest struct {
	Path      string
	URL       string
	Headers   map[string]string
	Protocols []string
	Messages  []WebSocketMessage
}

WebSocketRequest is the upstream WebSocket session of a convertRequest result: the address, as Path or URL, the handshake headers and subprotocols, and the messages sent once it is open.

Jump to

Keyboard shortcuts

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