relaycontract

package
v0.46.0 Latest Latest
Warning

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

Go to latest
Published: Oct 13, 2026 License: Apache-2.0 Imports: 8 Imported by: 1 module, 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 relaycontract defines the wire protocol spoken between `tap relay` and Tapper Hub. A relay dials Hub, registers the models it can serve, and then answers inference requests Hub pushes down the same connection.

Every frame is an Envelope. Payloads are decoded strictly: an unknown field is an error rather than something forwarded to a provider.

Index

Constants

View Source
const (
	TypeRegister   = "register"
	TypeRegistered = "registered"
	TypeCatalog    = "catalog"
	TypePing       = "ping"
	TypePong       = "pong"
	TypeInfer      = "infer"
	TypeChunk      = "chunk"
	TypeDone       = "done"
	TypeError      = "error"
	TypeCancel     = "cancel"
	// TypeTools replaces the relay's advertised MCP servers and their tools.
	// It is connection-level and is sent only on a protocol 2 session.
	TypeTools = "tools"
	// TypeCall asks the relay to call one advertised tool. It is answered
	// like an infer: one chunk holding the CallToolResult, then done, or an
	// error. Cancel stops it.
	TypeCall = "call"
)

Frame types.

View Source
const (
	CapabilityChat          = "chat"
	CapabilityStream        = "stream"
	CapabilityTranscription = "transcription"
	CapabilityEmbeddings    = "embeddings"
	// CapabilityTools: the model can call tools (OpenAI function calling).
	CapabilityTools = "tools"
	// CapabilityVision: the model accepts image input.
	CapabilityVision = "vision"
)

Model capabilities a relay advertises.

View Source
const (
	// ReasoningToggle: thinking can be turned on or off, with no levels.
	ReasoningToggle = "toggle"
	// ReasoningEffort: thinking takes an effort level (low, medium, high).
	ReasoningEffort = "effort"
)

Reasoning modes a relay advertises for a model. Empty means the model does not reason, or the relay cannot tell. A value Hub does not know reads as empty, so a newer relay never fails registration over it.

View Source
const (
	CodeBadRequest          = "bad_request"
	CodeUnsupported         = "unsupported"
	CodeUnknownModel        = "unknown_model"
	CodeProviderUnavailable = "provider_unavailable"
	CodeProviderError       = "provider_error"
	CodeOverloaded          = "overloaded"
	CodeCancelled           = "cancelled"
	CodeRelayDisconnected   = "relay_disconnected"
	CodeInternal            = "internal"
	// CodeDisconnected ends a session because the relay's owner disconnected
	// it from Hub. It is connection-level (no id) and the relay must not
	// reconnect: the owner asked for it to go away.
	CodeDisconnected = "disconnected"
	// CodeUnknownTool: the call names a server or tool the relay does not
	// currently offer.
	CodeUnknownTool = "unknown_tool"
	// CodeToolUnavailable: the MCP server is down or failed the call at the
	// protocol level. A tool that ran and failed answers a result with
	// isError instead.
	CodeToolUnavailable = "tool_unavailable"
	// CodeTimeout: the call ran past the server's configured timeout.
	CodeTimeout = "timeout"
)

Error codes carried by an Error payload.

View Source
const (
	MaxNameLength    = 64
	MaxModelIDLength = 200
	MaxModels        = 256
	MaxConcurrentCap = 64
	// MaxPriority is the lowest-ranked priority a model may carry.
	MaxPriority = 99
)

Limits on what a relay may advertise.

View Source
const (
	MaxAppTitleLength = 64
	MaxAppURLLength   = 256
)

Limits on Infer's attribution fields, which a relay sends as HTTP headers.

View Source
const (
	MaxToolServers       = 32
	MaxToolsPerServer    = 128
	MaxTools             = 512
	MaxToolNameLength    = 128
	MaxToolTitleLength   = 200
	MaxToolDescription   = 4 << 10
	MaxToolSchemaBytes   = 64 << 10
	MaxToolsFrameBytes   = 4 << 20
	MaxToolCallArgsBytes = 1 << 20
	MaxToolResultBytes   = 4 << 20
)

Limits on the MCP servers and tools a relay may advertise, and on the calls that reach them. A relay drops a tool that breaks one of these before it sends the tools frame, so one bad tool never costs the whole catalog.

View Source
const APIOpenAIAudioTranscriptions = "openai.audio.transcriptions"

APIOpenAIAudioTranscriptions turns recorded speech into text. The request body is a TranscriptionRequest; the relay answers with exactly one chunk, a TranscriptionResult, then done. Hub only sends it to models advertising CapabilityTranscription, so a relay that predates it never sees one.

View Source
const APIOpenAIChatCompletions = "openai.chat.completions"

APIOpenAIChatCompletions is the chat inference API. The request body is an OpenAI chat completions request; each chunk is one OpenAI completion or completion-chunk object.

View Source
const APIOpenAIEmbeddings = "openai.embeddings"

APIOpenAIEmbeddings turns text into vectors. The request body is OpenAI's /embeddings JSON (input, and optionally dimensions and encoding_format); the relay answers with exactly one chunk, the provider's response, then done. Hub only sends it to models advertising CapabilityEmbeddings, so a relay that predates it never sees one.

View Source
const ConnectPath = "/api/v1/relay/connect"

ConnectPath is the Hub route a relay dials, relative to the hub base URL.

View Source
const EnvelopeVersion = 1

EnvelopeVersion is the frame shape every envelope carries in V. It is separate from ProtocolVersion because a peer checks V before it knows what was negotiated: a relay stamping its newest protocol there would be refused by every Hub that predates it. The shape has not changed since version 1.

View Source
const MaxCanonicalLength = 128

MaxCanonicalLength bounds a canonical model name.

View Source
const MaxTranscriptionAudioBytes = 10 << 20

MaxTranscriptionAudioBytes bounds one recording. Base64 in a JSON frame, it stays well inside the 16 MiB frame limit both ends enforce.

View Source
const ProtocolVersion = 3

ProtocolVersion is the newest relay protocol this package speaks. It is negotiated once, in register and registered, and gates which frames a session may carry: version 2 adds tools and call, version 3 adds the attribution fields of infer.

Variables

This section is empty.

Functions

func CanonicalModel

func CanonicalModel(id string) string

CanonicalModel derives the provider-neutral name a model pools under from the provider's own model id, so the same weights at the same precision share one name wherever they run: Ollama's "qwen3.6:35b-mlx" and LM Studio's "qwen/qwen3.6-35b" both become "qwen3.6-35b", and "qwen3.6:35b-a3b-mxfp8" and "Qwen3.6-35B-A3B-8bit" both become "qwen3.6-35b-a3b-8bit".

It lowercases, drops any source prefix up to the last '/', drops Ollama's ":latest" tag, strips trailing format parts ("mlx", "gguf", ...), and rewrites a trailing quantization part ("q4_k_m", "nvfp4", "bf16", ...) as its bits per weight ("4bit", "16bit"), so different quantizations of one model do not pool together. A name made only of those parts keeps them.

func SelectProtocol

func SelectProtocol(offered []int) int

SelectProtocol picks the highest version both sides speak, or 0.

func ValidCanonical

func ValidCanonical(name string) bool

ValidCanonical reports whether name is usable as a canonical model name: lowercase letters, digits, '.', '_' and '-', starting with a letter or digit, at most MaxCanonicalLength long.

func ValidName

func ValidName(name string) bool

ValidName reports whether name is acceptable as a relay or provider name.

func ValidToolName added in v0.45.0

func ValidToolName(name string) bool

ValidToolName reports whether name is acceptable as a tool name: 1 to MaxToolNameLength letters, digits, '.', '_' or '-'. MCP allows more; a relay drops a tool whose name falls outside this set.

Types

type Call added in v0.45.0

type Call struct {
	Server    string          `json:"server"`
	Tool      string          `json:"tool"`
	Arguments json.RawMessage `json:"arguments"`
}

Call is one tool call pushed from Hub to a relay. Server and Tool name an entry from the relay's own tools frame; nothing in a call can name a command, URL, header, or environment variable.

func (*Call) Validate added in v0.45.0

func (c *Call) Validate() error

Validate checks the call frame.

type Catalog

type Catalog struct {
	Models []Model `json:"models"`
}

Catalog replaces the relay's advertised model list after registration.

func (*Catalog) Validate

func (c *Catalog) Validate() error

Validate checks the catalog frame against protocol limits.

type CatalogBinding

type CatalogBinding struct {
	CatalogID string `json:"catalogId"`
	Provider  string `json:"provider"`
	Model     string `json:"model"`
}

CatalogBinding maps a relay's model to the catalog id Hub assigned it.

type Chunk

type Chunk struct {
	Data json.RawMessage `json:"data"`
}

Chunk carries one provider response object for an in-flight request. For a non-streaming request the relay sends exactly one chunk holding the whole response.

func (*Chunk) Validate

func (c *Chunk) Validate() error

Validate checks the chunk frame.

type Done

type Done struct {
	Usage *Usage `json:"usage,omitempty"`
}

Done terminates a request successfully.

type Envelope

type Envelope struct {
	V       int             `json:"v"`
	ID      string          `json:"id,omitempty"`
	Type    string          `json:"type"`
	Payload json.RawMessage `json:"payload,omitempty"`
}

Envelope is the frame shared by every message. ID correlates an infer request with its chunks and terminal frame; it is empty for connection-level frames such as register and ping.

func NewEnvelope

func NewEnvelope(typ, id string, payload any) (Envelope, error)

NewEnvelope marshals payload into an envelope of the given type.

func (Envelope) Decode

func (e Envelope) Decode(dst any) error

Decode strictly unmarshals the envelope payload into dst and validates it when dst implements Validate.

type Error

type Error struct {
	Code    string `json:"code"`
	Message string `json:"message"`
}

Error terminates a request, or the connection when the envelope has no ID.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Validate

func (e *Error) Validate() error

Validate checks the error frame.

type Infer

type Infer struct {
	API      string          `json:"api"`
	Provider string          `json:"provider"`
	Model    string          `json:"model"`
	Stream   bool            `json:"stream"`
	Body     json.RawMessage `json:"body"`
	// AppTitle and AppURL name the app the request came from, such as Hub's
	// chat or a `tap launch` harness, for providers that attribute usage to
	// apps (OpenRouter's X-Title and HTTP-Referer). Hub sends them only on
	// protocol 3 and later; they never select or authorize anything.
	AppTitle string `json:"appTitle,omitempty"`
	AppURL   string `json:"appUrl,omitempty"`
}

Infer is one inference request pushed from Hub to a relay.

func (*Infer) Validate

func (i *Infer) Validate() error

Validate checks the infer frame.

type Limits

type Limits struct {
	MaxConcurrent int `json:"maxConcurrent"`
}

Limits bounds how much work Hub may push at the relay at once.

type Model

type Model struct {
	ID               string   `json:"id"`
	Provider         string   `json:"provider"`
	ContextWindow    int      `json:"contextWindow,omitempty"`
	MaxContextWindow int      `json:"maxContextWindow,omitempty"`
	Reasoning        string   `json:"reasoning,omitempty"`
	Capabilities     []string `json:"capabilities,omitempty"`
	Priority         int      `json:"priority,omitempty"`
	Canonical        string   `json:"canonical,omitempty"`
}

Model is one model a relay offers. ID is the provider's own model name. Priority is the relay owner's ranking, 1 to MaxPriority with lower preferred; 0 is unranked and sorts after every ranked model. Hub lists models and routes pool requests in that order.

ContextWindow is the window the provider actually serves the model with (for Ollama, the allocated num_ctx); MaxContextWindow is the most the model supports. Either is 0 when unknown. Reasoning is one of the Reasoning* modes, or empty.

Canonical is the provider-neutral name the model pools under, so the same weights served by different providers or relays share one Hub id. Empty means Hub derives it with CanonicalModel; a value ValidCanonical rejects is ignored the same way.

type Register

type Register struct {
	Relay  RelayInfo `json:"relay"`
	Limits Limits    `json:"limits"`
	Models []Model   `json:"models"`
}

Register is the first frame a relay sends.

func (*Register) Validate

func (r *Register) Validate() error

Validate checks the register frame against protocol limits.

type Registered

type Registered struct {
	Protocol int              `json:"protocol"`
	Models   []CatalogBinding `json:"models"`
}

Registered is Hub's answer to Register.

type RelayInfo

type RelayInfo struct {
	Name      string `json:"name"`
	Version   string `json:"version,omitempty"`
	Protocols []int  `json:"protocols"`
}

RelayInfo identifies the relay process.

type Tool added in v0.45.0

type Tool struct {
	Name        string           `json:"name"`
	Title       string           `json:"title,omitempty"`
	Description string           `json:"description,omitempty"`
	InputSchema json.RawMessage  `json:"inputSchema"`
	Annotations *ToolAnnotations `json:"annotations,omitempty"`
}

Tool is one tool as its MCP server lists it. InputSchema is the tool's JSON Schema for its arguments; Annotations are the server's own hints, passed through as the server reported them.

func (*Tool) Validate added in v0.45.0

func (t *Tool) Validate() error

Validate checks one tool against protocol limits. A relay runs it on each tool it lists so it can drop the ones Hub would refuse.

type ToolAnnotations added in v0.45.0

type ToolAnnotations struct {
	ReadOnlyHint    *bool `json:"readOnlyHint,omitempty"`
	DestructiveHint *bool `json:"destructiveHint,omitempty"`
	IdempotentHint  *bool `json:"idempotentHint,omitempty"`
	OpenWorldHint   *bool `json:"openWorldHint,omitempty"`
}

ToolAnnotations mirrors MCP's tool annotations. Nil means the server did not say.

type ToolServer added in v0.45.0

type ToolServer struct {
	Name          string `json:"name"`
	Title         string `json:"title,omitempty"`
	MaxConcurrent int    `json:"maxConcurrent"`
	Tools         []Tool `json:"tools"`
}

ToolServer is one MCP server from the relay owner's configuration. Name is the key the owner gave it, not anything the server reports. MaxConcurrent bounds this server's in-flight calls across every hub the relay serves.

type Tools added in v0.45.0

type Tools struct {
	Servers []ToolServer `json:"servers"`
}

Tools replaces every MCP server a relay offers. Hub treats it as the whole list: a server missing from it is gone.

func (*Tools) Validate added in v0.45.0

func (t *Tools) Validate() error

Validate checks the tools frame against protocol limits.

type TranscriptionRequest

type TranscriptionRequest struct {
	Audio    []byte `json:"audio"`
	MimeType string `json:"mimeType"`
	Filename string `json:"filename,omitempty"`
	Language string `json:"language,omitempty"`
	Prompt   string `json:"prompt,omitempty"`
}

TranscriptionRequest is the body of an APIOpenAIAudioTranscriptions infer. Audio is the recording's bytes (base64 on the wire).

func (*TranscriptionRequest) Validate

func (t *TranscriptionRequest) Validate() error

Validate checks a transcription request.

type TranscriptionResult

type TranscriptionResult struct {
	Text string `json:"text"`
}

TranscriptionResult is the one chunk answering a transcription.

type Usage

type Usage struct {
	PromptTokens     int `json:"promptTokens,omitempty"`
	CompletionTokens int `json:"completionTokens,omitempty"`
}

Usage counts tokens when the provider reports them.

Jump to

Keyboard shortcuts

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