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
- func CanonicalModel(id string) string
- func SelectProtocol(offered []int) int
- func ValidCanonical(name string) bool
- func ValidName(name string) bool
- func ValidToolName(name string) bool
- type Call
- type Catalog
- type CatalogBinding
- type Chunk
- type Done
- type Envelope
- type Error
- type Infer
- type Limits
- type Model
- type Reauth
- type Reauthed
- type Register
- type Registered
- type RelayInfo
- type Tool
- type ToolAnnotations
- type ToolServer
- type Tools
- type TranscriptionRequest
- type TranscriptionResult
- type Usage
Constants ¶
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" // TypeReauth presents a refreshed access token on a live session, so // the session outlives the token that opened it. The relay sends it, // with an id of its choosing, only on a protocol 4 session whose // registered frame advertised credentialExpiresIn. Hub answers with // reauthed carrying the same id, or with an error of that id and code // CodeReauthRejected; either way the session goes on. TypeReauth = "reauth" // TypeReauthed accepts a reauth: the session now runs under the new // token, which expires credentialExpiresIn seconds from this frame. TypeReauthed = "reauthed" )
Frame types.
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" // CapabilityVideo: the model accepts video input (an OpenAI-style // "video_url" content part). CapabilityVideo = "video" )
Model capabilities a relay advertises.
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.
const ( CodeBadRequest = "bad_request" CodeUnsupported = "unsupported" CodeUnknownModel = "unknown_model" 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. From protocol 4 it means // only that; a revoked credential ends with CodeCredentialRevoked. CodeDisconnected = "disconnected" // CodeCredentialExpired ends a session because the access token that // opened it (or the last reauth) expired. It is connection-level (no id) // and, unlike CodeDisconnected, retryable: the relay should reconnect at // once with a refreshed token. Hub closes the WebSocket with status 1013 // (try again later) after sending it. CodeCredentialExpired = "credential_expired" // CodeCredentialRevoked ends a session because the credential behind it // was revoked: a sign-out, a revoked token, or a removed account. It is // connection-level and final; only a new sign-in restores the relay. // Hub sends it only on protocol 4 sessions. CodeCredentialRevoked = "credential_revoked" // CodeGoingAway ends a session because Hub is shutting down or // restarting. It is connection-level and retryable at once: the relay // reconnects after a short random delay, without a backoff penalty. // Hub sends it only on protocol 4 sessions. CodeGoingAway = "going_away" // CodeReauthRejected answers a reauth Hub refused (the token is not // valid, or not for the same account). It carries the reauth's id and // does not end the session: the old credential stands until it expires. CodeReauthRejected = "reauth_rejected" // CodeUnknownTool: the call names a server or tool the relay does not // currently offer. CodeUnknownTool = "unknown_tool" // 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.
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.
const ( MaxAppTitleLength = 64 MaxAppURLLength = 256 )
Limits on Infer's attribution fields, which a relay sends as HTTP headers.
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.
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.
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.
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.
const ConnectPath = "/api/v1/relay/connect"
ConnectPath is the Hub route a relay dials, relative to the hub base URL.
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.
const MaxCanonicalLength = 128
MaxCanonicalLength bounds a canonical model name.
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.
const ProtocolVersion = 4
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, version 4 adds in-band reauthentication (registered's credentialExpiresIn, reauth and reauthed) and the credential_revoked and going_away end codes.
Variables ¶
This section is empty.
Functions ¶
func CanonicalModel ¶
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 ¶
SelectProtocol picks the highest version both sides speak, or 0.
func ValidCanonical ¶
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 ValidToolName ¶ added in v0.45.0
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.
type Catalog ¶
type Catalog struct {
Models []Model `json:"models"`
}
Catalog replaces the relay's advertised model list after registration.
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.
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 ¶
NewEnvelope marshals payload into an envelope of the given type.
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.
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 Reauth ¶ added in v0.47.0
type Reauth struct {
Token string `json:"token"`
}
Reauth is the payload of a reauth frame.
type Reauthed ¶ added in v0.47.0
type Reauthed struct {
CredentialExpiresIn int `json:"credentialExpiresIn"`
}
Reauthed is the payload of a reauthed frame. CredentialExpiresIn counts seconds from this frame, like Registered's.
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.
type Registered ¶
type Registered struct {
Protocol int `json:"protocol"`
Models []CatalogBinding `json:"models"`
CredentialExpiresIn int `json:"credentialExpiresIn,omitempty"`
}
Registered is Hub's answer to Register.
CredentialExpiresIn is how many seconds after this frame the access token that opened the session expires. Zero means Hub does not end the session at a token expiry (the token does not expire, or Hub predates protocol 4). Hub sends it only on protocol 4 sessions, since older relays decode registered strictly. The relay times its reauth from when it read this frame, never from its own wall clock, so clock skew cannot move it.
func (*Registered) Validate ¶ added in v0.47.0
func (r *Registered) Validate() error
Validate checks the registered frame.
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"`
OutputSchema json.RawMessage `json:"outputSchema,omitempty"`
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, and OutputSchema the one for its structured result when the server declares one; a relay that predates OutputSchema, or a server that declares none, leaves it out. Annotations are the server's own hints, passed through as the server reported them.
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.
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.