protocol

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 17 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 protocol defines the versioned, provider-neutral contracts shared by the runtime, control plane, and framework integrations.

Index

Constants

View Source
const (
	// RelayRevision is the protocol revision claimed by relay plans. It is
	// deliberately separate from CurrentRevision: relay plans carry their own
	// execution contract, including the credential owner that connectors must
	// use. A connector that does not understand this revision rejects the plan
	// outright instead of guessing how to authenticate to a provider.
	RelayRevision = 5
	// RelayBillingRevision requires operation metering. Revision 5 remains
	// accepted for already-issued plans and routes not yet converted.
	RelayBillingRevision = 6
	// RelayPlanJWSType is the protected-header typ required on a relay-plan
	// compact JWS. Even under a shared signing key, the typ check stops a
	// session-plan signature from authorizing a relay dispatch and a
	// relay-plan signature from opening a provider session.
	RelayPlanJWSType = "speko.relay-plan+jws"
	// RelayPlanAudience is the aud claim relay verifiers require. Relay
	// connectors are the sole intended consumers of relay plans; the distinct
	// audience keeps a plan minted for the runtime fleet from verifying at a
	// connector even before the typ check is reached.
	RelayPlanAudience = "speko-relay"
)
View Source
const (
	// VoiceV0 is the current wire-protocol identifier.
	VoiceV0 = "speko.voice.v0"
	// CurrentRevision is intentionally exact during initial development. A
	// runtime must reject a plan built for any other revision before media is
	// accepted.
	CurrentRevision = 3
	// SessionPlanCredentialDigestJWSType identifies a session-plan JWS whose
	// enclosed credential value is a SHA-256 binding rather than the bearer
	// itself. This keeps large one-time provider tokens inside AWS KMS's raw
	// Ed25519 signing limit without weakening their binding to the plan.
	SessionPlanCredentialDigestJWSType = "speko.session-plan+credential-digest+jws"
)
View Source
const (
	MaxLiveInstructionsBytes        = 96 << 10
	MaxLiveBackendInstructionsBytes = 96 << 10
	MaxLiveHistoryItems             = 256
	MaxLiveHistoryBytes             = 256 << 10
	MaxLiveHistoryItemBytes         = 32 << 10
	MaxLiveTools                    = 64
	MaxLiveToolBytes                = 64 << 10
	MaxLiveToolChoiceBytes          = 4 << 10
	MaxLiveSettingBytes             = 4 << 10
	MinLiveMaxOutputTokens          = 16
	MaxLiveMaxOutputTokens          = 131_072
	// MaxBidiSetupBytes bounds the Gemini Live setup document forwarded from
	// the public /v1/bidi socket. relayapi.MaxBidiSetupFrameBytes mirrors it
	// on the whole first frame, so a document the route accepts always fits
	// through here; the two must move together.
	MaxBidiSetupBytes = 192 << 10
	// MaxLiveContextAppendBytes bounds the content of one
	// session.{instructions,thinking,commentary}.append. The vendor caps an
	// append at 500 tokens; 16 KiB of UTF-8 is far above that in every
	// script, so the bound rejects only abuse, never a legitimate append.
	MaxLiveContextAppendBytes = 16 << 10
)

Live session configuration bounds. They bound what a caller can place on the wire, not what the vendor accepts: every one is comfortably above the documented vendor limit (16,384 instruction tokens, 500-token appends) and exists so a session request can be hashed, validated, and forwarded without buffering an unbounded document.

View Source
const (
	// LiveBackendInputTokensPerResponse bounds the context GPT-Live supplies
	// to one backend response: the replacement-engine history cap (8,192
	// tokens) plus instructions, tools, and appended context.
	LiveBackendInputTokensPerResponse int64 = 16_384
	// LiveBackendToolCallsPerResponse bounds billable hosted tool calls one
	// backend response may perform.
	LiveBackendToolCallsPerResponse int64 = 8
	// LiveBackendResponsesPerSlice is how many responses one admission or
	// top-up slice funds.
	LiveBackendResponsesPerSlice int64 = 2
	// MaxLiveContinuations caps response.create commands per session.
	MaxLiveContinuations = 64
	// MaxLiveConfigurationChanges caps session.update commands per session.
	MaxLiveConfigurationChanges = 32
)

Hosted accounting bounds for a GPT-Live Responses backend. The Router reserves backend exposure per response — in-flight work included — from these bounds and the session's max_output_tokens, and refuses further continuations or configuration changes past the count limits. They are shared here so the edge that sizes a reservation and the connector that guards it can never disagree.

View Source
const (
	// MaxProviderControlBytes bounds one forwarded native command.
	MaxProviderControlBytes = 64 << 10
	// MaxProviderEventBytes bounds one surfaced native event, including a
	// base64 audio delta.
	MaxProviderEventBytes = 2 << 20
)
View Source
const BillingRevision = 1

BillingRevision versions trusted server-side metering, independently of the public relay API. These quantities are never accepted from a customer.

Variables

View Source
var TranslationNoiseReductionTypes = []string{"near_field", "far_field"}

TranslationNoiseReductionTypes are the audio.input.noise_reduction.type values the vendor documents for its realtime audio input.

View Source
var TranslationOutputLanguages = []string{"es", "pt", "fr", "ja", "ru", "zh", "de", "ko", "hi", "id", "vi", "it", "en"}

TranslationOutputLanguages are the target languages gpt-realtime-translate speaks, in the vendor's published order. Source speech is auto-detected, so only the output side is named.

View Source
var TranslationTranscriptionModels = []string{"gpt-realtime-whisper"}

TranslationTranscriptionModels are the source-transcript models the translation session accepts under audio.input.transcription.model. Only the vendor's documented one is admitted: a transcription model may be priced on its own, and a caller must not be able to attach an unpriced one to a session billed as translation minutes.

Functions

func BidiControlAllowed

func BidiControlAllowed(key string) bool

BidiControlAllowed reports whether a Gemini Live client message key may be forwarded. Unknown keys are refused rather than passed through: the vendor would reject them anyway, and the caller learns at the hop instead of mid-session.

func BidiControlKeys

func BidiControlKeys() []string

BidiControlKeys lists the forwardable Gemini Live client message keys.

func ProviderControlAllowed

func ProviderControlAllowed(protocol SpeechProtocol, controlType string) bool

ProviderControlAllowed reports whether a native command type may be forwarded on a session of the given protocol. A Realtime-only control on a Live session (input_audio_buffer.commit, response.cancel) and a Live-only control on a Realtime session are both refused. Gemini Live is key-tagged and never answers true here — see BidiControlAllowed.

func ProviderControlTypes

func ProviderControlTypes(protocol SpeechProtocol) []string

ProviderControlTypes lists the forwardable command types for a protocol.

func SttOptionKeyReserved added in v0.3.1

func SttOptionKeyReserved(key string) bool

SttOptionKeyReserved reports whether a provider setting name, folded the way Normalize folds it, is one the gateway owns. An adapter that can be driven without Normalize refuses these itself.

func SttOptionString

func SttOptionString(value any) string

SttOptionString writes a scalar provider option the way a caller writing the query parameter by hand would: strings unquoted, numbers and booleans in their JSON spelling. Shared by the adapters that spell settings into URLs so two vendors cannot disagree about what a value looks like.

func ThinkingLevels

func ThinkingLevels() []string

ThinkingLevels returns the accepted levels, in wire order. Exported so the public contract package can pin its own copy against this one — it may not import protocol (relayapi/doc.go: standard library only), and a set that drifts would let the edge accept a level admission rejects.

func TimingMSFromSeconds

func TimingMSFromSeconds(seconds float64) int64

TimingMSFromSeconds converts a provider's fractional-second timestamp to integer milliseconds, rounding rather than truncating: truncation biases every span low, and the bias accumulates visibly across a long render.

func TtsOptionNumber

func TtsOptionNumber(value any) (float64, bool)

TtsOptionNumber reads a numeric provider setting in any spelling JSON decoding or a Go caller can produce.

func ValidBillingUnit

func ValidBillingUnit(unit string) bool

func ValidLanguageTag

func ValidLanguageTag(tag string) bool

ValidLanguageTag is a BCP-47 shape check: a 2-3 letter primary subtag, then 1-8 character alphanumeric subtags, 35 characters in all. Shape only, not a registry lookup.

func ValidSTTLanguageTag added in v0.3.1

func ValidSTTLanguageTag(tag string) bool

ValidSTTLanguageTag is a BCP-47 shape check — a 2-3 letter primary subtag, then 1-8 character alphanumeric subtags — the same rule as relayapi.ValidSTTLanguageTag. The tag is written into a vendor config frame, so the check keeps arbitrary caller text out of it; whether the vendor translates into the language is the vendor's answer.

func ValidSpeechProtocol

func ValidSpeechProtocol(p SpeechProtocol) bool

ValidSpeechProtocol reports whether p names a known speech protocol.

func ValidThinkingLevel

func ValidThinkingLevel(level string) bool

ValidThinkingLevel reports whether a caller-supplied level is one the service accepts. Empty is valid and means "let the adapter decide".

func ValidTranslationOutputLanguage

func ValidTranslationOutputLanguage(language string) bool

ValidTranslationOutputLanguage reports whether language is a supported target language.

Types

type BidiOptions

type BidiOptions struct {
	// Setup is the validated `setup` object (the inner document, without its
	// wrapping key), forwarded verbatim apart from the pinned model.
	Setup json.RawMessage `json:"setup,omitempty"`
}

BidiOptions carries the caller's own Gemini Live setup document from the public /v1/bidi socket through to the adapter.

It exists because that route is native passthrough: the caller wrote a vendor setup object, the Router validated and bounded it, and the adapter must send THAT — not one re-derived from a handful of extracted fields, which would silently drop every vendor setting the Router had just accepted. The model is not taken from here: the adapter pins the admitted one, so a setup naming another model cannot move the session.

func (BidiOptions) Validate

func (o BidiOptions) Validate() error

Validate bounds the forwarded setup document.

type BillingAuthorization

type BillingAuthorization struct {
	Mode                string    `json:"mode"`
	State               string    `json:"state"`
	MaximumAmountMicros int64     `json:"maximum_amount_micros"`
	Currency            string    `json:"currency"`
	RenewalURL          string    `json:"renewal_url,omitempty"`
	RenewableUntil      time.Time `json:"renewable_until,omitempty"`
}

BillingAuthorization is the customer-visible financial authority attached to a managed provider-direct session. "estimated" means the maximum has been reserved but provider-authoritative reconciliation has not completed; "final" is only emitted by a settlement read, never by browser telemetry.

type BillingObservation

type BillingObservation struct {
	ProviderRequestID  string           `json:"provider_request_id,omitempty"`
	ProviderResponseID string           `json:"provider_response_id,omitempty"`
	OperationID        string           `json:"operation_id"`
	Model              string           `json:"model"`
	Mode               string           `json:"mode"`
	Quantities         map[string]int64 `json:"quantities"`
	// QuantityDenominators overrides the default 1000 for fractional duration, credits, or provider-reported USD.
	QuantityDenominators map[string]int64 `json:"quantity_denominators,omitempty"`
	Complete             bool             `json:"complete"`
	ContextTokens        int64            `json:"context_tokens,omitempty"`
	Channels             int64            `json:"channels,omitempty"`
	Language             string           `json:"language,omitempty"`
	Features             []string         `json:"features,omitempty"`
}

BillingObservation is the cumulative quantity snapshot of one upstream operation. Distinct responses/utterances/chunks require distinct OperationIDs. An incomplete observation can omit Model until the provider identifies it. A Complete observation is immutable; retrying it is harmless. Quantities are thousandths of the named billable unit, including explicitly measured zeros. Metadata contains classifications only, never request or response content.

func MergeBillingObservation

func MergeBillingObservation(previous, next BillingObservation) (BillingObservation, error)

MergeBillingObservation accepts monotonic cumulative snapshots and exact duplicates. It never sums two snapshots of the same operation.

func (BillingObservation) Clone

func (BillingObservation) QuantityDenominator

func (o BillingObservation) QuantityDenominator(unit string) int64

func (BillingObservation) Validate

func (o BillingObservation) Validate() error

type BillingReport

type BillingReport struct {
	Revision   int                  `json:"revision"`
	Complete   bool                 `json:"complete"`
	Operations []BillingObservation `json:"operations"`
}

BillingReport is the terminal, normalized evidence for an attempt. Complete means every dispatched operation is represented, not just that one finished.

func (BillingReport) Validate

func (r BillingReport) Validate() error

type CapacityAttribution

type CapacityAttribution struct {
	Account    string `json:"account"`
	Capability string `json:"capability"`
	Model      string `json:"model"`
	Slots      int64  `json:"slots"`
}

CapacityAttribution is public accounting metadata authenticated by the plan. It is not a grant, account credential, or proof that an old runtime enforces new fields. Only protocol-3 instance reports carry the resulting occupancy.

func (CapacityAttribution) Validate

func (c CapacityAttribution) Validate() error

type CapacityOccupancy

type CapacityOccupancy struct {
	Account    string `json:"account"`
	Capability string `json:"capability"`
	Model      string `json:"model"`
	Active     int64  `json:"active"`
	Pending    int64  `json:"pending"`
}

CapacityOccupancy carries actual verified active/opening sessions. Omitted attribution stays explicitly unknown; BYOK never becomes Speko account use.

type CapacitySnapshot

type CapacitySnapshot struct {
	Complete       bool                `json:"complete"`
	Accounts       []CapacityOccupancy `json:"accounts"`
	BYOKActive     int64               `json:"byok_active"`
	BYOKPending    int64               `json:"byok_pending"`
	UnknownActive  int64               `json:"unknown_active"`
	UnknownPending int64               `json:"unknown_pending"`
}

func (CapacitySnapshot) Validate

func (c CapacitySnapshot) Validate(active int64, pending int) error

type ConcurrencyReservation

type ConcurrencyReservation struct {
	LeaseID string `json:"lease_id"`
	Slots   int    `json:"slots"`
}

ConcurrencyReservation identifies the capacity lease consumed by this session. It is control-plane metadata, not a client-controlled limit. Settlement uses the lease ID alongside the reservation ID so a retry cannot release or charge a different concurrent session.

type CredentialKind

type CredentialKind string

CredentialKind identifies a bounded credential that can safely be placed in a customer-controlled runtime. It deliberately has no server-key variant.

const (
	CredentialBearer      CredentialKind = "bearer"
	CredentialSignedURL   CredentialKind = "signed_url"
	CredentialSessionURL  CredentialKind = "session_url"
	CredentialRelayAccess CredentialKind = "relay_access"
)

type CredentialSource

type CredentialSource string

CredentialSource identifies who owns the upstream credential.

const (
	CredentialsManaged CredentialSource = "managed"
	CredentialsBYOK    CredentialSource = "byok"
)

type DelegatedCredential

type DelegatedCredential struct {
	Kind      CredentialKind `json:"kind"`
	Value     string         `json:"value"`
	ExpiresAt time.Time      `json:"expires_at"`
}

DelegatedCredential must be scoped and short lived. Callers must never log Value, which is omitted by its String method.

func (DelegatedCredential) String

func (c DelegatedCredential) String() string

type Event

type Event struct {
	Type        EventType                  `json:"type"`
	EventID     string                     `json:"event_id"`
	SessionID   string                     `json:"session_id"`
	AttemptID   string                     `json:"attempt_id"`
	Sequence    uint64                     `json:"sequence"`
	CreatedAtMS int64                      `json:"created_at_ms"`
	Data        json.RawMessage            `json:"data,omitempty"`
	Extensions  map[string]json.RawMessage `json:"extensions,omitempty"`
	Audio       []byte                     `json:"-"`
}

Event is the canonical in-memory representation of a streaming server event. Audio is deliberately not JSON encoded: transports send it in binary frames and the embedded API preserves the supplied buffer without copying. Once delivered, Audio is owned by the consumer and must not be retained by the runtime.

type EventType

type EventType string

EventType is a provider-neutral streaming event name.

const (
	EventSessionReady      EventType = "session.ready"
	EventSessionRecovering EventType = "session.recovering"
	EventSessionRecovered  EventType = "session.recovered"
	EventSessionClosed     EventType = "session.closed"

	EventSpeechStarted    EventType = "speech.started"
	EventSpeechEnded      EventType = "speech.ended"
	EventTranscriptDelta  EventType = "transcript.delta"
	EventTranscriptFinal  EventType = "transcript.final"
	EventResponseStarted  EventType = "response.started"
	EventTextDelta        EventType = "text.delta"
	EventTextDone         EventType = "text.done"
	EventToolCall         EventType = "tool.call"
	EventResponseDone     EventType = "response.done"
	EventResponseCanceled EventType = "response.cancelled"
	EventAudioStarted     EventType = "audio.started"
	// EventAudioFrame is the in-memory marker for a binary TTS frame. WebSocket
	// transports carry the associated Event.Audio bytes in a binary frame.
	EventAudioFrame    EventType = "audio.frame"
	EventAudioDone     EventType = "audio.done"
	EventAlignment     EventType = "alignment"
	EventRouteSelected EventType = "route.selected"
	EventUsageObserved EventType = "usage.observed"
	// EventUsageReported is authenticated, content-free metering telemetry from
	// the Gateway. It reports only a normalized quantity, never media or text.
	EventUsageReported EventType = "usage.reported"
	// EventUsageFinalized closes the one successful use of an issued plan.
	// Failed opens and legacy usage.reported observations are not final usage.
	EventUsageFinalized EventType = "usage.finalized"
	EventWarning        EventType = "warning"
	EventError          EventType = "error"
	// EventProviderEvent surfaces one native provider event verbatim on a
	// speech-to-speech session (Data is a ProviderEvent envelope). It carries
	// delegation notices, nested Responses events, command acknowledgments,
	// and session updates whose native identifiers must survive untouched.
	EventProviderEvent EventType = "provider.event"
)

type Execution

type Execution struct {
	Placement        Placement        `json:"placement"`
	ProviderRoute    ProviderRoute    `json:"provider_route"`
	CredentialSource CredentialSource `json:"credential_source"`
}

Execution records the concrete route selected by the control plane.

type ExecutionRequest

type ExecutionRequest struct {
	ProviderRoute    ProviderRoute    `json:"provider_route"`
	CredentialSource CredentialSource `json:"credential_source"`
	RelayPolicy      RelayPolicy      `json:"relay_policy"`
}

ExecutionRequest expresses route constraints. RouteAuto is valid only here; returned SessionPlans always contain a concrete route.

type Fallback

type Fallback struct {
	ExchangeURL string `json:"exchange_url"`
}

Fallback provides the control-plane endpoint used only at an explicit recovery boundary.

type Integration

type Integration struct {
	Name             string `json:"name"`
	Version          string `json:"version"`
	FrameworkVersion string `json:"framework_version,omitempty"`
	Transport        string `json:"transport,omitempty"`
}

Integration identifies an optional framework integration without coupling the plan to framework-specific provider logic.

type LiveDelegation

type LiveDelegation struct {
	Type      LiveDelegationType   `json:"type"`
	Responses *LiveResponsesConfig `json:"responses,omitempty"`
}

LiveDelegation names the delegation mode and, for Responses delegation, the backend configuration.

func (*LiveDelegation) Mode

Mode returns the effective delegation type: an absent delegation is client delegation.

func (LiveDelegation) Validate

func (d LiveDelegation) Validate() error

Validate checks the delegation. Responses delegation requires an explicit backend model; client delegation carries no backend configuration.

type LiveDelegationType

type LiveDelegationType string

LiveDelegationType selects who runs delegated work for a GPT-Live session.

const (
	// LiveDelegationClient hands delegations to the application: the model
	// emits session.delegation.created and the caller answers with
	// session.commentary.append / session.thinking.append. The application
	// retains its own conversation and task state. This is the mode an
	// omitted or null delegation selects.
	LiveDelegationClient LiveDelegationType = "client"
	// LiveDelegationResponses lets GPT-Live call a Responses backend of the
	// caller's choosing. The backend model is required; function results and
	// continuations flow through response.item.create / response.create.
	LiveDelegationResponses LiveDelegationType = "responses"
)

type LiveHistoryItem

type LiveHistoryItem struct {
	Role string `json:"role"`
	Text string `json:"text"`
}

LiveHistoryItem is one prior text message.

func (LiveHistoryItem) Validate

func (h LiveHistoryItem) Validate() error

Validate checks one history item.

type LiveOptions

type LiveOptions struct {
	// History seeds the session with prior text turns (the vendor's session
	// `input`). Append-only afterwards: a running session takes context
	// through the append commands, never a replacement history.
	History []LiveHistoryItem `json:"history,omitempty"`
	// Delegation selects the delegation mode. Nil selects client delegation.
	Delegation *LiveDelegation `json:"delegation,omitempty"`
}

LiveOptions is the bounded GPT-Live session configuration beyond the voice, instructions, and media that every speech-to-speech session carries on S2SOptions. The voice instructions (S2SOptions.Instructions) steer the live model; backend instructions live on Delegation.Responses and are never merged into them.

func (LiveOptions) Validate

func (o LiveOptions) Validate() error

Validate checks the bounded GPT-Live configuration.

type LiveResponsesConfig

type LiveResponsesConfig struct {
	Model             string          `json:"model"`
	Instructions      string          `json:"instructions,omitempty"`
	Tools             []LiveTool      `json:"tools,omitempty"`
	ToolChoice        json.RawMessage `json:"tool_choice,omitempty"`
	ParallelToolCalls *bool           `json:"parallel_tool_calls,omitempty"`
	MaxOutputTokens   int             `json:"max_output_tokens,omitempty"`
	ServiceTier       string          `json:"service_tier,omitempty"`
	Reasoning         json.RawMessage `json:"reasoning,omitempty"`
	Text              json.RawMessage `json:"text,omitempty"`
}

LiveResponsesConfig configures the Responses backend GPT-Live delegates to. Model is required. Tools may be function definitions or web_search entries in the Responses tool schema; ToolChoice, Reasoning, and Text are forwarded verbatim within their size bounds because their shapes belong to the backend model, not to this contract.

func (LiveResponsesConfig) ToolTypes

func (c LiveResponsesConfig) ToolTypes() []LiveToolType

ToolTypes returns the distinct tool types the backend declares, in declaration order. Managed admission prices each of them.

func (LiveResponsesConfig) Validate

func (c LiveResponsesConfig) Validate() error

Validate checks the Responses backend configuration.

type LiveTool

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

LiveTool is one backend tool declaration kept verbatim: the function schema is customer content the backend interprets, so only the type tag and the function name are read here.

func NewLiveTool

func NewLiveTool(raw json.RawMessage) LiveTool

NewLiveTool wraps a raw Responses tool object.

func (LiveTool) MarshalJSON

func (t LiveTool) MarshalJSON() ([]byte, error)

MarshalJSON writes the tool verbatim.

func (LiveTool) Name

func (t LiveTool) Name() string

Name returns the function name for function tools, "" otherwise.

func (LiveTool) Raw

func (t LiveTool) Raw() json.RawMessage

Raw returns the tool declaration bytes.

func (LiveTool) Type

func (t LiveTool) Type() LiveToolType

Type returns the tool type tag ("function" or "web_search").

func (*LiveTool) UnmarshalJSON

func (t *LiveTool) UnmarshalJSON(data []byte) error

UnmarshalJSON keeps the tool verbatim.

func (LiveTool) Validate

func (t LiveTool) Validate() error

Validate checks the bounded tool declaration: a JSON object with a supported type tag, and a function name for function tools.

type LiveToolType

type LiveToolType string

LiveToolType is the tool kinds GPT-Live Responses delegation supports.

const (
	LiveToolFunction  LiveToolType = "function"
	LiveToolWebSearch LiveToolType = "web_search"
)

type MediaFormat

type MediaFormat struct {
	Encoding     string `json:"encoding"`
	SampleRateHz int    `json:"sample_rate_hz"`
	Channels     int    `json:"channels"`
}

MediaFormat describes unencoded audio supplied to or received from a streaming session.

func (MediaFormat) Validate

func (m MediaFormat) Validate() error

Validate checks that a portable audio format is within the current protocol bounds. Provider adapters may apply stricter documented constraints.

type Placement

type Placement string

Placement identifies where the runtime executes.

const (
	PlacementEmbedded Placement = "embedded"
	PlacementSidecar  Placement = "sidecar"
	PlacementClient   Placement = "client"
)

type PlanRoute

type PlanRoute struct {
	Provider string `json:"provider"`
	Model    string `json:"model"`
	// Voice is the control plane's choice for the provider it just selected,
	// used only when the caller did not name one. It exists because a caller
	// sending `provider: "auto"` cannot know which vendor it will get, and a
	// Cartesia voice id means nothing to ElevenLabs — so the party that picks
	// the vendor is the only one that can pick a voice for it. It is optional
	// because non-TTS routes do not select voices.
	Voice      string               `json:"voice,omitempty"`
	Region     string               `json:"region,omitempty"`
	Adapter    string               `json:"adapter"`
	Transport  Transport            `json:"transport"`
	Endpoint   string               `json:"endpoint"`
	Credential *DelegatedCredential `json:"credential,omitempty"`
}

PlanRoute contains no permanent Speko-owned provider credential.

type ProviderControl

type ProviderControl struct {
	Type    string          `json:"type"`
	Payload json.RawMessage `json:"payload"`
}

ProviderControl is one native client command forwarded on a speech-to-speech session.

func (ProviderControl) Validate

func (c ProviderControl) Validate(protocol SpeechProtocol) error

Validate checks the envelope against a protocol: allowed type, a JSON object payload within bounds whose own type tag matches the envelope.

type ProviderEvent

type ProviderEvent struct {
	Type    string          `json:"type"`
	Payload json.RawMessage `json:"payload"`
}

ProviderEvent is one native server event surfaced from a speech-to-speech session. It rides protocol.Event.Data under EventProviderEvent.

func (ProviderEvent) Validate

func (e ProviderEvent) Validate() error

Validate checks a surfaced event envelope.

type ProviderRoute

type ProviderRoute string

ProviderRoute identifies the remote hop selected for a session.

const (
	RouteAuto           ProviderRoute = "auto"
	RouteProviderDirect ProviderRoute = "provider_direct"
	RouteSpekoRelay     ProviderRoute = "speko_relay"
)

type RelayAccessCredential

type RelayAccessCredential struct {
	Value     string    `json:"value"`
	ExpiresAt time.Time `json:"expires_at"`
}

RelayAccessCredential is the one-use bearer that admits the edge to the connector named in the plan. Callers must never log Value, which is omitted by its String method.

func (RelayAccessCredential) String

func (c RelayAccessCredential) String() string

type RelayBudget

type RelayBudget struct {
	Group        RelayBudgetGroup `json:"group"`
	CeilingUnits int64            `json:"ceiling_units"`
}

RelayBudget is one signed spend ceiling. The ceiling is the connector's defense-in-depth guard and the ledger's settlement cap. Streaming sessions may extend a group later through lease slices or top-ups; extensions never edit the signed plan, so the plan always records what admission authorized.

type RelayBudgetGroup

type RelayBudgetGroup string

RelayBudgetGroup names an authorized spend bucket in a relay plan. Groups are deliberately coarser than units: settlement can split one group across several usage-line units (llm_input covers fresh input, cache reads and writes), but authorization is granted and capped per group.

const (
	RelayBudgetGroupSTTDuration     RelayBudgetGroup = "stt_duration"
	RelayBudgetGroupTTSCharacters   RelayBudgetGroup = "tts_characters"
	RelayBudgetGroupLLMInput        RelayBudgetGroup = "llm_input"
	RelayBudgetGroupLLMOutput       RelayBudgetGroup = "llm_output"
	RelayBudgetGroupEvaluationInput RelayBudgetGroup = "evaluation_input"
	// RelayBudgetGroupS2SDuration authorizes connected seconds of a
	// speech-to-speech session, denominated in duration_seconds like STT. The
	// session is metered by wall clock from provider connect to close: vendor
	// audio-token counts differ per vendor and cannot be guarded before the
	// audio is sent, so they stay telemetry evidence rather than the unit.
	RelayBudgetGroupS2SDuration RelayBudgetGroup = "s2s_duration"
	// RelayBudgetGroupBackendInput and RelayBudgetGroupBackendOutput authorize
	// the token spend of a GPT-Live Responses backend, denominated like the
	// llm groups (fresh + cached input; output + reasoning). They are separate
	// groups from s2s_duration so a Live reservation carries the voice lease
	// and the backend exposure as distinct, separately settled ceilings, and
	// separate from llm_input/llm_output so an s2s plan can never be read as
	// an LLM plan.
	RelayBudgetGroupBackendInput  RelayBudgetGroup = "backend_input"
	RelayBudgetGroupBackendOutput RelayBudgetGroup = "backend_output"
	// RelayBudgetGroupBackendTools authorizes billable hosted tool calls of a
	// GPT-Live Responses backend, in tool_calls.
	RelayBudgetGroupBackendTools RelayBudgetGroup = "backend_tools"
)

type RelayControlToken

type RelayControlToken struct {
	Value     string    `json:"value"`
	ExpiresAt time.Time `json:"expires_at"`
}

RelayControlToken authenticates content-free follow-up control-plane calls for one relay session. The control plane stores only its hash. Callers must never log Value, which is omitted by its String method.

func (RelayControlToken) String

func (t RelayControlToken) String() string

type RelayLease

type RelayLease struct {
	DurationSeconds int       `json:"duration_seconds"`
	ExpiresAt       time.Time `json:"expires_at"`
	RenewalURL      string    `json:"renewal_url"`
	TopUpURL        string    `json:"top_up_url,omitempty"`
}

RelayLease describes the first renewable accounting slice of a streaming relay session. Renewal extends accounting only, exactly like the rev-3 session lease: the provider stream and the relay access bearer are never reissued by a renewal. TopUpURL is present only when the session's budget groups can be extended mid-stream (TTS character top-ups).

type RelayPlan

type RelayPlan struct {
	PlanID        string `json:"plan_id"`
	RequestID     string `json:"request_id"`
	SessionID     string `json:"session_id"`
	AttemptID     string `json:"attempt_id"`
	ReservationID string `json:"reservation_id"`
	// OrganizationID and PrincipalID identify the paying customer.
	// PrincipalID is the credential identifier, never the key itself: relay
	// plans are content-free and safe to persist in the ledger.
	OrganizationID string `json:"organization_id"`
	PrincipalID    string `json:"principal_id"`
	// Kind is limited to stt, tts, llm, and s2s; the local gateway's realtime
	// kind has no relay execution contract.
	Kind SessionKind `json:"kind"`
	// Region is the Speko relay region (an AWS region identifier) whose
	// connector fleet must execute this plan, not a provider residency claim.
	Region    string    `json:"region"`
	Provider  string    `json:"provider"`
	Model     string    `json:"model"`
	Endpoint  string    `json:"endpoint"`
	Transport Transport `json:"transport"`
	// Protocol names the native speech protocol the model speaks; required
	// for s2s plans and absent otherwise. The connector verifies it against
	// its embedded catalog descriptor before any credential is read and
	// dispatches the matching adapter, so a plan can never make a Realtime
	// connector speak Live or vice versa.
	Protocol SpeechProtocol `json:"protocol,omitempty"`
	// CatalogDigest pins the release catalog the endpoint and model were
	// selected from, in "sha256:<64 hex>" form. A connector running a
	// different catalog release rejects the plan instead of guessing.
	CatalogDigest string `json:"catalog_digest"`
	// RateCardVersion records the rate card frozen into the attempt's price
	// lines at admission so settlement disputes are reconstructible.
	RateCardVersion string `json:"rate_card_version"`
	// CredentialSource names who owns the provider credential. It is signed
	// with every relay plan and must be managed or byok.
	CredentialSource CredentialSource `json:"credential_source"`
	// Budgets carries at least one group with a positive ceiling; groups are
	// unique and must be legal for Kind.
	Budgets []RelayBudget `json:"budgets"`
	// Lease is present for streaming sessions, whose accounting horizon is
	// extended in slices rather than reserved up front.
	Lease *RelayLease `json:"lease,omitempty"`
	// RelayAccess is the random one-use bearer the edge presents on the
	// connector handshake. It is bound into the signature so it cannot be
	// swapped onto another plan.
	RelayAccess RelayAccessCredential `json:"relay_access"`
	// ControlToken authorizes the edge's session-scoped follow-up calls to
	// the control plane (status, usage reports, renewals, top-ups, fallback).
	ControlToken RelayControlToken `json:"control_token"`
	ExpiresAt    time.Time         `json:"expires_at"`
	Requirements RelayRequirements `json:"requirements"`
	// Signature is a compact JWS over a RelayPlanEnvelope containing this
	// plan with Signature omitted. It is deliberately opaque to callers: only
	// a relay plan verifier may interpret it.
	Signature string `json:"signature,omitempty"`
}

RelayPlan is the signed relay execution decision. It is issued by the control plane at admission, carried by the edge, and consumed exactly once by the provider connector named in it. Endpoint is an assertion the connector checks against its embedded catalog, never a dial input, so a signed plan cannot redirect a connector to an attacker-chosen host. Signature verification is intentionally separate from structural validation.

func (RelayPlan) Unsigned

func (p RelayPlan) Unsigned() RelayPlan

Unsigned returns the exact plan representation that is signed inside a RelayPlanEnvelope. It is useful to control-plane code and test fixtures, but it deliberately does not attempt to create a signature.

func (RelayPlan) Validate

func (p RelayPlan) Validate(now time.Time) error

Validate verifies structural and time-bound invariants. It does not verify the signature; callers must do that with a trusted control-plane key first.

type RelayPlanEnvelope

type RelayPlanEnvelope struct {
	Issuer    string    `json:"iss"`
	Audience  []string  `json:"aud"`
	IssuedAt  time.Time `json:"iat"`
	ExpiresAt time.Time `json:"exp"`
	ID        string    `json:"jti"`
	Plan      RelayPlan `json:"plan"`
}

RelayPlanEnvelope is the payload of the compact JWS carried in RelayPlan.Signature. The control plane signs the full unsigned plan so a caller cannot transplant a valid signature onto a modified route, budget, or bearer.

The JSON field names intentionally follow registered JWT claim names even though this is a JWS envelope rather than a bearer identity token.

func (RelayPlanEnvelope) Validate

func (e RelayPlanEnvelope) Validate(now time.Time, issuer, audience string, clockSkew time.Duration) error

Validate checks envelope claims that are independent of the signature. A verifier must first verify the JWS and then call this method before using any endpoint or bearer in the enclosed plan.

type RelayPolicy

type RelayPolicy string

RelayPolicy constrains whether the control plane may select the relay route.

const (
	RelayRequired  RelayPolicy = "required"
	RelayAllowed   RelayPolicy = "allowed"
	RelayForbidden RelayPolicy = "forbidden"
)

type RelayRequirements

type RelayRequirements struct {
	Protocol         string `json:"protocol"`
	ProtocolRevision int    `json:"protocol_revision"`
}

RelayRequirements binds a relay plan to its exact protocol contract. It deliberately exact-matches RelayRevision rather than CurrentRevision so the rev-3 Requirements validator stays untouched and neither artifact can masquerade as the other.

type RelayUsageUnit

type RelayUsageUnit string

RelayUsageUnit identifies a provider quantity metered by the relay ledger. It is a separate enum from the rev-3 UsageUnit on purpose: rev-3 settlement exact-matches the two session-plan units, and widening that enum would change revision-3 acceptance behavior. Units appear on reservation and usage lines; the signed plan itself carries budgets keyed by RelayBudgetGroup.

const (
	RelayUsageUnitDurationSeconds   RelayUsageUnit = "duration_seconds"
	RelayUsageUnitCharacters        RelayUsageUnit = "characters"
	RelayUsageUnitInputTokens       RelayUsageUnit = "input_tokens"
	RelayUsageUnitCachedInputTokens RelayUsageUnit = "cached_input_tokens"
	// Cache writes are disjoint from ordinary input and cache reads. They
	// consume the same input budget, with prices depending on retention.
	RelayUsageUnitCacheWrite5mTokens RelayUsageUnit = "cache_write_5m_tokens"
	RelayUsageUnitCacheWrite1hTokens RelayUsageUnit = "cache_write_1h_tokens"
	RelayUsageUnitOutputTokens       RelayUsageUnit = "output_tokens"
	RelayUsageUnitReasoningTokens    RelayUsageUnit = "reasoning_tokens"
	// RelayUsageUnitToolCalls counts billable hosted tool invocations (web
	// search) a delegated GPT-Live backend performs. One call is one unit.
	RelayUsageUnitToolCalls RelayUsageUnit = "tool_calls"
)

type RequestOptions

type RequestOptions struct {
	Provider string `json:"provider,omitempty"`
	// ClientSessionID lets a trusted setup service allocate the public session
	// identifier before asking the control plane for a plan. The control plane
	// still binds it to the authenticated principal and idempotency key; it is
	// never accepted as billing identity on its own.
	ClientSessionID string `json:"client_session_id,omitempty"`
	// MaxSessionSeconds is the customer-visible hard ceiling requested by the
	// setup service. Policy may shorten it, but may never extend it.
	MaxSessionSeconds  int      `json:"max_session_seconds,omitempty"`
	MaxInputCharacters int64    `json:"max_input_characters,omitempty"`
	Language           string   `json:"language,omitempty"`
	Objective          string   `json:"objective,omitempty"`
	Model              string   `json:"model,omitempty"`
	Voice              string   `json:"voice,omitempty"`
	RegionHint         string   `json:"region_hint,omitempty"`
	Allow              []string `json:"allow,omitempty"`
	Deny               []string `json:"deny,omitempty"`
	// STT carries transcription feature asks and per-provider settings. Only
	// ever set on STT sessions; omitempty keeps every existing payload — and
	// every plan request an older control plane parses — byte-identical when
	// the caller asks for nothing.
	STT *SttOptions `json:"stt,omitempty"`
	// TTS carries per-provider synthesis settings. Only ever set on TTS
	// sessions; omitempty keeps every existing payload byte-identical when
	// the caller asks for nothing.
	TTS *TtsOptions `json:"tts,omitempty"`
	// S2S carries the local session-level asks of a provider-direct realtime
	// session. The gateway strips this content before requesting a hosted plan;
	// only the selected provider adapter reads it. Omitempty keeps every existing payload
	// byte-identical when the caller asks for nothing.
	S2S *S2SOptions `json:"s2s,omitempty"`
}

RequestOptions contains portable, provider-neutral session options.

type Requirements

type Requirements struct {
	Protocol         string `json:"protocol"`
	ProtocolRevision int    `json:"protocol_revision"`
	RuntimeVersion   string `json:"runtime_version"`
}

Requirements binds a plan to an exact implementation contract.

type Reservation

type Reservation struct {
	ID                   string                 `json:"id"`
	LeaseDurationSeconds int                    `json:"lease_duration_seconds"`
	LeaseExpiresAt       time.Time              `json:"lease_expires_at"`
	Concurrency          ConcurrencyReservation `json:"concurrency"`
	Usage                UsageReservation       `json:"usage"`
	Billing              *BillingAuthorization  `json:"billing,omitempty"`
}

Reservation describes the fixed capacity and usage bounds for a session.

type RuntimeDescriptor

type RuntimeDescriptor struct {
	Name           string          `json:"name"`
	Version        string          `json:"version"`
	InstanceID     string          `json:"instance_id"`
	IncarnationID  string          `json:"incarnation_id,omitempty"`
	Placement      Placement       `json:"placement"`
	ProviderRoutes []ProviderRoute `json:"provider_routes"`
	Adapters       []string        `json:"adapters"`
	// Region is where the runtime runs, in its cloud's spelling
	// (asia-southeast1, ap-northeast-1). Optional; the control plane uses it
	// to plan a provider deployment near the runtime.
	Region string `json:"region,omitempty"`
}

RuntimeDescriptor describes the implementation that will execute the plan.

func (RuntimeDescriptor) Validate

func (r RuntimeDescriptor) Validate() error

Validate checks the descriptor a runtime sends with every plan request, so a process can refuse a bad configuration at startup rather than per session.

type S2SOptions

type S2SOptions struct {
	// Instructions is the system prompt the model speaks under. Customer
	// content: adapters place it on the vendor wire and nothing else reads it.
	Instructions string `json:"instructions,omitempty"`
	// Temperature is the sampling temperature; nil leaves the vendor default.
	Temperature *float64 `json:"temperature,omitempty"`
	// OutputMedia is the format of the audio the model speaks back. Input
	// audio rides AdapterRequest.Media like every speech session.
	OutputMedia *MediaFormat `json:"output_media,omitempty"`
	// Live carries the GPT-Live-only configuration: seeded history and the
	// delegation mode with its backend settings. Nil on every other
	// speech-to-speech protocol; a Live adapter treats nil as client
	// delegation with no history.
	Live *LiveOptions `json:"live,omitempty"`
	// Bidi carries the Gemini-Live-only configuration. Nil on every other
	// speech-to-speech protocol, and nil on a Gemini session the Router
	// composed itself (the provider-direct path), where the adapter builds a
	// setup document from Instructions, Voice and Temperature as before.
	Bidi *BidiOptions `json:"bidi,omitempty"`
	// ThinkingLevel is how much a Gemini Live model thinks before it speaks.
	// Empty leaves the adapter's model-derived answer, which is the only safe
	// default: the level is a property of the MODEL, not a preference.
	// Verified against the service on 2026-09-16 —
	// gemini-3.8-live-extended-thinking closes 1007 "Thinking level must be
	// specified for this model" WITHOUT one, and every other Live model closes
	// 1007 "Thinking level is not supported for this model" WITH one. So an
	// adapter must supply it where it is mandatory and drop it everywhere
	// else, whatever a caller asks for.
	ThinkingLevel string `json:"thinking_level,omitempty"`
}

S2SOptions are the portable session settings of a speech-to-speech session: what the model is told, how deterministic it should be, and the audio format the caller wants back. Voice and language ride the enclosing RequestOptions like they do for TTS.

type SessionKind

type SessionKind string

SessionKind selects the provider-neutral operation requested by a session.

const (
	SessionKindSTT SessionKind = "stt"
	SessionKindTTS SessionKind = "tts"
	SessionKindLLM SessionKind = "llm"
	// SessionKindEvaluation is a hosted Router-only typed decision request.
	// It is accepted by relay plans and deliberately rejected by revision-3
	// provider-direct session plans.
	SessionKindEvaluation SessionKind = "evaluation"
	SessionKindRealtime   SessionKind = "realtime"
	// SessionKindS2S is a reserved legacy wire value with no public Relay route.
	// New speech-to-speech sessions use SessionKindRealtime and execute in the
	// customer-side gateway with a provider-direct SessionPlan.
	//
	// The two kinds are mirror images, and both exclusions are deliberate:
	// relay plans reject realtime (validRelayKind), and revision-3 session
	// plans reject s2s (validKind below). A session plan is executed by the
	// local runtime Engine, which has no s2s arm; accepting the kind there
	// would admit a plan the runtime cannot serve, which is worse than
	// refusing it. Both refusals are pinned by tests.
	SessionKindS2S SessionKind = "s2s"
)

type SessionPlan

type SessionPlan struct {
	PlanID       string               `json:"plan_id"`
	SessionID    string               `json:"session_id"`
	AttemptID    string               `json:"attempt_id"`
	Execution    Execution            `json:"execution"`
	ExpiresAt    time.Time            `json:"expires_at"`
	Route        PlanRoute            `json:"route"`
	Reservation  Reservation          `json:"reservation"`
	Telemetry    Telemetry            `json:"telemetry"`
	Capacity     *CapacityAttribution `json:"capacity,omitempty"`
	Fallback     *Fallback            `json:"fallback,omitempty"`
	Requirements Requirements         `json:"requirements"`
	// Signature is a compact JWS over a SessionPlanEnvelope containing this
	// plan with Signature omitted. It is deliberately opaque to callers: only
	// a runtime PlanVerifier may interpret it.
	Signature string `json:"signature,omitempty"`
}

SessionPlan is the signed execution decision consumed by the runtime. Signature verification is intentionally separate from structural validation.

func (SessionPlan) CredentialDigestBoundUnsigned

func (p SessionPlan) CredentialDigestBoundUnsigned() (SessionPlan, error)

CredentialDigestBoundUnsigned returns the non-executable plan representation used only inside a credential-digest JWS envelope. The delegated credential value is replaced with a deterministic SHA-256 binding; a verifier repeats this transformation over the supplied plan, so changing the bearer still invalidates the signature without placing the potentially large bearer in the KMS signing input.

func (SessionPlan) Unsigned

func (p SessionPlan) Unsigned() SessionPlan

Unsigned returns the exact plan representation that is signed inside a SessionPlanEnvelope. It is useful to control-plane clients and test fixtures, but it deliberately does not attempt to create a signature.

func (SessionPlan) UsesFundedContinuation added in v0.3.1

func (p SessionPlan) UsesFundedContinuation() bool

UsesFundedContinuation selects the issued-plan family even when its token is malformed. This classification is not authentication or execution authority.

func (SessionPlan) Validate

func (p SessionPlan) Validate(now time.Time) error

Validate verifies structural and time-bound invariants. It does not verify the signature; callers must do that with a trusted control-plane key first.

type SessionPlanEnvelope

type SessionPlanEnvelope struct {
	Issuer    string      `json:"iss"`
	Audience  []string    `json:"aud"`
	IssuedAt  time.Time   `json:"iat"`
	ExpiresAt time.Time   `json:"exp"`
	ID        string      `json:"jti"`
	Plan      SessionPlan `json:"plan"`
}

SessionPlanEnvelope is the payload of the compact JWS carried in SessionPlan.Signature. The control plane signs the full unsigned plan so a caller cannot transplant a valid signature onto a modified route, reservation, or delegated credential.

The JSON field names intentionally follow registered JWT claim names even though this is a JWS envelope rather than a bearer identity token.

func (SessionPlanEnvelope) Validate

func (e SessionPlanEnvelope) Validate(now time.Time, issuer, audience string, clockSkew time.Duration) error

Validate checks envelope claims that are independent of the signature. A verifier must first verify the JWS and then call this method before using any route or credential in the enclosed plan.

type SessionPlanRequest

type SessionPlanRequest struct {
	Kind             SessionKind       `json:"kind"`
	Protocol         string            `json:"protocol"`
	ProtocolRevision int               `json:"protocol_revision"`
	Runtime          RuntimeDescriptor `json:"runtime"`
	Workload         *Workload         `json:"workload,omitempty"`
	Integration      *Integration      `json:"integration,omitempty"`
	Execution        ExecutionRequest  `json:"execution"`
	Request          RequestOptions    `json:"request"`
	Media            *MediaFormat      `json:"media,omitempty"`
}

SessionPlanRequest is the control-plane request made before a new local or embedded session opens. ProtocolRevision mirrors the protocol header so JSON fixtures can validate the full request contract in one place.

func (SessionPlanRequest) Validate

func (r SessionPlanRequest) Validate() error

Validate rejects a request before any media is accepted or a plan is sought.

type SpeechProtocol

type SpeechProtocol string

SpeechProtocol names the native wire protocol a speech-to-speech model speaks. It is the dispatch key that lets two OpenAI voice adapters coexist under one provider: gpt-realtime-* models speak the Realtime protocol on wss://api.openai.com/v1/realtime, while gpt-live-1 speaks the Live protocol on wss://api.openai.com/v1/live/sessions. Catalog rows carry the protocol, signed relay plans assert it, connectors verify it before touching a credential, and the Router exposes the realtime-shaped protocols, GPT-Live, Gemini Live, and Alibaba LiveTranslate natively on their own public routes (/v1/realtime, /v1/live, /v1/bidi, /v1/realtime/translations/qwen).

const (
	// SpeechProtocolOpenAIRealtimeV1 is the OpenAI Realtime event protocol
	// (input_audio_buffer.append, response.output_audio.delta, ...). Public
	// route: GET /v1/realtime?model=<id>.
	SpeechProtocolOpenAIRealtimeV1 SpeechProtocol = "openai.realtime.v1"
	// SpeechProtocolOpenAILiveV1 is the GPT-Live event protocol
	// (session.start, session.input_audio.append, session.output_audio.delta,
	// delegation and response.event envelopes). Public route: GET /v1/live;
	// the model rides the initial session.start frame.
	SpeechProtocolOpenAILiveV1 SpeechProtocol = "openai.live.v1"
	// SpeechProtocolGoogleLiveV1 is Gemini Live (BidiGenerateContent), served
	// natively on /v1/bidi. Unlike the two OpenAI protocols its frames are
	// KEY-tagged (`{"setup":…}`, `{"realtimeInput":…}`) rather than carrying a
	// "type" field, so it uses the BidiControl family below instead of
	// ProviderControl.
	SpeechProtocolGoogleLiveV1 SpeechProtocol = "google.live.v1"
	// SpeechProtocolXAIRealtimeV1 is xAI Grok Voice, a Realtime-shaped
	// protocol with its own session body. Public route: GET
	// /v1/realtime?model=<id>; the exact model selects this protocol.
	SpeechProtocolXAIRealtimeV1 SpeechProtocol = "xai.realtime.v1"
	// SpeechProtocolOpenAIRealtimeTranslationV1 is OpenAI realtime speech
	// translation (gpt-realtime-translate) on the vendor's dedicated
	// wss://api.openai.com/v1/realtime/translations socket — the only
	// endpoint the model accepts. It is NOT the conversational Realtime
	// protocol: the session carries a target language and nothing else (no
	// voice, instructions, tools, conversation items or response.create),
	// audio rides session.input_audio_buffer.append, and the answer is a
	// continuous stream of session.output_audio.delta and transcript deltas
	// rather than responses. Public route: GET
	// /v1/realtime/translations?model=<id>.
	SpeechProtocolOpenAIRealtimeTranslationV1 SpeechProtocol = "openai.realtime.translation.v1"
	// SpeechProtocolAlibabaLiveTranslateV1 is Alibaba Model Studio's
	// LiveTranslate event protocol (qwen3.8-livetranslate-flash-realtime):
	// speech in, translated speech and text out, with no assistant turn and
	// no response.create. It reuses the Realtime event NAMES
	// (input_audio_buffer.append, response.audio.delta, response.done) but
	// not their meaning: the session body carries translation.language
	// instead of instructions and tools, turns are cut by the vendor's own
	// VAD, and the session must end with session.finish or the final segment
	// is never translated. Sharing /v1/realtime would advertise a
	// conversational surface this socket does not have, so it gets its own
	// public route: GET /v1/realtime/translations/qwen?model=<id>.
	SpeechProtocolAlibabaLiveTranslateV1 SpeechProtocol = "alibaba.livetranslate.v1"
)

func (SpeechProtocol) PublicRoute

func (p SpeechProtocol) PublicRoute() string

PublicRoute returns the Router route path that exposes this protocol natively, or "" for protocols the Router does not expose.

type SpeechTimings

type SpeechTimings struct {
	Granularity TimingGranularity `json:"granularity,omitempty"`
	Spans       []TimingSpan      `json:"spans,omitempty"`
}

SpeechTimings is the normalized part of an EventAlignment payload for a TTS adapter. Adapters embed these two keys alongside whatever native timing arrays they already carry, so the raw provider reading stays available for debugging while consumers read one shape across providers.

The zero value is the "measured nothing" case and is what an adapter emits for a frame it cannot or must not normalize — an empty alignment, or a reading taken over normalized rather than caller-supplied text. Consumers treat an empty Spans as "stay silent" rather than as an error.

This shape is NOT emitted by the STT adapters that also use EventAlignment; it is specific to synthesis.

func TimingSpansFromMillisecondDurations

func TimingSpansFromMillisecondDurations(texts []string, starts, durations []int, granularity TimingGranularity) SpeechTimings

TimingSpansFromMillisecondDurations builds spans from parallel arrays of text, start milliseconds, and DURATION milliseconds — the shape ElevenLabs sends on its streaming transport. The end time is the sum, so the caller never has to know which of the two the provider meant.

Disagreeing array lengths return nil, for the reason given on TimingSpansFromSeconds.

func TimingSpansFromSeconds

func TimingSpansFromSeconds(texts []string, starts, ends []float64, granularity TimingGranularity) SpeechTimings

TimingSpansFromSeconds builds spans from parallel arrays of text, start seconds, and END seconds — the shape Cartesia and Soniox send.

Disagreeing array lengths return nil rather than a partial reading: the arrays are one measurement split three ways, so a length mismatch means the frame was not understood, and half-decoding it would emit spans whose text and times belong to different positions.

type SttOptions

type SttOptions struct {
	// Diarization labels each transcript segment with the speaker who said it.
	// A pointer, not a bool: nil means the caller said nothing and the vendor
	// default stands, which is not the same as an explicit false.
	Diarization *bool `json:"diarization,omitempty"`
	// LanguageIdentification asks for spoken-language labels on streaming
	// transcript spans. Nil and false leave the adapter's legacy behavior.
	LanguageIdentification *bool `json:"language_identification,omitempty"`
	// Keywords biases recognition toward domain terms (names, products,
	// jargon). Adapters translate to the vendor's own spelling: Deepgram
	// keyterm/keywords, AssemblyAI keyterms_prompt, ElevenLabs keyterms,
	// Soniox context terms, Gladia custom vocabulary, OpenAI prompt text.
	Keywords []string `json:"keywords,omitempty"`
	// NoiseReduction asks the provider to clean the audio before transcribing.
	// Canonical rather than a provider option because the one evidenced wire
	// shape (Gladia pre_processing.audio_enhancer) is a nested object, and
	// provider option values are deliberately scalar-only.
	NoiseReduction *bool `json:"noise_reduction,omitempty"`
	// WordTimestamps asks for per-word start/end timings on a batch
	// transcription. Fails closed like Diarization: a route whose adapter
	// cannot return them is refused with the option named. Only prerecorded
	// (batch) adapters can honor it today.
	WordTimestamps *bool `json:"word_timestamps,omitempty"`
	// Translation asks for the spoken audio translated into TargetLanguage
	// alongside the transcript. Fails closed like Diarization. Adapters keep
	// the original words in transcript `text` and put the translated words in
	// a separate `translation` field of the same event, so a consumer that
	// predates translation never reads a second language as the transcript.
	Translation *SttTranslation `json:"translation,omitempty"`
	// ProviderOptions maps a provider name to that vendor's own settings,
	// e.g. {"deepgram": {"numerals": true}, "elevenlabs":
	// {"vad_silence_threshold_secs": 0.7}}. Scalars only; each adapter
	// forwards only the keys it allow-lists and refuses the rest by name.
	ProviderOptions map[string]map[string]any `json:"provider_options,omitempty"`
}

SttOptions carries what a caller asked a transcription session to do beyond returning text. The canonical fields use the same vocabulary as the Speko platform API's provider params, so a caller moving between the hosted API and this gateway does not learn a second spelling.

Canonical asks are provider-neutral and fail closed: a session routed to a provider that cannot honor one is refused with the option named, never answered 200 with the feature silently missing. A diarization request served by a provider that cannot diarize is indistinguishable from a one-speaker recording, so nobody would ever report it.

ProviderOptions are the vendor's OWN settings, namespaced by provider name. They never fail a route: settings for a provider the session does not reach are ignored by design, so a caller can tune two providers and let routing decide which one reads its own.

func (*SttOptions) Diarize

func (o *SttOptions) Diarize() bool

Diarize reports whether the caller asked for speaker labels.

func (*SttOptions) GetKeywords

func (o *SttOptions) GetKeywords() []string

GetKeywords returns the caller's vocabulary-biasing terms, trimmed. Nil-safe so adapters can ask unconditionally.

func (*SttOptions) IdentifyLanguage added in v0.3.1

func (o *SttOptions) IdentifyLanguage() bool

IdentifyLanguage reports whether the caller asked for language labels.

func (*SttOptions) IsZero

func (o *SttOptions) IsZero() bool

IsZero reports whether the caller asked for nothing, which is every request that predates this type.

func (*SttOptions) Normalize

func (o *SttOptions) Normalize() error

Normalize folds provider and setting names to lower case and validates shape and bounds. Folding happens here, once, because validation folds case and map lookup cannot: a document written {"Deepgram":{"Numerals":true}} must not validate and then match nothing at the adapter — accepted but silently never forwarded is the failure mode this type exists to prevent.

Normalize checks SHAPE only. Whether a named provider exists and whether it accepts a named setting are routing-time questions answered against the deployment's support table, which this package does not have.

func (*SttOptions) Provider

func (o *SttOptions) Provider(name string) map[string]any

Provider returns the caller's settings for one provider, already normalized to lower-case names by Normalize. Nil when nothing was sent, so an adapter can range over it unconditionally.

func (*SttOptions) ProviderKeys

func (o *SttOptions) ProviderKeys(name string) []string

ProviderKeys returns the caller's setting names for one provider in a stable order, so a URL built from them is byte-identical run to run.

func (*SttOptions) ReduceNoise

func (o *SttOptions) ReduceNoise() bool

ReduceNoise reports whether the caller asked for audio enhancement.

func (*SttOptions) TranslationTarget

func (o *SttOptions) TranslationTarget() string

TranslationTarget returns the trimmed target language, or "" when no translation was asked for. Nil-safe so adapters can ask unconditionally.

func (*SttOptions) WantsWordTimestamps

func (o *SttOptions) WantsWordTimestamps() bool

WantsWordTimestamps reports whether the caller asked for per-word timings.

type SttTranslation

type SttTranslation struct {
	TargetLanguage string `json:"target_language"`
}

SttTranslation is a one-way translation target: whatever is spoken is translated into TargetLanguage, a BCP-47 tag.

type Telemetry

type Telemetry struct {
	Endpoint        string `json:"endpoint,omitempty"`
	Token           string `json:"token,omitempty"`
	FlushIntervalMS int    `json:"flush_interval_ms,omitempty"`
}

Telemetry identifies an asynchronous, session-scoped authenticated destination. It is empty for locally issued plans, whose anonymous default destination belongs to the exporter rather than the signed routing plan.

type TimingGranularity

type TimingGranularity string

TimingGranularity is the unit a TimingSpan measures. It is always what the provider itself measured, never a conversion: a character-level engine reports TimingGranularityCharacter, and grouping those characters into words is left to whoever knows where the words are in the source text.

const (
	TimingGranularityWord      TimingGranularity = "word"
	TimingGranularityCharacter TimingGranularity = "character"
)

type TimingSpan

type TimingSpan struct {
	Text    string `json:"text"`
	StartMS int64  `json:"start_ms"`
	EndMS   int64  `json:"end_ms"`
}

TimingSpan is one time-aligned span of synthesized speech, measured in integer milliseconds from the start of the utterance. EndMS is an end time, never a duration, because providers disagree about which they send and a normalized event must not make the consumer guess.

Spans are individually well-formed but are NOT mutually ordered: engines legitimately return adjacent spans that overlap, where one sound is still being articulated as the next begins, and zero-width spans occur for characters that carry no measurable duration of their own.

type TranslationSessionUpdate

type TranslationSessionUpdate struct {
	EventID string
	// Language is the target language, "" when this update leaves it as is.
	Language string
	// TranscriptionModel is the source-transcript model, "" when unchanged.
	// TranscriptionDisabled reports an explicit null.
	TranscriptionModel    string
	TranscriptionDisabled bool
	// NoiseReduction is the noise reduction type, "" when unchanged.
	// NoiseReductionDisabled reports an explicit null.
	NoiseReduction         string
	NoiseReductionDisabled bool
}

TranslationSessionUpdate is the decoded, validated translation session.update. The hop forwards the caller's own bytes once they validate (native identifiers such as event_id survive); this value is what the hop learned from them.

func ValidateTranslationSessionUpdate

func ValidateTranslationSessionUpdate(payload []byte) (TranslationSessionUpdate, error)

ValidateTranslationSessionUpdate strictly decodes a translation session.update. Unknown fields are refused at every level.

type Transport

type Transport string

Transport describes the upstream protocol selected in a session plan.

const (
	TransportWebSocket Transport = "websocket"
	TransportHTTP      Transport = "http"
	TransportGRPC      Transport = "grpc"
	TransportWebRTC    Transport = "webrtc"
)

type TtsOptionError

type TtsOptionError struct {
	Provider string
	Key      string
	Detail   string
}

TtsOptionError is a provider setting the routed provider's adapter refuses: a key it does not forward on this model, or a value outside the range the vendor accepts. Out-of-range values matter as much as unknown keys here: ElevenLabs answers an out-of-range voice setting on its multi-context socket with no audio and no error frame, so the only useful refusal is ours.

func (*TtsOptionError) Error

func (e *TtsOptionError) Error() string

func (*TtsOptionError) Option

func (e *TtsOptionError) Option() string

Option is the dotted name the refusal is about, for error envelopes that name the ask.

type TtsOptions

type TtsOptions struct {
	ProviderOptions map[string]map[string]any `json:"provider_options,omitempty"`
}

TtsOptions carries per-provider synthesis settings: the vendor's OWN knobs, namespaced by provider name, e.g. {"cartesia": {"normalization": "en-IN"}, "elevenlabs": {"stability": 0.4}}.

Like SttOptions.ProviderOptions, settings for a provider the session does not reach are ignored by design, and settings for the routed provider fail closed: each adapter owns an allow-list (its package's ValidateTTSOptions) and a key outside it is refused by name before a provider is dialed, never forwarded or dropped.

func (*TtsOptions) IsZero

func (o *TtsOptions) IsZero() bool

IsZero reports whether the caller asked for nothing.

func (*TtsOptions) Normalize

func (o *TtsOptions) Normalize() error

Normalize folds provider and setting names to lower case and validates shape and bounds, exactly as SttOptions.Normalize does and for the same reason: a setting that validates under one casing and then matches nothing at the adapter is accepted-but-ignored.

func (*TtsOptions) Provider

func (o *TtsOptions) Provider(name string) map[string]any

Provider returns the caller's settings for one provider. Nil when nothing was sent, so an adapter can range over it unconditionally.

type UsageReservation

type UsageReservation struct {
	Unit            UsageUnit `json:"unit"`
	AuthorizedUnits int64     `json:"authorized_units"`
}

UsageReservation is the fixed provider-usage allowance committed before a credential is minted.

type UsageUnit

type UsageUnit string

UsageUnit identifies the provider quantity whose spend was authorized by a reservation. Session time and usage authorization are deliberately separate.

const (
	UsageUnitDurationSeconds UsageUnit = "duration_seconds"
	UsageUnitCharacters      UsageUnit = "characters"
)

type VoiceSessionConfigure

type VoiceSessionConfigure struct {
	Protocol     SpeechProtocol `json:"protocol"`
	Media        MediaFormat    `json:"media"`
	OutputMedia  MediaFormat    `json:"output_media"`
	Voice        string         `json:"voice,omitempty"`
	Instructions string         `json:"instructions,omitempty"`
	Live         *LiveOptions   `json:"live,omitempty"`
	// Bidi carries the caller's Gemini Live setup document on the native
	// /v1/bidi route. Nil on every other protocol.
	Bidi *BidiOptions `json:"bidi,omitempty"`
	// ThinkingLevel asks a Gemini Live model to think harder before speaking.
	// Carried through to S2SOptions so the adapter sees what the caller asked
	// for; the adapter still decides whether this model may have one at all.
	ThinkingLevel string `json:"thinking_level,omitempty"`
}

VoiceSessionConfigure rides the connector handshake of a native speech-to-speech relay session (the Router's /v1/realtime and /v1/live). The edge builds it from what it admitted — the protocol, both audio directions, the resolved voice, the voice instructions, and for GPT-Live the bounded history and delegation — and the connector opens the provider from it immediately after verification. The connector refuses a configure whose protocol differs from the verified plan's protocol claim.

func (VoiceSessionConfigure) Options

Options converts the configure into the adapter request options the speech adapters read.

func (VoiceSessionConfigure) Validate

func (c VoiceSessionConfigure) Validate() error

Validate checks the configure document.

type Workload

type Workload struct {
	Type string `json:"type"`
	ID   string `json:"id"`
}

Workload identifies the customer-owned logical workload that opened a session. It is deliberately framework-neutral: a managed Speko agent is one workload type, while a customer can use another stable type/id pair for a custom service. The identifier is operational metadata only and carries no prompt, transcript, or user content.

func (Workload) Validate

func (w Workload) Validate() error

Validate checks the bounded, content-free workload identity contract.

Jump to

Keyboard shortcuts

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