abiboot

package
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package abiboot implements the CPA native plugin JSON-envelope contract.

A CPA plugin is a native dynamic library that exports cliproxy_plugin_init together with a single call/free/shutdown function table. Every exchange between host and plugin is a JSON envelope:

{"ok":true,"result":{...}}
{"ok":false,"error":{"code":"...","message":"..."}}

This package owns the Go side of that contract: envelope construction, capability registration, method dispatch and the typed host callbacks (host.http.do, host.http.* stream operations, host.auth.*, host.log). The cgo glue that exports the four C symbols lives in each plugin's main package because //export is only honoured in package main.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ClearHostCaller

func ClearHostCaller()

ClearHostCaller drops the transport during plugin shutdown.

func Decode

func Decode[T any](raw json.RawMessage) (T, error)

Decode unmarshals a method payload into a typed request, tolerating the extra host_callback_id field the host appends.

func Dispatch

func Dispatch(p Plugin, method string, payload []byte) []byte

Dispatch routes one inbound call and always returns a complete envelope, so the cgo layer never has to synthesise an error reply itself.

func HostCall

func HostCall(method string, payload any) (json.RawMessage, error)

HostCall marshals payload, invokes a host method and returns the raw result. It is the generic escape hatch; prefer the typed Host methods.

func HostCallInto

func HostCallInto(method string, payload any, out any) error

HostCallInto marshals payload and decodes the host result into out.

func OK

func OK(v any) ([]byte, error)

OK wraps a method result in a success envelope.

func SetHostCaller

func SetHostCaller(fn func(method string, request []byte) ([]byte, error))

SetHostCaller installs the transport used for host callbacks. It is called exactly once from cliproxy_plugin_init.

Types

type Capabilities

type Capabilities struct {
	ModelRegistrar                bool                         `json:"model_registrar"`
	ModelProvider                 bool                         `json:"model_provider"`
	AuthProvider                  bool                         `json:"auth_provider"`
	FrontendAuthProvider          bool                         `json:"frontend_auth_provider"`
	FrontendAuthProviderExclusive bool                         `json:"frontend_auth_provider_exclusive"`
	Scheduler                     bool                         `json:"scheduler"`
	SchedulerAcrossPriorities     bool                         `json:"scheduler_across_priorities,omitempty"`
	ModelRouter                   bool                         `json:"model_router"`
	Executor                      bool                         `json:"executor"`
	ExecutorModelScope            pluginapi.ExecutorModelScope `json:"executor_model_scope"`
	ExecutorInputFormats          []string                     `json:"executor_input_formats,omitempty"`
	ExecutorOutputFormats         []string                     `json:"executor_output_formats,omitempty"`
	RequestTranslator             bool                         `json:"request_translator"`
	RequestNormalizer             bool                         `json:"request_normalizer"`
	RequestInterceptor            bool                         `json:"request_interceptor"`
	RequestLifecyclePlugin        bool                         `json:"request_lifecycle_plugin"`
	ResponseTranslator            bool                         `json:"response_translator"`
	ResponseBeforeTranslator      bool                         `json:"response_before_translator"`
	ResponseAfterTranslator       bool                         `json:"response_after_translator"`
	ResponseInterceptor           bool                         `json:"response_interceptor"`
	StreamChunkInterceptor        bool                         `json:"response_stream_interceptor"`
	WebSocketResponseObserver     bool                         `json:"websocket_response_observer"`
	ThinkingApplier               bool                         `json:"thinking_applier"`
	UsagePlugin                   bool                         `json:"usage_plugin"`
	CommandLinePlugin             bool                         `json:"command_line_plugin"`
	ManagementAPI                 bool                         `json:"management_api"`
	QuotaProvider                 bool                         `json:"quota_provider"`
}

Capabilities is the wire form of the capability block. The host decodes it into rpcCapabilities (see internal/pluginhost/rpc_schema.go) so the JSON tags below must match that struct exactly.

type Configurer

type Configurer interface {
	Configure(configYAML []byte) error
}

Configurer is implemented by plugins that read their instance settings from the config_yaml subtree delivered with plugin.register / plugin.reconfigure.

type Envelope

type Envelope struct {
	OK     bool            `json:"ok"`
	Result json.RawMessage `json:"result,omitempty"`
	Error  *EnvelopeError  `json:"error,omitempty"`
}

Envelope is the framing used for every host <-> plugin exchange.

type EnvelopeError

type EnvelopeError struct {
	Code       string `json:"code"`
	Message    string `json:"message"`
	Retryable  bool   `json:"retryable,omitempty"`
	HTTPStatus int    `json:"http_status,omitempty"`
}

EnvelopeError mirrors pluginabi.Error. HTTPStatus is surfaced to the client when the failing method is an executor call.

func Errorf

func Errorf(code, format string, args ...any) *EnvelopeError

Errorf builds a plain (non-HTTP) plugin error.

func HTTPError

func HTTPError(code string, status int, format string, args ...any) *EnvelopeError

HTTPError builds an error that carries an HTTP status code through to the CPA client (used by executor methods).

func RetryableError

func RetryableError(code string, format string, args ...any) *EnvelopeError

RetryableError marks a failure as retryable so the host may re-dispatch it.

func (*EnvelopeError) Error

func (e *EnvelopeError) Error() string

type HTTPDoRequest

type HTTPDoRequest struct {
	Method      string                     `json:"method,omitempty"`
	URL         string                     `json:"url,omitempty"`
	Headers     http.Header                `json:"headers,omitempty"`
	Body        []byte                     `json:"body,omitempty"`
	WireProfile *pluginapi.HTTPWireProfile `json:"wire_profile,omitempty"`
}

HTTPDoRequest is the wire shape of host.http.do. The host decodes a flat object with lower-case snake_case keys (internal/pluginhost/host_callbacks.go, rpcHostHTTPRequest), so these tags are part of the contract.

type HTTPStream

type HTTPStream struct {
	StatusCode int
	Headers    http.Header
	StreamID   string
	// contains filtered or unexported fields
}

HTTPStream is an incremental upstream response opened with host.http.do_stream.

func (*HTTPStream) Close

func (s *HTTPStream) Close() error

Close releases the host-side stream. It is safe to call more than once.

func (*HTTPStream) Header

func (s *HTTPStream) Header() http.Header

Header exposes the response headers of the opened stream.

func (*HTTPStream) Read

func (s *HTTPStream) Read() ([]byte, error)

Read returns the next body chunk, or io.EOF once the upstream stream is exhausted. Callers must Close the stream.

type Handler

type Handler func(h *Host, raw json.RawMessage) (any, error)

Handler processes a single method invocation. The returned value is wrapped in a success envelope; returning an error produces a failure envelope.

type Host

type Host struct {
	CallbackID string
	PluginID   string
	Config     pluginapi.HostConfigSummary
	// Incoming is the raw auth payload the host supplied for this invocation
	// (`RawJSON` on auth.parse, `StorageJSON` on auth.refresh and the model and
	// execution paths). It is the auth file as the host sees it, so SaveAuth can
	// carry forward the members this plugin does not own: the host reads
	// `priority` and `weight` from that same file to choose a credential, and a
	// rewrite that drops them silently resets the credential's routing tier.
	Incoming json.RawMessage
}

Host is the per-invocation handle passed to every method handler. It carries the host_callback_id that the host minted for this call; outbound host callbacks must echo it back so the host can attribute them to the caller.

func NewHost

func NewHost(raw json.RawMessage) *Host

NewHost extracts the callback identity and host summary from an inbound method payload. Unknown fields are ignored, so it is safe for every method.

func (*Host) GetAuth

func (h *Host) GetAuth(authIndex string) (*pluginapi.HostAuthGetResponse, error)

GetAuth reads a previously stored auth file by its auth index.

The payload is also remembered as this invocation's Incoming file, because management routes reach a credential this way rather than through a parse or refresh callback: a page that reads a quota and then persists a renewed token must still merge into the file the host is holding.

func (*Host) HTTPDo

func (h *Host) HTTPDo(req HTTPDoRequest) (*pluginapi.HTTPResponse, error)

HTTPDo performs a buffered request through the host transport, inheriting the host's proxy, TLS and header-profile settings.

func (*Host) HTTPDoStream

func (h *Host) HTTPDoStream(req HTTPDoRequest) (*HTTPStream, error)

HTTPDoStream opens a streaming request. The host returns as soon as it has the response head; body bytes are pulled with Read.

func (*Host) ListAuth

func (h *Host) ListAuth() ([]pluginapi.HostAuthFileEntry, error)

ListAuth enumerates every credential the host currently tracks. The list is host-wide, so callers must filter it down to their own provider key.

func (*Host) Log

func (h *Host) Log(level, message string, fields map[string]any)

Log emits a structured log line into the CPA log stream.

func (*Host) SaveAuth

func (h *Host) SaveAuth(name string, storage json.RawMessage) (*pluginapi.HostAuthSaveResponse, error)

SaveAuth persists an auth file through the host so it appears in the CPA auth directory and management UI. storage must be a JSON object.

host.auth.save replaces the whole file (pluginapi.HostAuthSaveRequest carries only a name and a JSON blob), so the members the plugin does not define are carried forward from Incoming. Without that, every self-initiated refresh would erase host-owned routing members such as `priority` and `weight`, and the credential would silently fall back to the default tier.

type Identifier

type Identifier struct {
	Identifier string `json:"identifier"`
}

Identifier is the shared reply shape for auth.identifier / executor.identifier.

func IdentifierReply

func IdentifierReply(id string) Identifier

IdentifierReply builds an identifier reply.

type Mux

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

Mux is a small helper for building the route table.

func NewMux

func NewMux() *Mux

NewMux returns an empty route table.

func (*Mux) On

func (m *Mux) On(method string, handler Handler) *Mux

On registers a handler for a pluginabi method constant.

func (*Mux) Routes

func (m *Mux) Routes() map[string]Handler

Routes exposes the accumulated table.

type Plugin

type Plugin interface {
	Registration() Registration
	Routes() map[string]Handler
}

Plugin is the contract between a provider plugin and the ABI bootstrap.

type Quiescer

type Quiescer interface{ Quiesce() }

Quiescer is implemented by plugins that need to drain in-flight work.

type Registration

type Registration struct {
	SchemaVersion uint32             `json:"schema_version"`
	Metadata      pluginapi.Metadata `json:"metadata"`
	Capabilities  Capabilities       `json:"capabilities"`
}

Registration is returned from plugin.register and plugin.reconfigure.

func NewRegistration

func NewRegistration(meta pluginapi.Metadata, caps Capabilities) Registration

NewRegistration stamps the current schema version onto a registration so plugins never hard-code the negotiated revision.

type Shutdowner

type Shutdowner interface{ Shutdown() }

Shutdowner is implemented by plugins that hold background resources.

Jump to

Keyboard shortcuts

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