aibridged

package
v2.38.7 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: AGPL-3.0 Imports: 42 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

Index

Constants

View Source
const (
	InternalMCPServerID = "coder"
)

Variables

View Source
var (
	ErrNoAuthKey             = xerrors.New("no authentication key provided")
	ErrConnect               = xerrors.New("could not connect to coderd")
	ErrUnauthorized          = xerrors.New("unauthorized")
	ErrAcquireRequestHandler = xerrors.New("failed to acquire request handler")
	ErrBudgetCheck           = xerrors.New("internal server error checking user AI budget")
)
View Source
var (
	ErrEmptyConfig  = xerrors.New("empty config given")
	ErrCompileRegex = xerrors.New("compile tool regex")
)
View Source
var DefaultPoolOptions = PoolOptions{MaxItems: 5000, TTL: time.Minute * 15}
View Source
var (
	ErrShutdown = xerrors.New("aibridged server shutdown")
)

Functions

func BaseURLHostname added in v2.37.0

func BaseURLHostname(baseURL string) string

BaseURLHostname returns the normalized hostname from a provider base URL. It is the canonical normalization used by the proxy classifier and the API status check. Scheme-less inputs (from env-config seeding) get https:// prepended.

func NewTransportFactory

func NewTransportFactory(handler http.Handler) aibridge.TransportFactory

NewTransportFactory returns an [aibridge.TransportFactory] whose RoundTripper dispatches requests to handler in-process, streaming the response body through an io.Pipe so SSE/NDJSON/chunked responses propagate token-by-token just as they would over the wire.

handler is typically the aibridged HTTP entrypoint registered via [API.RegisterInMemoryAIBridgedHTTPHandler].

func SubscribeProviderReload

func SubscribeProviderReload(
	ctx context.Context,
	ps dbpubsub.Pubsub,
	reloader ProviderReloader,
	logger slog.Logger,
) (func(), error)

SubscribeProviderReload subscribes to AI provider change events, reloading the reloader's snapshot on each event, and performs one initial reload before returning. Subscribing happens before the initial reload so no change event is missed.

A subscription failure returns an error without reloading. The initial reload is best-effort: a reload failure is logged and not returned. A dropped-message delivery error triggers a reload too, matching WatchAIProviders: a drop may have masked a change, so the snapshot must reconverge.

func WatchProviderReload added in v2.36.0

func WatchProviderReload(
	ctx context.Context,
	clientFn ClientFunc,
	reloader ProviderReloader,
	logger slog.Logger,
) error

WatchProviderReload opens a coderd WatchAIProviders stream via clientFn and calls reloader.Reload on each change signal the server emits. The stream is re-established with exponential backoff whenever it drops. It does not perform an initial load; the caller is responsible for any blocking load before serving.

It runs until ctx is canceled, then returns ctx.Err(). clientFn receives ctx, so a client acquisition that blocks (e.g. Server.Client waiting for the daemon to connect to coderd) unblocks when ctx is canceled, leaving no goroutine behind.

func WriteProviderInfoSnapshot

func WriteProviderInfoSnapshot(info *prometheus.GaugeVec, outcomes []ProviderOutcome)

WriteProviderInfoSnapshot Resets info and writes one series per outcome. Both aibridged and aibridgeproxyd use this so the provider_info recording contract stays in one place.

Types

type CachedBridgePool

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

func NewCachedBridgePool

func NewCachedBridgePool(options PoolOptions, providers []aibridge.Provider, logger slog.Logger, metrics *aibridge.Metrics, tracer trace.Tracer) (*CachedBridgePool, error)

func (*CachedBridgePool) Acquire

func (p *CachedBridgePool) Acquire(ctx context.Context, req Request, clientFn ClientFunc, mcpProxyFactory MCPProxyBuilder) (_ http.Handler, outErr error)

Acquire retrieves or creates a [*aibridge.RequestBridge] instance per given key.

Each returned [*aibridge.RequestBridge] is safe for concurrent use. Each [*aibridge.RequestBridge] is stateful because it has MCP clients which maintain sessions to the configured MCP server.

func (*CachedBridgePool) CacheMetrics

func (p *CachedBridgePool) CacheMetrics() PoolMetrics

func (*CachedBridgePool) KeyPools added in v2.35.0

func (p *CachedBridgePool) KeyPools() []*keypool.Pool

KeyPools returns the non-nil key pools of the current providers.

func (*CachedBridgePool) Options

func (p *CachedBridgePool) Options() PoolOptions

Options reports the options the pool was built with.

func (*CachedBridgePool) ReplaceProviders

func (p *CachedBridgePool) ReplaceProviders(providers []aibridge.Provider)

ReplaceProviders swaps the provider snapshot used by future Acquires. It is safe to call concurrently with Acquire and is a no-op after Shutdown.

func (*CachedBridgePool) Shutdown

func (p *CachedBridgePool) Shutdown(_ context.Context) error

Shutdown will close the cache which will trigger eviction of all the Bridge entries.

type ClientFunc

type ClientFunc func(context.Context) (DRPCClient, error)

ClientFunc acquires a DRPCClient, honoring the passed context so a blocking acquisition (e.g. waiting for the daemon to connect to coderd) unblocks when the context is canceled. Server.Client satisfies it.

type DRPCClient

DRPCClient is the union of various service interfaces the client must support.

type Dialer

type Dialer func(ctx context.Context) (DRPCClient, error)

func NewWebsocketDialer added in v2.36.0

func NewWebsocketDialer(serverURL *url.URL, transport http.RoundTripper, key string) Dialer

type MCPProxyBuilder deprecated

type MCPProxyBuilder interface {
	// Build creates a [mcp.ServerProxier] for the given request initiator.
	// At minimum, the Coder MCP server will be proxied.
	// The SessionKey from [Request] is used to authenticate against the Coder MCP server.
	//
	// NOTE: the [mcp.ServerProxier] instance may be proxying one or more MCP servers.
	Build(ctx context.Context, req Request, tracer trace.Tracer) (mcp.ServerProxier, error)
}

Deprecated: Injected MCP in AI Bridge is deprecated and will be removed in a future release.

type MCPProxyFactory deprecated

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

Deprecated: Injected MCP in AI Bridge is deprecated and will be removed in a future release.

func NewMCPProxyFactory

func NewMCPProxyFactory(logger slog.Logger, tracer trace.Tracer, clientFn ClientFunc) *MCPProxyFactory

func (*MCPProxyFactory) Build

func (m *MCPProxyFactory) Build(ctx context.Context, req Request, tracer trace.Tracer) (mcp.ServerProxier, error)

type Metrics

type Metrics struct {

	// ProviderInfo is one series per configured provider; value is
	// always 1 and the status label carries the alertable signal.
	// Labels: provider_name, provider_type, status.
	ProviderInfo *prometheus.GaugeVec

	// ProvidersLastReloadTimestampSeconds is the unix timestamp of the
	// last reload attempt, success or failure.
	ProvidersLastReloadTimestampSeconds prometheus.Gauge

	// ProvidersLastReloadSuccessTimestampSeconds is the unix timestamp
	// of the last reload that successfully refreshed the providers. A gap
	// against ProvidersLastReloadTimestampSeconds means the loop is
	// firing but the refresh function is failing.
	ProvidersLastReloadSuccessTimestampSeconds prometheus.Gauge
	// contains filtered or unexported fields
}

Metrics is the prometheus surface for aibridged provider reloads.

func NewMetrics

func NewMetrics(reg prometheus.Registerer) *Metrics

NewMetrics registers the provider metrics against reg.

func (*Metrics) RecordReloadAttempt

func (m *Metrics) RecordReloadAttempt()

RecordReloadAttempt stamps the attempt-time gauge at the start of a reload. A reload that hangs mid-flight is detected by watching the gap between this gauge and ProvidersLastReloadSuccessTimestampSeconds.

func (*Metrics) RecordReloadSuccess

func (m *Metrics) RecordReloadSuccess(outcomes []ProviderOutcome)

RecordReloadSuccess rewrites the ProviderInfo GaugeVec from the outcomes and stamps the success-time gauge. Reset clears series for providers that have left the configuration so they don't linger as stale.

func (*Metrics) Unregister

func (m *Metrics) Unregister()

Unregister removes the provider metrics from the registerer.

type PoolMetrics

type PoolMetrics interface {
	Hits() uint64
	Misses() uint64
	KeysAdded() uint64
	KeysEvicted() uint64
}

type PoolOptions

type PoolOptions struct {
	MaxItems int64
	TTL      time.Duration
	Clock    quartz.Clock

	// StructuredLogging makes each bridge emit AI Gateway interception
	// records in the format described by [recorder.InterceptionLogMarker].
	StructuredLogging bool
	// DisableContentRecording stops prompts, tool call arguments and model
	// thoughts from being recorded. Interceptions and token usage are still
	// recorded, so AI spend accounting and budget enforcement are unaffected.
	DisableContentRecording bool
}

func PoolOptionsFromConfig

func PoolOptionsFromConfig(ctx context.Context, logger slog.Logger, cfg codersdk.AIBridgeConfig) PoolOptions

PoolOptionsFromConfig returns DefaultPoolOptions with the record policy the deployment configured. Every construction site uses it, so the in-process daemon, the standalone gateway and the test harness cannot drift.

It also reports a deployment that drops content records without exporting them anywhere: they never reach coderd, so if coderd is the only emitter the deployment has silently stopped exporting the very records it is declining to store. Nothing else reports this.

type Pooler

type Pooler interface {
	KeyPools() []*keypool.Pool
	Acquire(ctx context.Context, req Request, clientFn ClientFunc, mcpBootstrapper MCPProxyBuilder) (http.Handler, error)
	// ReplaceProviders swaps the providers used to construct future
	// RequestBridge instances and clears the cache. Disabled providers
	// must be included; the bridge serves a 503 sentinel on their
	// routes.
	ReplaceProviders(providers []aibridge.Provider)
	Shutdown(ctx context.Context) error
}

Pooler describes a pool of [*aibridge.RequestBridge] instances from which instances can be retrieved. One [*aibridge.RequestBridge] instance is created per given key.

type ProviderOutcome

type ProviderOutcome struct {
	Name   string
	Type   string
	Status ProviderStatus
	Err    error
}

ProviderOutcome classifies one ai_providers row, including disabled rows (503 sentinel), errored rows (excluded from pool), and proxy-excluded rows (excluded from proxy routing). Err is set when Status is Error or ProxyExcluded; the build error is already logged at the call site.

type ProviderReloader

type ProviderReloader interface {
	Reload(ctx context.Context) error
}

ProviderReloader refreshes a component's provider snapshot.

type ProviderStatus

type ProviderStatus string

ProviderStatus is the lifecycle state of a configured AI provider.

const (
	// ProviderStatusEnabled indicates the provider is configured and
	// valid, and is included in the active pool snapshot.
	ProviderStatusEnabled ProviderStatus = "enabled"
	// ProviderStatusDisabled indicates the provider is configured but
	// intentionally turned off by an operator.
	ProviderStatusDisabled ProviderStatus = "disabled"
	// ProviderStatusError indicates the provider is configured but
	// cannot be constructed (missing keys, unsupported type, malformed
	// settings).
	ProviderStatusError ProviderStatus = "error"
	// ProviderStatusProxyExcluded means another enabled provider
	// already claimed its hostname. The provider is still routable via
	// the direct path (/api/v2/ai-gateway/{name}/...).
	ProviderStatusProxyExcluded ProviderStatus = "proxy_excluded"
)

type Request

type Request struct {
	SessionKey  string
	APIKeyID    string
	InitiatorID uuid.UUID
}

type Server

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

Server manages the AI Gateway's connection to coderd and request handlers for embedded and standalone deployments. It selects interception or proxy mode at startup, applies provider snapshots, and coordinates shutdown.

func New

func New(ctx context.Context, rpcDialer Dialer, logger slog.Logger, tracer trace.Tracer, experiments codersdk.Experiments, metrics *aibridge.Metrics, opts ...ServerOption) (*Server, error)

New starts a gateway server. Creates a request pool only when interception mode is selected. Mode is fixed at startup and requires a restart to change.

func (*Server) Client

func (s *Server) Client(ctx context.Context) (DRPCClient, error)

Client acquires a DRPCClient, blocking until the daemon is connected to coderd, the server lifecycle ends, or ctx is canceled.

func (*Server) Close

func (s *Server) Close() error

Close shuts down the server with a timeout of 5s.

func (*Server) Done added in v2.36.0

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

Done returns a channel that is closed when the server lifecycle ends. It closes on explicit shutdown and on fatal connection-loop exit.

func (*Server) Err added in v2.36.0

func (s *Server) Err() error

Err returns the reason the server lifecycle ended.

func (*Server) GetRequestHandler

func (s *Server) GetRequestHandler(ctx context.Context, req Request) (http.Handler, error)

GetRequestHandler retrieves the selected gateway handler for the request.

func (*Server) KeyPoolStateCollector

func (s *Server) KeyPoolStateCollector() prometheus.Collector

KeyPoolStateCollector reports key states from the current provider snapshot.

func (*Server) PoolOptions

func (s *Server) PoolOptions() PoolOptions

PoolOptions reports the options the published interception pool was built with, so a caller can assert that its configuration reached the pool serving requests. It reports the zero value in proxy mode, which has no pool.

func (*Server) Ready added in v2.36.0

func (s *Server) Ready() bool

Ready reports whether the server currently has an active DRPC connection to coderd.

func (*Server) ReplaceProviders

func (s *Server) ReplaceProviders(ctx context.Context, providers []aibridge.Provider) error

ReplaceProviders publishes a provider snapshot to the selected backend. Proxy requests retain their router across reloads, and a failed construction keeps the previous router serving. Returns an error if mode selection has not completed.

A replaced router is not drained: in-flight requests hold it by reference and finish on the snapshot they started with. Shutdown drains them through the server's in-flight tracking, whichever snapshot they run on.

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(rw http.ResponseWriter, r *http.Request)

ServeHTTP is the entrypoint for requests which will be intercepted by AI Bridge. This function will validate that the given API key may be used to perform the request.

An [aibridge.RequestBridge] instance is acquired from a pool based on the API key's owner (referred to as the "initiator"); this instance is responsible for the AI Bridge-specific handling of the request.

A DRPCClient is provided to the [aibridge.RequestBridge] instance so that data can be passed up to a DRPCServer for persistence.

func (*Server) SetPoolForTest

func (s *Server) SetPoolForTest(ctx context.Context, t testing.TB, pool Pooler) error

SetPoolForTest closes the unused interception pool and installs a replacement. Call it after interception is selected, before requests, reloads, or shutdown. The server owns the replacement pool and shuts it down with the server.

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown waits for all exiting in-flight requests to complete, or the context to expire, whichever comes first.

type ServerOption

type ServerOption func(*Server)

ServerOption configures a Server at construction.

func WithPoolOptions

func WithPoolOptions(options PoolOptions) ServerOption

WithPoolOptions builds the server's interception pool with options instead of DefaultPoolOptions. The deployment's record policy reaches the pool that serves requests this way; see PoolOptionsFromConfig.

Directories

Path Synopsis
Package aibridgedmock is a generated GoMock package.
Package aibridgedmock is a generated GoMock package.

Jump to

Keyboard shortcuts

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