Documentation
¶
Index ¶
- Constants
- Variables
- func NewTransportFactory(handler http.Handler) aibridge.TransportFactory
- func SubscribeProviderReload(ctx context.Context, ps dbpubsub.Pubsub, reloader ProviderReloader, ...) (func(), error)
- func WatchProviderReload(ctx context.Context, clientFn ClientFuncWithContext, reloader ProviderReloader, ...) error
- func WriteProviderInfoSnapshot(info *prometheus.GaugeVec, outcomes []ProviderOutcome)
- type CachedBridgePool
- func (p *CachedBridgePool) Acquire(ctx context.Context, req Request, clientFn ClientFunc, ...) (_ http.Handler, outErr error)
- func (p *CachedBridgePool) CacheMetrics() PoolMetrics
- func (p *CachedBridgePool) KeyPools() []*keypool.Pool
- func (p *CachedBridgePool) ReplaceProviders(providers []aibridge.Provider)
- func (p *CachedBridgePool) Shutdown(_ context.Context) error
- type Client
- type ClientFunc
- type ClientFuncWithContext
- type DRPCClient
- type DRPCServer
- type Dialer
- type MCPProxyBuilderdeprecated
- type MCPProxyFactorydeprecated
- type Metrics
- type PoolMetrics
- type PoolOptions
- type Pooler
- type ProviderOutcome
- type ProviderReloader
- type ProviderStatus
- type Request
- type Server
- func (s *Server) Client() (DRPCClient, error)
- func (s *Server) ClientContext(ctx context.Context) (DRPCClient, error)
- func (s *Server) Close() error
- func (s *Server) Done() <-chan struct{}
- func (s *Server) Err() error
- func (s *Server) GetRequestHandler(ctx context.Context, req Request) (http.Handler, error)
- func (s *Server) Ready() bool
- func (s *Server) ServeHTTP(rw http.ResponseWriter, r *http.Request)
- func (s *Server) Shutdown(ctx context.Context) error
Constants ¶
const (
InternalMCPServerID = "coder"
)
Variables ¶
var ( ErrNoAuthKey = xerrors.New("no authentication key provided") ErrConnect = xerrors.New("could not connect to coderd") ErrAcquireRequestHandler = xerrors.New("failed to acquire request handler") ErrBudgetCheck = xerrors.New("internal server error checking user AI budget") )
var ( ErrEmptyConfig = xerrors.New("empty config given") ErrCompileRegex = xerrors.New("compile tool regex") )
var DefaultPoolOptions = PoolOptions{MaxItems: 5000, TTL: time.Minute * 15}
var (
ErrShutdown = xerrors.New("aibridged server shutdown")
)
Functions ¶
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 ClientFuncWithContext, 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.ClientContext 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 (*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 key pools of the current live providers.
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.
type Client ¶
type Client struct {
proto.DRPCRecorderClient
proto.DRPCMCPConfiguratorClient
proto.DRPCAuthorizerClient
proto.DRPCProviderConfiguratorClient
Conn drpc.Conn
}
type ClientFunc ¶
type ClientFunc func() (DRPCClient, error)
type ClientFuncWithContext ¶ added in v2.36.0
type ClientFuncWithContext func(context.Context) (DRPCClient, error)
ClientFuncWithContext 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.ClientContext satisfies it.
type DRPCClient ¶
type DRPCClient interface {
proto.DRPCRecorderClient
proto.DRPCMCPConfiguratorClient
proto.DRPCAuthorizerClient
proto.DRPCProviderConfiguratorClient
}
DRPCClient is the union of various service interfaces the client must support.
type DRPCServer ¶
type DRPCServer interface {
proto.DRPCRecorderServer
proto.DRPCMCPConfiguratorServer
proto.DRPCAuthorizerServer
proto.DRPCProviderConfiguratorServer
}
type Dialer ¶
type Dialer func(ctx context.Context) (DRPCClient, error)
func NewWebsocketDialer ¶ added in v2.36.0
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
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 pool. 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 Pooler ¶
type Pooler interface {
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 (which the pool keeps as 503 stubs) and errored rows (which the pool excludes). Err is populated only when Status == ProviderStatusError; the build error is already logged at the call site.
type ProviderReloader ¶
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" )
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server provides the AI Bridge functionality. It is responsible for:
- receiving requests on /api/v2/aibridged/*
- manipulating the requests
- relaying requests to upstream AI services and relaying responses to caller
It requires a Dialer to provide a DRPCClient implementation to communicate with a DRPCServer implementation, to persist state and perform other functions.
func (*Server) Client ¶
func (s *Server) Client() (DRPCClient, error)
func (*Server) ClientContext ¶ added in v2.36.0
func (s *Server) ClientContext(ctx context.Context) (DRPCClient, error)
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) GetRequestHandler ¶
GetRequestHandler retrieves a (possibly reused) [*aibridge.RequestBridge] from the pool, for the given user.
func (*Server) Ready ¶ added in v2.36.0
Ready reports whether the server currently has an active DRPC connection to coderd.
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.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package aibridgedmock is a generated GoMock package.
|
Package aibridgedmock is a generated GoMock package. |