runtime

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: 28 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 runtime implements the embedded provider-neutral session engine.

Index

Constants

View Source
const (
	// SessionPlanJWSType prevents a key intended for another control-plane
	// artifact from being used to authorize a provider connection.
	SessionPlanJWSType = "speko.session-plan+jws"
	// SessionPlanCredentialDigestJWSType is accepted only for session plans
	// and binds the actual delegated credential through its SHA-256 digest.
	SessionPlanCredentialDigestJWSType = protocol.SessionPlanCredentialDigestJWSType
)
View Source
const DefaultMaxReplayEntries = 65_536

DefaultMaxReplayEntries bounds retained keys in each Engine/default verifier.

Variables

View Source
var (
	// ErrPlanReplay is returned when an otherwise-valid signed plan is used
	// more than once within its envelope lifetime or after its signed horizon
	// has been retired from a bounded funded cache.
	ErrPlanReplay = errors.New("runtime: signed session plan has already been used")
	// ErrReplayCacheFull refuses new work rather than evicting live replay guards.
	ErrReplayCacheFull = errors.New("runtime: replay cache capacity exhausted")
	// ErrPlanSignature is returned for malformed, tampered, or unsupported
	// compact JWS values. It never includes raw credentials or JWS contents.
	ErrPlanSignature = errors.New("runtime: invalid signed session plan")
)
View Source
var (
	// ErrBackpressure means a bounded session queue is full. The caller retains
	// ownership of the rejected AudioInput and may retry or release it.
	ErrBackpressure = errors.New("runtime: backpressure")
	// ErrFrameTooLarge means a frame cannot ever fit in the configured bounded
	// audio queue. The caller retains ownership of the rejected input.
	ErrFrameTooLarge = errors.New("runtime: audio frame exceeds queue limit")
	// ErrSessionClosed means an input was submitted after the session started
	// closing. The caller retains ownership of any rejected audio input.
	ErrSessionClosed = errors.New("runtime: session is closed")
	// ErrNothingToCommit means a text commit found no open utterance to end:
	// nothing was appended since the last one, or it was already committed.
	// The provider stream stays usable.
	ErrNothingToCommit = errors.New("runtime: nothing to commit")
	// ErrSessionAborted means the runtime force-terminated the provider stream
	// because its local consumer or transport could not continue safely.
	ErrSessionAborted = errors.New("runtime: session aborted")
	// ErrSessionLeaseExpired means the session reached its fixed deadline.
	ErrSessionLeaseExpired = errors.New("runtime: session lease expired")
	// ErrUsageLimitExceeded means accepting the input would exceed the fixed
	// provider-usage allowance in the signed reservation. Lease renewal cannot
	// increase this allowance.
	ErrUsageLimitExceeded = errors.New("runtime: authorized usage exceeded")
	// ErrUnsupportedOperation means the selected kind cannot accept that input.
	ErrUnsupportedOperation = errors.New("runtime: unsupported session operation")
	// ErrOutputBackpressure means the consumer did not drain canonical events
	// within the configured bound. The session emits a terminal error event.
	ErrOutputBackpressure = errors.New("runtime: event consumer is too slow")
	// ErrPlanUnverified prevents accidental use of a plan without a configured
	// signature verifier.
	ErrPlanUnverified = errors.New("runtime: session plan was not verified")
)
View Source
var ErrFundedGoogleAdapter = errors.New("runtime: funded Google adapter is not supported")

ErrFundedGoogleAdapter refuses unknown adapter implementations without treating their funded Google plans as ordinary local-clock sessions.

View Source
var ErrFundedGoogleClockAuthority = errors.New("runtime: funded Google plan has no signed clock authority")

ErrFundedGoogleClockAuthority refuses a funded shape whose current signed plan supplies no accepted clock endpoint. It never falls into OSS admission.

View Source
var ErrResumptionUnavailable = errors.New("runtime: provider resumption handle unavailable")

Functions

func ProviderPhysicalDeadline added in v0.3.1

func ProviderPhysicalDeadline(ctx context.Context) time.Time

ProviderPhysicalDeadline returns the Engine's already validated monotonic replacement cap. It is independent of a caller/setup context's deadline and must be retained through setup, handoff and physical teardown. A zero value means the Engine did not supply a funded replacement cap. A SQL refresh may shorten this same pending cap; reading it never renews its original lifetime.

func SanitizeProviderCode added in v0.3.1

func SanitizeProviderCode(s string) string

SanitizeProviderCode admits s as a provider's machine-readable error code: 1 to 64 bytes of ASCII letters, digits, '_', '.', ':' and '-'. Anything else returns "": a message (it has spaces), a URL, JSON, control characters, or non-ASCII text. The check is on shape only. A credential can be letters and digits too, so a consumer that persists the code (a log line, a metric) admits it against its own list of known codes as well.

Types

type AbortingProviderStream

type AbortingProviderStream interface {
	Abort(context.Context) error
}

AbortingProviderStream provides serialized teardown after the runtime becomes terminal. Immediate concurrent physical interruption uses the separate InterruptingProviderStream capability. Normal input draining uses ProviderStream.Close first; cleanup joins teardown before capacity release.

type Adapter

type Adapter interface {
	ID() string
	Open(context.Context, AdapterRequest) (ProviderStream, error)
}

Adapter is the one provider-specific implementation point in the embedded engine. Framework integrations must use Session rather than this interface.

type AdapterRequest

type AdapterRequest struct {
	// Continuation requests a stable ResumableProviderStream event source.
	Continuation bool
	// PhysicalDeadline is an optional monotonic cap derived by the Engine from
	// verified funding. It survives setup-context cancellation and a delayed
	// Open return. It never creates authority or extends signed time bounds.
	PhysicalDeadline time.Time
	Kind             protocol.SessionKind
	Plan             protocol.SessionPlan
	Options          protocol.RequestOptions
	Media            *protocol.MediaFormat
	// Delivery identifies whether audio is arriving at real-time cadence or
	// from a buffered upload. Adapters that require real-time pacing use it to
	// pace only buffered input and avoid adding latency to live streams.
	Delivery AudioDeliveryMode
	// RefreshCredential, when non-nil, mints a fresh credential for this
	// attempt. It is set only for managed provider-direct plans; BYOK and relay
	// credentials are permanent keys an adapter can simply reuse.
	RefreshCredential CredentialRefresher
}

AdapterRequest contains the concrete, already-validated execution choice.

type AudioDeliveryMode

type AudioDeliveryMode string

AudioDeliveryMode describes the cadence of audio supplied to an adapter.

const (
	AudioDeliveryLive     AudioDeliveryMode = "live"
	AudioDeliveryBuffered AudioDeliveryMode = "buffered"
)

type AudioInput

type AudioInput struct {
	Data    []byte
	Release func()
}

AudioInput transfers ownership of Data to the session after SubmitAudio returns nil. Release is called once when the provider consumes or the runtime discards the input. When SubmitAudio returns an error, the caller retains ownership and Release is not invoked.

type BatchSegment

type BatchSegment struct {
	Text    string
	StartMS int64
	EndMS   int64
	Speaker string
}

BatchSegment is one time-aligned span of the transcript. Speaker is the vendor's own label carried verbatim (a number, "A", "speaker_1"), empty when the provider did not diarize.

type BatchTranscribeRequest

type BatchTranscribeRequest struct {
	Plan    protocol.SessionPlan
	Options protocol.RequestOptions
	// Media is the PCM format inside the WAV container.
	Media protocol.MediaFormat
	// Audio is the complete WAV container (RIFF header + PCM data). Adapters
	// receive a container rather than raw PCM because almost no batch endpoint
	// accepts headerless audio, and the ones that do also accept WAV. Adapters
	// that need a second pass over the bytes (an upload step before a submit
	// step, a retry) Seek to the start rather than buffering the file.
	Audio io.ReadSeeker
	// AudioBytes is the container's total length, for Content-Length and for
	// refusing an upload the provider documents as too large before sending
	// any of it.
	AudioBytes int64
	// SourceURL is an HTTPS URL the provider may fetch the same audio from.
	// Set only by callers that can host the audio for providers whose batch
	// API takes URL input exclusively; adapters that upload bytes ignore it.
	SourceURL string
}

BatchTranscribeRequest is the already-validated execution choice plus the audio. Plan.Route names the BATCH endpoint and model — not the realtime pair for the same product — and Route.Credential authenticates exactly as it does for Adapter.

type BatchTranscriber

type BatchTranscriber interface {
	ID() string
	Transcribe(context.Context, BatchTranscribeRequest) (*BatchTranscription, error)
}

BatchTranscriber is the provider-specific implementation point for transcribing one complete PRERECORDED utterance through a provider's non-realtime API — the endpoints vendors document as "pre-recorded", "async", "file" or "batch" transcription.

It exists because Adapter cannot express that shape. ProviderStream is a realtime contract (write audio, commit, drain events) and every realtime socket has an ingest rate it can actually sustain; pushing a 30-minute upload down one at wire speed silently yields the first 37 seconds and a clean close. A batch endpoint takes the whole file, returns a whole transcript, and reports the duration it processed — which is also the only honest billing basis for prerecorded audio.

One call is one provider request (or one submit-poll-fetch sequence). Chunking oversized audio is the caller's job, informed by the limits the caller's catalog publishes; adapters refuse rather than split.

type BatchTranscription

type BatchTranscription struct {
	// Billing preserves provider quantities separately from audio authorization.
	Billing  *protocol.BillingReport
	Text     string
	Segments []BatchSegment
	// Words are the provider's per-word timings, populated only when the
	// request asked for them (SttOptions.WordTimestamps) and the provider
	// returned them. Segments stay the coarser unit; Words never replace it.
	Words []BatchWord
	// Translation is the transcript translated into the requested
	// SttOptions.Translation target; empty when none was asked for. Text
	// stays the original words.
	Translation string
	// Language is the BCP-47 tag the provider reported using or detecting;
	// empty when it reported none.
	Language string
	// DurationMS is the audio duration the PROVIDER reported processing —
	// the quantity it bills — or zero when the response carries none. Callers
	// meter from this rather than from bytes sent when it is present.
	DurationMS int64
	// ProviderRequestID is the provider's request or job identifier: evidence
	// for settlement disputes, never customer-visible output.
	ProviderRequestID string
	// Extensions may retain the raw vendor payload for diagnostics. Callers
	// never forward it to customers or telemetry.
	Extensions map[string]json.RawMessage
}

BatchTranscription is the normalized result. Text is the whole transcript in reading order; Segments are the provider's time-aligned spans (words grouped into utterances where the vendor gives no coarser unit) and may be empty when a provider returns untimed text.

func (*BatchTranscription) LastTimedMS

func (t *BatchTranscription) LastTimedMS() int64

LastTimedMS returns the end of the latest timed span, or zero when the result carries no timing. Callers compare it against the audio they sent to detect a provider that returned a prefix of the transcript as if it were the whole.

type BatchWord

type BatchWord struct {
	Text    string
	StartMS int64
	EndMS   int64
	Speaker string
}

BatchWord is one word of the transcript with its own timing. Speaker is the vendor's own label carried verbatim, empty when the provider did not diarize.

type ClockedPlanVerifier added in v0.3.1

type ClockedPlanVerifier interface {
	PlanVerifier
	VerifyWithClock(context.Context, protocol.SessionPlan, func(context.Context) (time.Time, error)) error
}

ClockedPlanVerifier authenticates the exact JWS, issuer and audience before invoking clock and fences the nonce with monotonic retention. It then validates all time bounds against SQL time. Renewable funded roots require this capability.

type ClockedReplayCache added in v0.3.1

type ClockedReplayCache interface {
	ReplayCache
	TryUseFor(context.Context, string, time.Duration) (bool, error)
}

ClockedReplayCache retains authenticated nonces for a monotonic TTL, independently of host wall-clock changes. TTL alone cannot protect against SQL rollback after eviction; funded admission requires FundedReplayCache.

type Config

type Config struct {
	// MaxReplayEntries bounds retained attempts. Zero uses DefaultMaxReplayEntries.
	MaxReplayEntries int
	Adapters         []Adapter
	Verifier         PlanVerifier
	// LocalCredentials maps a signed provider name to a customer-owned BYOK
	// credential. The engine copies a matching credential only into the
	// ephemeral adapter request; the verified plan and session retain no secret.
	LocalCredentials map[string]LocalCredential
	Telemetry        TelemetrySink
	Limits           Limits
	Now              func() time.Time
}

Config configures an embedded Engine. Verifier is required because a runtime must not trust a customer-provided plan merely because it is well formed.

type CredentialRefresher

type CredentialRefresher func(context.Context) (protocol.DelegatedCredential, error)

CredentialRefresher obtains a fresh delegated credential for the SAME plan attempt: same route, same reservation, no new attempt. It exists for providers whose managed credential is single-use per connection, so an adapter that must redial mid-session (ElevenLabs dialogue after a Cancel) can authenticate the new socket.

type Engine

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

Engine opens provider-neutral sessions through registered provider adapters.

func New

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

New constructs an Engine with fixed per-session limits.

func (*Engine) Open

func (e *Engine) Open(ctx context.Context, request OpenRequest) (session *Session, err error)

Open verifies a concrete session plan, opens its selected adapter, and emits session.ready only after the upstream stream is ready to accept work.

type EntitlementClient added in v0.3.1

EntitlementClient is implemented by the hosted control-plane client.

type FundedReplayCache added in v0.3.1

type FundedReplayCache interface {
	ClockedReplayCache
	TryUseFunded(context.Context, string, time.Time, time.Duration) (bool, error)
}

FundedReplayCache atomically retains a signed expiry cutoff when elapsed guards are retired. A SQL rollback cannot revive a forgotten nonce. Shared implementations must persist the cutoff with eviction, not only SETNX/TTL.

type GoogleRealtimeAdapter added in v0.3.1

type GoogleRealtimeAdapter interface {
	Adapter
	GoogleRealtimeAdapter() bool
}

GoogleRealtimeAdapter identifies an installed Google realtime implementation for any installed ID. Wrappers return their underlying implementation's capability, and return false when it is absent or refused. This capability promises physical cap retention; it does not enable managed resumption.

type InterruptingProviderStream added in v0.3.1

type InterruptingProviderStream interface {
	Interrupt()
}

InterruptingProviderStream stops physical I/O promptly without joining a reader, waiting for an event consumer, or acquiring the runtime provider mutex. Interrupt must be safe concurrently with every provider operation. Serialized Abort/Close and event-channel closure still provide teardown evidence; Interrupt alone never releases tracked capacity.

type JWKSPlanVerifier

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

JWKSPlanVerifier verifies compact JWS session-plan envelopes using cached control-plane public keys. An unknown key ID forces one synchronous refresh so normal signing-key rotation does not wait for the cache TTL to expire.

func NewPlanVerifier

func NewPlanVerifier(config PlanVerifierConfig) (*JWKSPlanVerifier, error)

NewPlanVerifier creates the production PlanVerifier implementation used by an embedded runtime or gateway.

func (*JWKSPlanVerifier) Verify

Verify validates the outer plan, verifies its JWS, binds the envelope to that exact plan, validates issuer/audience/times, and consumes its jti.

func (*JWKSPlanVerifier) VerifyWithClock added in v0.3.1

func (v *JWKSPlanVerifier) VerifyWithClock(ctx context.Context, plan protocol.SessionPlan, clock func(context.Context) (time.Time, error)) error

VerifyWithClock never sends a plan token to a clock endpoint before its signature, exact payload, issuer and audience have been authenticated.

type Limits

type Limits struct {
	MaxInputMessages int
	MaxInputBytes    int
	MaxOutputEvents  int
}

Limits bounds all session-owned buffering. Values are per active session.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits are intentionally small enough that a misbehaving local caller cannot consume unbounded memory, while allowing normal audio frames.

type LocalCredential

type LocalCredential struct {
	Kind protocol.CredentialKind
	// Exactly one of Value and ValueFile is configured. ValueFile is reread for
	// every session so an external OAuth refresher can rotate short-lived tokens
	// without restarting the Gateway.
	Value     string
	ValueFile string
}

LocalCredential is a customer-owned provider credential installed in the local runtime. It is deliberately separate from SessionPlan: BYOK secrets are never sent to, signed by, or logged by the control plane.

type MemoryReplayCache

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

MemoryReplayCache is a bounded-by-expiry in-process replay cache.

func NewMemoryReplayCache

func NewMemoryReplayCache(now func() time.Time) *MemoryReplayCache

NewMemoryReplayCache constructs an in-memory replay cache.

func (*MemoryReplayCache) TryUse

func (c *MemoryReplayCache) TryUse(_ context.Context, id string, expiresAt time.Time) (bool, error)

TryUse atomically consumes ID until its expiry. It returns false when the ID was previously consumed and has not yet expired.

func (*MemoryReplayCache) TryUseFor added in v0.3.1

func (c *MemoryReplayCache) TryUseFor(_ context.Context, id string, ttl time.Duration) (bool, error)

TryUseFor retains a nonce for its full authenticated issuance lifetime. Both legacy and clocked lookups respect the monotonic retention deadline.

func (*MemoryReplayCache) TryUseFunded added in v0.3.1

func (c *MemoryReplayCache) TryUseFunded(_ context.Context, id string, expiresAt time.Time, ttl time.Duration) (bool, error)

TryUseFunded refuses retired signed horizons without changing the SQL sample used for validation. A newer signed horizon can still use reclaimed space.

type NopTelemetry

type NopTelemetry struct{}

NopTelemetry discards all telemetry and is safe for tests and local use.

func (NopTelemetry) TryRecord

func (NopTelemetry) TryRecord(TelemetryEvent) bool

type OpenRequest

type OpenRequest struct {
	// Called synchronously after verification and before provider I/O. Metrics
	// consumers receive only the nonsecret, signed accounting projection.
	OnVerifiedCapacity func(*protocol.CapacityAttribution, protocol.CredentialSource)
	// TrackVerifiedCapacity acquires local physical capacity after verification,
	// before provider I/O. Its release runs only after provider teardown returns
	// and its event channel closes, independently of public session termination.
	TrackVerifiedCapacity func(*protocol.CapacityAttribution, protocol.CredentialSource) (release func(), err error)
	Kind                  protocol.SessionKind
	Plan                  protocol.SessionPlan
	Options               protocol.RequestOptions
	Media                 *protocol.MediaFormat
	Delivery              AudioDeliveryMode
	// RefreshCredential is passed through to AdapterRequest unchanged.
	RefreshCredential CredentialRefresher
	// Entitlements enables SQL-clock lease checks and bounded continuation when
	// the adapter permits it. Managed Google resumption currently stays refused.
	// No caller-supplied replacement plan or allowance is accepted.
	Entitlements EntitlementClient
}

OpenRequest supplies the operation-specific information omitted from a signed SessionPlan because the plan is also used by local and remote APIs.

type PassthroughReplayCache

type PassthroughReplayCache struct{}

PassthroughReplayCache accepts every envelope ID without recording it. It exists for callers that own replay protection themselves: a relay connector verifies the plan's signature first, runs its routing self-checks, and only then consumes the JTI against its shared Redis cache. Wiring a real cache into Verify would burn the JTI before the self-checks run, turning a misrouted-but-valid plan into a permanently unusable one. Never use this cache anywhere the Verify call itself is the last line of replay defense.

func (PassthroughReplayCache) TryUse

func (PassthroughReplayCache) TryUse(_ context.Context, id string, expiresAt time.Time) (bool, error)

TryUse accepts any well-formed ID and remembers nothing.

type PlanVerifier

type PlanVerifier interface {
	Verify(context.Context, protocol.SessionPlan) error
}

PlanVerifier verifies a SessionPlan signature against its trusted issuer. Managed routing uses control-plane keys; local routing uses a process-local signer. An engine refuses to open sessions without a verifier.

type PlanVerifierConfig

type PlanVerifierConfig struct {
	// MaxReplayEntries bounds the default cache; custom ReplayCache owns its bound.
	MaxReplayEntries int
	JWKSURL          string
	Issuer           string
	Audience         string
	HTTPClient       *http.Client
	CacheTTL         time.Duration
	MaxCacheTTL      time.Duration
	ClockSkew        time.Duration
	// Now supplies plan admission time, not elapsed JWKS cache time.
	Now               func() time.Time
	ReplayCache       ReplayCache
	AllowInsecureJWKS bool
}

PlanVerifierConfig identifies the control-plane signing authority and local verification policy. JWKSURL must be HTTPS in production; the explicit AllowInsecureJWKS option exists only for hermetic HTTP test fixtures.

type PlanVerifierFunc

type PlanVerifierFunc func(context.Context, protocol.SessionPlan) error

PlanVerifierFunc adapts a function into a PlanVerifier.

func (PlanVerifierFunc) Verify

type ProviderControlStream

type ProviderControlStream interface {
	SendProviderControl(context.Context, protocol.ProviderControl) error
}

ProviderControlStream is an optional capability of speech-to-speech streams: forwarding one bounded, protocol-allowlisted native provider command (protocol.ProviderControl) upstream. Streams without it refuse controls with ErrUnsupportedOperation.

type ProviderError

type ProviderError struct {
	Code    string
	Message string
	// Hint is optional inside the gateway. When set it must be a fixed,
	// caller-safe remediation string; raw provider messages belong only in
	// Extensions. The relay edge supplies a code-based fallback when absent.
	Hint           string
	Retryable      bool
	ProviderStatus int
	Cause          error
	// Extensions may retain a provider's raw error payload for the local
	// canonical error event. Telemetry never copies this field; it reads the
	// provider's error code out of it through SafeProviderCode only.
	Extensions map[string]json.RawMessage
	// ProviderCode is optional: the provider's own machine-readable error
	// code, set by an adapter whose vendor names it where SafeProviderCode's
	// generic reading of Extensions would not look (a frame's type, a header
	// object, a mapped numeric code). Leave it empty otherwise.
	ProviderCode string
}

ProviderError preserves the stable protocol classification when an adapter cannot continue an upstream stream. It must not contain credentials or raw request URLs.

func (*ProviderError) Error

func (e *ProviderError) Error() string

func (*ProviderError) SafeHint

func (e *ProviderError) SafeHint() string

SafeHint exposes only the adapter-authored, caller-safe remediation. Relay versions that predate the concrete Hint field can discover it through this interface without coupling their provider-error classifier to a particular gateway release.

func (*ProviderError) SafeProviderCode added in v0.3.1

func (e *ProviderError) SafeProviderCode() string

SafeProviderCode is the provider's own machine-readable error code (voice_not_found, insufficient_quota, RESOURCE_EXHAUSTED, ...), so an operator can see why a provider failed beyond the closed Code. It is, in order: the adapter's ProviderCode; the code the raw error payload in Extensions names (see providerCodeFromPayload); or the reason of a WebSocket close frame in Cause. Every answer passes SanitizeProviderCode, so it is one token, never a message or a payload. "" means the provider named no code.

func (*ProviderError) Unwrap

func (e *ProviderError) Unwrap() error

type ProviderEvent

type ProviderEvent struct {
	// Billing is trusted normalized usage, independent of public event forwarding.
	Billing *protocol.BillingObservation `json:"-"`

	Type       protocol.EventType
	Data       json.RawMessage
	Extensions map[string]json.RawMessage
	Audio      []byte
	Err        error
}

ProviderEvent is a provider adapter's normalized output. The adapter grants ownership of Data, Extensions, and Audio to the runtime when sending the event; it must not mutate any of them after delivery. Err terminates the attempt and is never emitted as a normal event.

type ProviderStream

type ProviderStream interface {
	Events() <-chan ProviderEvent
	WriteAudio(context.Context, []byte) error
	CommitAudio(context.Context) error
	AppendText(context.Context, string) error
	CommitText(context.Context) error
	Cancel(context.Context) error
	Close(context.Context) error
}

ProviderStream is serialized by the runtime: WriteAudio, control methods, and Close never run concurrently for one session. Events may arrive concurrently from the provider implementation.

type RelayPlanVerifier

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

RelayPlanVerifier verifies compact JWS relay-plan envelopes using cached control-plane public keys. It shares the JWKS cache, key-rotation, and clock-skew machinery of JWKSPlanVerifier unchanged; only the envelope type, the expected JWS typ, and the byte-exact plan binding differ. A relay plan signed for the session-plan typ (or vice versa) is rejected before any key lookup semantics matter, so the two verifiers never accept each other's artifacts even when pointed at the same JWKS.

A relay connector is the sole JTI consumer for a relay plan, and it must only consume the JTI once it knows the plan was routed to the right place. Connectors therefore construct this verifier with PassthroughReplayCache, run their region/provider/model/endpoint self-checks after Verify returns, and only then consume the envelope ID against their shared replay cache. A valid plan misrouted to the wrong connector fails the self-check with its JTI intact, so redelivery to the correct connector still succeeds exactly once.

func NewRelayPlanVerifier

func NewRelayPlanVerifier(config PlanVerifierConfig) (*RelayPlanVerifier, error)

NewRelayPlanVerifier creates the production relay-plan verifier used by relay edges and connectors. The config carries the relay issuer, the dedicated relay JWKS URL, and the relay audience (protocol.RelayPlanAudience for production deployments).

func (*RelayPlanVerifier) Verify

Verify validates the outer relay plan, verifies its JWS against the relay typ, binds the envelope to that exact plan, validates issuer/audience/times, and offers its jti to the configured ReplayCache. With PassthroughReplayCache the final step always accepts and the caller owns replay protection; see the type comment for the connector contract.

type ReplayCache

type ReplayCache interface {
	TryUse(context.Context, string, time.Time) (bool, error)
}

ReplayCache records verified envelope IDs until expiry. Production users that run several gateways should supply a shared, atomic implementation; MemoryReplayCache is safe within one runtime process and is the default.

type ResumableProviderStream added in v0.3.1

type ResumableProviderStream interface {
	ProviderStream
	CanResume() bool
	Detach()
	// TightenPhysicalDeadline is concurrent and nonblocking. It may only
	// shorten this socket's Engine-derived cap, never extend or renew it.
	TightenPhysicalDeadline(time.Time)
	Resume(context.Context, protocol.DelegatedCredential) error
}

ResumableProviderStream keeps one event source across funded socket changes. Detach must promptly stop the current socket, independently of an in-flight HTTP renewal or Resume. Resume must wait for provider setup acknowledgment.

type Session

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

Session is an active, single-provider attempt. Its methods are safe to call from multiple goroutines; provider calls remain serialized by runInput.

func (*Session) Abort

func (s *Session) Abort()

Abort claims terminal failure and interrupts physical I/O immediately when supported, then joins provider teardown asynchronously. Use it when a local transport has failed and graceful draining has no viable consumer.

func (*Session) AppendText

func (s *Session) AppendText(text string) error

AppendText queues TTS or LLM input after prior session input.

func (*Session) Cancel

func (s *Session) Cancel() error

Cancel requests best-effort cancellation after all earlier queued input.

func (*Session) Close

func (s *Session) Close()

Close begins a graceful close. Queued input is sent in order and the stream then receives Close. It never waits for provider or telemetry I/O.

func (*Session) CommitAudio

func (s *Session) CommitAudio() error

CommitAudio marks an STT boundary after all earlier audio frames.

func (*Session) CommitText

func (s *Session) CommitText() error

CommitText marks a TTS or LLM utterance boundary.

func (*Session) Done

func (s *Session) Done() <-chan struct{}

Done closes when the session becomes terminal. Events may still contain the already-enqueued terminal event and should be drained independently.

func (*Session) Err

func (s *Session) Err() error

Err returns the terminal error, if the session ended abnormally.

func (*Session) Events

func (s *Session) Events() <-chan protocol.Event

Events contains canonical events in provider order. It closes after a terminal event. The session owns event Audio buffers until delivery.

func (*Session) SendProviderControl

func (s *Session) SendProviderControl(control protocol.ProviderControl) error

SendProviderControl queues one native provider command for a realtime session. The envelope is validated against the route's speech protocol before it is queued, so a Realtime-only control on a Live session — or an unknown command on either — is refused synchronously with ErrUnsupportedOperation rather than reaching the provider.

func (*Session) Stats

func (s *Session) Stats() Stats

Stats returns a point-in-time view of bounded queue usage.

func (*Session) SubmitAudio

func (s *Session) SubmitAudio(input AudioInput) error

SubmitAudio enqueues an audio frame without copying it.

func (*Session) Wait

func (s *Session) Wait(ctx context.Context) error

Wait blocks until the session is terminal or ctx expires.

type Stats

type Stats struct {
	InputMessages    int
	InputBytes       int
	TelemetryDropped uint64
	EventSequence    uint64
}

Stats is a snapshot of bounded-buffer and terminal-session state.

type TelemetryEvent

type TelemetryEvent struct {
	Name        string
	SessionID   string
	AttemptID   string
	At          time.Time
	EventID     string
	Destination protocol.Telemetry
	Data        json.RawMessage
	// Required marks the minimal terminal/usage events needed to meter a
	// managed route. Optional telemetry controls never suppress these events.
	Required bool
}

TelemetryEvent captures local experience metadata only. It intentionally contains no media, transcripts, or provider credentials.

EventID identifies one event occurrence and stays stable across delivery retries, so an at-least-once exporter can be deduplicated by the receiver. The Engine assigns IDs at creation; the exporter assigns a missing ID once before enqueueing. Destination is empty for anonymous local routing or carries the plan-scoped contract for an authenticated attempt; Destination.Token is a credential and must never be logged or persisted by a sink. Data carries a redacted, provider-neutral payload for events that have one (for example usage.observed's provider request ID).

type TelemetryExporter

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

TelemetryExporter is the production TelemetrySink: TryRecord never performs I/O, events batch per plan-carried or anonymous default destination, and delivery retries within bounded attempts and memory. Stable event IDs make at-least-once delivery safe against idempotent ingest; a full queue or exhausted retry drops events and counts them rather than blocking a session.

func NewTelemetryExporter

func NewTelemetryExporter(config TelemetryExporterConfig) (*TelemetryExporter, error)

NewTelemetryExporter starts the exporter's background batching and delivery goroutines. Callers own its lifetime and must call Close during shutdown to flush buffered events.

func (*TelemetryExporter) Close

func (e *TelemetryExporter) Close(ctx context.Context) error

Close stops intake, flushes buffered events, and waits for delivery to finish or ctx to expire. In-flight requests still respect their own bounded timeout after ctx expires.

func (*TelemetryExporter) Stats

Stats returns a point-in-time snapshot of the drop, retry, and delivery counters.

func (*TelemetryExporter) TryRecord

func (e *TelemetryExporter) TryRecord(event TelemetryEvent) bool

TryRecord enqueues one event without blocking. It returns false when the exporter is shut down or its bounded queue is full.

type TelemetryExporterConfig

type TelemetryExporterConfig struct {
	HTTPClient               *http.Client
	QueueSize                int
	MaxBatchEvents           int
	MaxAttempts              int
	RetryBackoff             time.Duration
	RequestTimeout           time.Duration
	UserAgent                string
	Now                      func() time.Time
	AnonymousEndpoint        string
	DisableOptionalTelemetry bool
}

TelemetryExporterConfig bounds every exporter resource explicitly. All fields are optional; zero values receive conservative defaults.

type TelemetryExporterStats

type TelemetryExporterStats struct {
	Enqueued      uint64
	Exported      uint64
	Dropped       uint64
	Retried       uint64
	FailedBatches uint64
	Suppressed    uint64
}

TelemetryExporterStats are monotonic process counters. They deliberately carry no session, tenant, or credential detail.

type TelemetrySink

type TelemetrySink interface {
	TryRecord(TelemetryEvent) bool
}

TelemetrySink must return without waiting for network or disk I/O. Returning false reports a dropped event; it never affects session delivery.

type TerminalErrorProviderStream

type TerminalErrorProviderStream interface {
	TerminalError() error
}

TerminalErrorProviderStream preserves a terminal failure independently of the bounded event queue. Runtimes check it when Events closes so downstream backpressure cannot turn a dropped terminal event into clean completion.

Jump to

Keyboard shortcuts

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