Documentation
¶
Overview ¶
Package relay implements the `tap relay` process: it offers the models of locally configured providers to Tapper Hub over an outbound WebSocket and forwards the inference requests Hub pushes back down to those providers.
It also forwards tool calls to the MCP servers named in the same configuration, to hubs that speak relay protocol 2.
The relay forwards inference and tool calls and nothing else. Destinations are the providers and MCP servers named in the user's own configuration; nothing Hub sends can name a command, URL, host, header, or environment variable. A tool call names only a server and tool the relay advertised.
Index ¶
- Constants
- Variables
- func ConnectURL(hubURL string) (string, error)
- func ToolEnv(environ []string, inherit bool, pass []string, set map[string]string) []string
- type Client
- type Hub
- type ModelMeta
- type Options
- type Provider
- func (p *Provider) ChatCompletions(ctx context.Context, body json.RawMessage, model string, stream bool, ...) (*relaycontract.Usage, error)
- func (p *Provider) Embeddings(ctx context.Context, body json.RawMessage, model string) (json.RawMessage, *relaycontract.Usage, error)
- func (p *Provider) Embeds(model string) bool
- func (p *Provider) ListModels(ctx context.Context) ([]relaycontract.Model, error)
- func (p *Provider) MaxConcurrent() int
- func (p *Provider) Name() string
- func (p *Provider) Priority() int
- func (p *Provider) Transcribe(ctx context.Context, body json.RawMessage, model string) (json.RawMessage, error)
- func (p *Provider) Transcribes(model string) bool
- func (p *Provider) WithTranscriptionModels(listed []relaycontract.Model) []relaycontract.Model
- type ProviderConfig
- type ProviderError
- type ToolServer
- type ToolServerConfig
- type Variant
Constants ¶
const ( KindOllama = "ollama" KindOpenAI = "openai" KindOpenRouter = "openrouter" KindOpenAICompatible = "openai-compatible" )
Provider kinds.
const ( AuthNone = "none" AuthAPIKey = "apiKey" AuthSubscription = "subscription" AuthKeychain = "keychain" )
Credential sources.
const DefaultMaxConcurrent = 4
DefaultMaxConcurrent is a provider's in-flight limit when its config sets none.
const (
DefaultToolTimeout = 2 * time.Minute
)
Defaults for a configured MCP server.
const ReasoningNone = "none"
ReasoningNone marks, in config, a model that does not reason even though discovery says it does.
Variables ¶
var ErrDisconnected = errors.New("relay was disconnected from Hub by its owner; restart `tap relay` to reconnect")
ErrDisconnected means the relay's owner disconnected it from Hub. Reconnecting would undo that, so it is permanent.
var ErrIncompatible = errors.New("hub does not support this relay's protocol version")
ErrIncompatible means Hub and this relay share no protocol version.
var ErrRevoked = errors.New("hub revoked the relay's sign-in; run `tap auth login`, then restart `tap relay`")
ErrRevoked means Hub revoked the credential the relay runs under (a sign-out, a revoked token). Reconnecting cannot fix it; the user has to sign in again.
var ErrToolServerDown = errors.New("mcp server is not running")
ErrToolServerDown means the MCP server is not connected right now.
ErrUnauthorized means Hub rejected the relay's credential. Reconnecting cannot fix it; the user has to sign in again.
Functions ¶
func ConnectURL ¶
ConnectURL converts a hub root into the relay WebSocket URL.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client maintains the relay's connections to its hubs.
type Hub ¶
type Hub struct {
// URL is the hub root, e.g. https://atlas.foldwise.dev.
URL string
// Token returns the current bearer token. It is called on every dial so a
// refreshed token is picked up after a reconnect.
Token func(ctx context.Context) (string, error)
// Refresh, when set, returns a freshly refreshed token whatever the
// cached one's recorded expiry says. The relay calls it to reauth a live
// session before Hub expires its token, to redial after
// credential_expired, and to retry a dial Hub refused. An error wrapping
// ErrUnauthorized means the sign-in is gone. Without it Token is used.
Refresh func(ctx context.Context) (string, error)
}
Hub is one hub the relay serves.
type ModelMeta ¶
type ModelMeta struct {
// ContextWindow is the window the provider serves the model with.
ContextWindow int
// MaxContextWindow is the most the model supports.
MaxContextWindow int
// Reasoning is "none", relaycontract.ReasoningToggle, or
// relaycontract.ReasoningEffort; empty keeps what discovery found.
Reasoning string
// Tools, Vision, and Video say whether the model calls tools, accepts
// images, and accepts video; nil keeps what discovery found.
Tools, Vision, Video *bool
// Canonical is the provider-neutral name Hub pools the model under;
// empty derives it with relaycontract.CanonicalModel.
Canonical string
}
ModelMeta is what the user's config says about a model when the provider does not say, or says it wrong. Zero fields leave discovery alone.
type Options ¶
type Options struct {
// Hubs are served at once, each over its own connection, from one shared
// concurrency budget and one model catalog.
Hubs []Hub
// Name identifies the relay to Hub.
Name string
// Version is the tap version reported at registration.
Version string
Providers []*Provider
// ToolServers are the MCP servers whose tools the relay forwards to hubs
// that speak protocol 2.
ToolServers []*ToolServer
Logger *slog.Logger
HTTPClient *http.Client
// CatalogInterval is how often providers are re-listed. Zero means a minute.
CatalogInterval time.Duration
// ReadTimeout drops a connection that has been silent this long. Hub pings
// well inside it. Zero means 90 seconds.
ReadTimeout time.Duration
// OnRegistered, when set, observes each successful registration.
OnRegistered func(hubURL string, reg relaycontract.Registered)
}
Options configures a Client.
type Provider ¶
type Provider struct {
// contains filtered or unexported fields
}
Provider reaches one OpenAI-compatible provider: its chat completions endpoint, and /audio/transcriptions for the Transcription models.
func NewProvider ¶
func NewProvider(cfg ProviderConfig, getenv func(string) string, client *http.Client) (*Provider, error)
NewProvider validates cfg and resolves its credential through getenv. The resolved key stays inside the Provider and is never logged.
func (*Provider) ChatCompletions ¶
func (p *Provider) ChatCompletions(ctx context.Context, body json.RawMessage, model string, stream bool, emit func(json.RawMessage) error) (*relaycontract.Usage, error)
ChatCompletions sends an OpenAI chat completions request with model and stream set from the caller, and passes each response object to emit: one object for a non-streaming request, one per SSE event otherwise.
func (*Provider) Embeddings ¶
func (p *Provider) Embeddings(ctx context.Context, body json.RawMessage, model string) (json.RawMessage, *relaycontract.Usage, error)
Embeddings posts an OpenAI /embeddings request and returns the provider's response as is. body is the caller's request; model is the offered id, rewritten to the provider's own name for an alias variant.
func (*Provider) ListModels ¶
ListModels returns the models the provider offers after allow and deny, with what the provider says about their context and reasoning, overlaid by the configured metadata, plus configured variants. The error is fatal only when models is nil; otherwise it reports metadata the relay could not get (an Ollama variant that could not be created, say) while still offering what it has.
func (*Provider) MaxConcurrent ¶
MaxConcurrent returns the provider's in-flight limit.
func (*Provider) Transcribe ¶
func (p *Provider) Transcribe(ctx context.Context, body json.RawMessage, model string) (json.RawMessage, error)
Transcribe posts a recording to the provider's OpenAI-style /audio/transcriptions endpoint and returns the transcript as a TranscriptionResult object. body is a relaycontract.TranscriptionRequest.
func (*Provider) Transcribes ¶
Transcribes reports whether model is one of the configured transcription models.
func (*Provider) WithTranscriptionModels ¶
func (p *Provider) WithTranscriptionModels(listed []relaycontract.Model) []relaycontract.Model
WithTranscriptionModels returns listed plus every exact (non-glob) transcription model id missing from it: a speech server often lists no models at all, or not the one configured.
type ProviderConfig ¶
type ProviderConfig struct {
Name string
Kind string
BaseURL string
Auth string
APIKeyEnv string
Allow []string
Deny []string
// Transcription names the models (exact ids or path.Match globs) that
// turn speech into text through /audio/transcriptions. /models does not
// say which models those are, so the user does.
Transcription []string
// Embeddings names the models (exact ids or globs) that turn text into
// vectors through /embeddings, for providers that do not say. Ollama
// reports its own.
Embeddings []string
// MaxConcurrent bounds this provider's in-flight requests across every
// hub. Zero means DefaultMaxConcurrent.
MaxConcurrent int
// Priority ranks the provider's models on Hub, lower preferred. Zero is
// unranked.
Priority int
// Metadata fills in, or corrects, what the provider says about a model's
// context and reasoning. Keys are exact ids or path.Match globs.
Metadata map[string]ModelMeta
// Variants are models offered under their own id that run another with
// fixed settings, keyed by the offered id.
Variants map[string]Variant
}
ProviderConfig describes one provider as configured by the user.
type ProviderError ¶
ProviderError reports a failure returned by the provider itself.
func (*ProviderError) Error ¶
func (e *ProviderError) Error() string
type ToolServer ¶ added in v0.45.0
type ToolServer struct {
// contains filtered or unexported fields
}
ToolServer supervises one MCP server: it connects (starting the command for a stdio server), lists the tools, reconnects after a crash, and runs calls. Its catalog is empty whenever it is down.
func NewToolServer ¶ added in v0.45.0
func NewToolServer(cfg ToolServerConfig) (*ToolServer, error)
NewToolServer validates cfg and returns a server that is not yet running.
func (*ToolServer) Name ¶ added in v0.45.0
func (s *ToolServer) Name() string
Name returns the server's configured name.
type ToolServerConfig ¶ added in v0.45.0
type ToolServerConfig struct {
Name string
Title string
Command string
Args []string
Dir string
Env []string
URL string
Headers map[string]string
// Allow and Deny filter the server's tools by name (exact or glob). An
// empty Allow offers every tool not denied.
Allow []string
Deny []string
// MaxConcurrent bounds this server's in-flight calls across every hub.
// Zero means DefaultMaxConcurrent.
MaxConcurrent int
// Timeout bounds one call. Zero means DefaultToolTimeout.
Timeout time.Duration
}
ToolServerConfig describes one MCP server. Exactly one of Command or URL is set. Env is the child's whole environment (see ToolEnv); Headers are sent on every HTTP request, already resolved from the environment.
type Variant ¶
Variant is a model offered under its own id that runs another with fixed settings. On Ollama a variant with a ContextWindow is created as a real model (`from` plus num_ctx), since Ollama's OpenAI API cannot set the context per request; elsewhere it is an alias the relay rewrites on the way out.