gateway

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: MIT Imports: 40 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 gateway serves the OpenRealtime Protocol over WebSocket.

The protocol over WebSocket is the only entrance to a session. Everything else - a WebRTC adapter, a LiveKit agent participant - sits strictly above it and speaks it like any other client. That is not tidiness: a transport that reached the session core directly would become a second place the protocol can drift, and every such place multiplies the compatibility surface until a feature exists on one path and not the other.

This package is a renderer. It translates protocol events into binding runtime calls and the runtime's output back into protocol events, and it decides nothing about the conversation.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ValidateSessionBinding

func ValidateSessionBinding(source SessionBinding) error

ValidateSessionBinding validates the immutable, resource-free protocol contract of a session provider. Server plugin assembly uses this before it publishes a provider; New repeats the validation at the final gateway seam.

Types

type Config

type Config struct {
	// Binding provides session runtimes. Its minimal start seam deliberately
	// carries no topology or capability projection; New resolves those protocol
	// facts from an exact graph adapter profile or the retained legacy fallback.
	Binding SessionBinding
	// Token, when set, is the bearer token required on the upgrade request.
	Token string
	// Model is the compatibility model identifier reported to clients.
	Model string
	// TranscriptionModel is reported in the session object so a client can see
	// what produced its transcripts.
	TranscriptionModel string
	// MaxAudioFrameBytes bounds one inbound audio frame.
	MaxAudioFrameBytes int
	// VideoLimits are the video bounds this deployment advertises at
	// negotiation and enforces on every frame. The zero value selects the
	// shipped defaults.
	//
	// They are configuration rather than a constant because the connection's
	// read limit is derived from them: the two numbers have to move together
	// or the transport starts refusing frames the protocol just promised to
	// accept.
	VideoLimits openrealtime.Limits
	// ValidateWire checks every base-protocol event in both directions against
	// the pinned schema. It is on by default: a compatibility claim that is
	// not continuously checked is a compatibility claim that decays.
	ValidateWire bool
	// Metrics is optional operational telemetry.
	Metrics *Metrics
	// Recogniser, when set, reports the recogniser boundary for the whole
	// process. Only a binding that owns perception can supply it: on `omni`,
	// `duplex`, and `upstream` the model hears the user directly and there is
	// no recogniser to time, so it stays nil and the field is absent rather
	// than reported as zero. A zero would read as a recogniser answering
	// instantly, which is the opposite of the truth.
	Recogniser func() RecogniserSnapshot
	// Warm reports whether the models a turn waits on have answered once. It
	// is optional: unset means nothing to wait for.
	//
	// Health is what a caller asks before deciding the server is ready, and a
	// local model server answers its own health long before it answers a
	// request at speed. Reporting ok while the first turn will be degraded
	// answers a different question than the one being asked - measured, the
	// first call after start failed the control scenario and the next nine
	// passed, ten times out of ten.
	Warm func() bool
	// Logger receives structured operational events. It never receives
	// conversation content: a log that leaked what was said would be a worse
	// problem than having no log.
	Logger *slog.Logger
	// Timeline receives one line per turn event - each transcript revision,
	// each policy choice, each model request and answer, each utterance
	// synthesised and played, each background question - for every session.
	// Unlike Logger it carries conversation content, because a turn cannot be
	// read back without the words; it is written only where an operator asked
	// for it. Nil disables it.
	Timeline *timeline.Writer
	// WriteTimeout bounds one outbound WebSocket write. Zero selects the
	// shipped default; a negative value removes the bound.
	//
	// Without it a client that stops reading wedges its session permanently.
	// The socket write blocks once the peer's receive window closes, the
	// writer goroutine stops draining, the send buffer fills, the handler
	// blocks in send, and the read loop then blocks handing it the next event
	// - at which point nothing in the session can make progress and nothing
	// ends it, because the session context has no deadline of its own. The
	// binding runtime and its provider connections are held for as long as the
	// process lives.
	//
	// The default is derived rather than chosen: it has to be longer than the
	// longest stall a healthy receiver can have, and a congested mobile link
	// can hold a flow for several seconds. Thirty is comfortably past that and
	// still bounded, and a realtime conversation whose client has not accepted
	// a frame for thirty seconds is over regardless of what the socket does
	// next.
	WriteTimeout time.Duration
	// KeepaliveInterval is how long a connection may be idle before the server
	// pings it. Zero selects the shipped default; a negative value disables
	// the ping.
	//
	// The WebSocket library answers the client's pings, so a client that sends
	// them learns the server is alive. Nothing tells the server the reverse. A
	// client that disappears without a FIN - a NAT rebind, a laptop lid, a
	// dropped mobile handover - leaves a connection that is open on this side
	// only, and in a session where neither side is currently speaking there is
	// no write to discover it with. The HTTP server's IdleTimeout does not
	// apply, because the connection was hijacked at the upgrade.
	//
	// The ping is sent only after an idle interval, so it costs nothing on a
	// session that is carrying audio, and it is bounded by the same interval:
	// a peer that has not answered within one is not answering.
	KeepaliveInterval time.Duration
	// MaxSessions bounds concurrently admitted sessions. Zero is unbounded,
	// which is what an embedder gets unless it says otherwise; a launcher that
	// owns its deployment's capacity sets a number.
	//
	// Admission is the only place a limit can be applied honestly. Past this
	// point a session holds a binding runtime and its provider connections,
	// and the way an unbounded gateway fails is by exhausting the process
	// rather than by refusing anything. A refusal is a 503 the caller can
	// retry; an exhausted process takes every established session with it.
	MaxSessions int
	// InspectionTokenTTL bounds the read-only management capability issued to
	// a session that explicitly negotiates session debugging. Zero selects one
	// hour. The capability is revoked earlier when debugging is disabled or the
	// owning session ends.
	InspectionTokenTTL time.Duration
	// SessionInspection and ManagementHandler are the clean server-composition
	// seams for session observability. They must either both be absent, in which
	// case New preserves the standalone Handler compatibility surface, or both
	// be supplied by an exact server plugin profile. The handler is used only as
	// the canonical management delegate; it is never rendered into protocol
	// state or retained by a session.
	SessionInspection *SessionInspectionPlane
	ManagementHandler http.Handler
	// ClientEffectIssuer is the replaceable server authority seam for the
	// negotiated client.effects extension. Nil means the feature is not
	// offered. The issuer is never rendered into session state, graphs, logs,
	// or evidence; only its opaque per-call receipt crosses the wire.
	ClientEffectIssuer effectauthority.EffectReceiptIssuerProvider
	// ServerProfile supplies the exact mounted server-realm composition. It is
	// optional for compatibility constructors; production launchers set it
	// before exposing the handler. Health refuses an incomplete configured
	// profile instead of reporting only caller-asserted binding labels.
	ServerProfile func() pluginruntime.Live
	// contains filtered or unexported fields
}

type Metrics

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

Metrics is operational telemetry. It contains counts and never content: a metrics endpoint that leaked conversation would be a worse problem than having no metrics endpoint.

func (*Metrics) Snapshot

func (metrics *Metrics) Snapshot() MetricsSnapshot

Snapshot reads the counters.

type MetricsSnapshot

type MetricsSnapshot struct {
	SessionsStarted    uint64 `json:"sessions_started"`
	SessionsCompleted  uint64 `json:"sessions_completed"`
	SessionsFailed     uint64 `json:"sessions_failed"`
	AudioFramesIn      uint64 `json:"audio_frames_in"`
	VideoFramesIn      uint64 `json:"video_frames_in"`
	VideoFramesDropped uint64 `json:"video_frames_dropped"`
	AudioFramesOut     uint64 `json:"audio_frames_out"`
	ToolCallsOut       uint64 `json:"tool_calls_out"`
	SessionsRejected   uint64 `json:"sessions_rejected"`
	SessionsInFlight   int64  `json:"sessions_in_flight"`
}

MetricsSnapshot is a consistent-enough view for reporting.

type RecogniserSnapshot

type RecogniserSnapshot struct {
	Utterances uint64 `json:"utterances"`
	// InFlight is how many utterances are open right now. It is reported
	// because the totals include them: a reader comparing two polls should
	// know that part of the difference is one call still running.
	InFlight int `json:"in_flight"`

	AdvanceInvocations uint64 `json:"advance_invocations"`
	AdvanceFailures    uint64 `json:"advance_failures"`
	AdvanceElapsedNS   uint64 `json:"advance_elapsed_ns"`
	// AdvanceMeanElapsedNS is the number to alert on. A maximum jumps once on
	// a single bad call and never comes down; a mean that climbs over an hour
	// is a recogniser degrading.
	AdvanceMeanElapsedNS uint64 `json:"advance_mean_elapsed_ns"`
	AdvanceMaxElapsedNS  uint64 `json:"advance_max_elapsed_ns"`

	FinalizeInvocations   uint64 `json:"finalize_invocations"`
	FinalizeFailures      uint64 `json:"finalize_failures"`
	FinalizeElapsedNS     uint64 `json:"finalize_elapsed_ns"`
	FinalizeMeanElapsedNS uint64 `json:"finalize_mean_elapsed_ns"`
	FinalizeMaxElapsedNS  uint64 `json:"finalize_max_elapsed_ns"`
}

RecogniserSnapshot is process-level telemetry for the recogniser boundary.

It answers one question the session counters cannot: whether the recogniser is getting slower. A failing recogniser already ends a session with a named error, so the visible signal today is the failure; this is the run-up to it. Counters and timing only, like every other number this package reports.

type Server

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

Server serves /v1/realtime and /healthz.

func New

func New(config Config) (*Server, error)

New validates the configuration and creates a server.

func (*Server) Close

func (server *Server) Close(ctx context.Context) error

Close stops admission, terminates every admitted realtime session, waits for its runtime and inspection authority to retire, and releases the mounted management route realm. This makes a gateway a complete lifecycle resource: replacing its plugin cannot leave a session using retired dependencies.

func (*Server) HealthHandler

func (server *Server) HealthHandler() http.Handler

HealthHandler is the payload-only readiness endpoint implementation.

func (*Server) ManagementHandler

func (server *Server) ManagementHandler() http.Handler

ManagementHandler is the canonical, capability-authorized management API implementation. Server route plugins select its exact public resource families.

func (*Server) MetricsHandler

func (server *Server) MetricsHandler() http.Handler

MetricsHandler is the payload-only bounded telemetry endpoint implementation.

func (*Server) RealtimeHandler

func (server *Server) RealtimeHandler() http.Handler

RealtimeHandler is the OpenAI-compatible WebSocket endpoint implementation. It carries no route pattern so a server profile, rather than the gateway, owns public route selection.

func (*Server) ServeHTTP

func (server *Server) ServeHTTP(writer http.ResponseWriter, request *http.Request)

ServeHTTP upgrades a request into a session.

type SessionBinding

type SessionBinding interface {
	Name() string
	Start(context.Context, legacy.Options) (legacy.Runtime, error)
}

SessionBinding is the protocol renderer's complete session-creation seam. Conversation policy, topology, ownership, and capability selection are not methods on this interface. Graph-native providers expose those facts through their exact frozen SessionAdapterProfile; retained legacy providers are admitted only through the separately validated legacy fallback below.

type SessionInspectionPlane

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

SessionInspectionPlane is the payload-free session authority shared by realtime negotiation and the canonical management API. A composable server profile publishes this value together with its exact Authorizer and SessionInspection projections.

func NewSessionInspectionPlane

func NewSessionInspectionPlane(ttl time.Duration) (*SessionInspectionPlane, error)

NewSessionInspectionPlane validates the capability lifetime and creates the in-memory registries without mounting routes, starting workers, or acquiring external resources.

func (*SessionInspectionPlane) Authorizer

func (plane *SessionInspectionPlane) Authorizer() management.Authorizer

Authorizer returns the exact narrow-capability projection consumed by a management session-API plugin.

func (*SessionInspectionPlane) Sessions

Sessions returns the exact payload-free inspection projection consumed by a management session-API plugin.

func (*SessionInspectionPlane) Validate

func (plane *SessionInspectionPlane) Validate() error

Validate rejects a zero, partially constructed, or drifted plane before a gateway or plugin publishes it.

Jump to

Keyboard shortcuts

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