relay

package
v0.45.0 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: Apache-2.0 Imports: 27 Imported by: 0 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.

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

View Source
const (
	KindOllama           = "ollama"
	KindOpenAI           = "openai"
	KindOpenRouter       = "openrouter"
	KindOpenAICompatible = "openai-compatible"
)

Provider kinds.

View Source
const (
	AuthNone         = "none"
	AuthAPIKey       = "apiKey"
	AuthSubscription = "subscription"
	AuthKeychain     = "keychain"
)

Credential sources.

View Source
const DefaultMaxConcurrent = 4

DefaultMaxConcurrent is a provider's in-flight limit when its config sets none.

View Source
const (
	DefaultToolTimeout = 2 * time.Minute
)

Defaults for a configured MCP server.

View Source
const ReasoningNone = "none"

ReasoningNone marks, in config, a model that does not reason even though discovery says it does.

Variables

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

View Source
var ErrIncompatible = errors.New("hub does not support this relay's protocol version")

ErrIncompatible means Hub and this relay share no protocol version.

View Source
var ErrToolServerDown = errors.New("mcp server is not running")

ErrToolServerDown means the MCP server is not connected right now.

View Source
var ErrUnauthorized = errors.New("hub rejected the relay credential; run `tap auth login`")

ErrUnauthorized means Hub rejected the relay's credential. Reconnecting cannot fix it; the user has to sign in again.

Functions

func ConnectURL

func ConnectURL(hubURL string) (string, error)

ConnectURL converts a hub root into the relay WebSocket URL.

func ToolEnv added in v0.45.0

func ToolEnv(environ []string, inherit bool, pass []string, set map[string]string) []string

ToolEnv builds a stdio MCP server's environment from the relay's own. With inherit it is the whole environment; otherwise the base variables, locale settings (LC_*), and the names in pass. Literal values in set are applied last and win.

Types

type Client

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

Client maintains the relay's connections to its hubs.

func NewClient

func NewClient(opts Options) (*Client, error)

NewClient validates opts and returns a Client.

func (*Client) Run

func (c *Client) Run(ctx context.Context) error

Run keeps the relay connected to every hub until ctx ends. A permanent error on one hub (unauthorized, incompatible, disconnected by its owner) stops that hub only; Run returns those errors once no hub is left.

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

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 and Vision say whether the model calls tools and accepts images;
	// nil keeps what discovery found.
	Tools, Vision *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) Embeds

func (p *Provider) Embeds(model string) bool

Embeds reports whether model is one of the configured embedding models.

func (*Provider) ListModels

func (p *Provider) ListModels(ctx context.Context) ([]relaycontract.Model, error)

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

func (p *Provider) MaxConcurrent() int

MaxConcurrent returns the provider's in-flight limit.

func (*Provider) Name

func (p *Provider) Name() string

Name returns the provider name advertised to Hub.

func (*Provider) Priority

func (p *Provider) Priority() int

Priority returns the provider's ranking on Hub, 0 when unranked.

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

func (p *Provider) Transcribes(model string) bool

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

type ProviderError struct {
	Provider string
	Status   int
	Message  string
}

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

type Variant struct {
	From string
	ModelMeta
}

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.

Jump to

Keyboard shortcuts

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