api

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Apr 18, 2026 License: Apache-2.0 Imports: 42 Imported by: 0

Documentation

Overview

Package api provides the HTTP API server implementation for the switchAILocal. It includes the main server struct, routing setup, middleware for CORS and authentication, and integration with various AI API handlers (OpenAI, Claude, Gemini). The server supports hot-reloading of clients and configuration.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AuthMiddleware

func AuthMiddleware(manager *sdkaccess.Manager) gin.HandlerFunc

AuthMiddleware returns a Gin middleware handler that authenticates requests using the configured authentication providers. When no providers are available, it allows all requests (legacy behaviour).

func StateBoxStatusHandler

func StateBoxStatusHandler(sb *util.StateBox) gin.HandlerFunc

StateBoxStatusHandler returns a handler for the /api/state-box/status endpoint. It provides information about the State Box configuration and file status.

Types

type EventBusIntegrator

type EventBusIntegrator interface {
	ConnectHeartbeatEvents() error
	ConnectRoutingEvents() error
	ConnectProviderEvents() error
	EmitEvent(event interface{}) error
}

EventBusIntegrator defines the interface for event bus integration. This interface allows the server to connect system events to hooks without creating a direct dependency on the integration package.

type FileStatus

type FileStatus struct {
	Path    string    `json:"path"`
	Exists  bool      `json:"exists"`
	Size    int64     `json:"size"`
	Mode    string    `json:"mode"`
	ModTime time.Time `json:"mod_time,omitempty"`
}

FileStatus represents the status of a State Box file.

type IntelligenceService

type IntelligenceService interface {
	IsEnabled() bool
	GetSkillRegistry() *skills.Registry
	GetSemanticCache() intelligence.SemanticCacheInterface
}

IntelligenceService defines the interface for accessing intelligence features.

type ModelDiscoverer

type ModelDiscoverer interface {
	Refresh(ctx context.Context, providerID string) error
	DiscoverAll(ctx context.Context) (map[string][]*registry.ModelInfo, error)
}

ModelDiscoverer is the interface for model discovery refresh operations.

type Server

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

Server represents the main API server. It encapsulates the Gin engine, HTTP server, handlers, and configuration.

func NewServer

func NewServer(cfg *config.Config, authManager *auth.Manager, accessManager *sdkaccess.Manager, configFilePath string, luaEngine *plugin.LuaEngine, opts ...ServerOption) *Server

NewServer creates and initializes a new API server instance. It sets up the Gin engine, middleware, routes, and handlers.

Parameters:

  • cfg: The server configuration
  • authManager: core runtime auth manager
  • accessManager: request authentication manager

Returns:

  • *Server: A new server instance

func (*Server) AttachWebsocketRoute

func (s *Server) AttachWebsocketRoute(path string, handler http.Handler)

AttachWebsocketRoute registers a websocket upgrade handler on the primary Gin engine. The handler is served as-is without additional middleware beyond the standard stack already configured.

func (*Server) GetHandlers

func (s *Server) GetHandlers() *handlers.BaseAPIHandler

GetHandlers returns the base API handlers instance.

func (*Server) SetDiscoverer

func (s *Server) SetDiscoverer(d ModelDiscoverer)

SetDiscoverer sets the model discoverer for refresh operations.

func (*Server) SetWebsocketAuthChangeHandler

func (s *Server) SetWebsocketAuthChangeHandler(fn func(bool, bool))

func (*Server) Start

func (s *Server) Start() error

Start begins listening for and serving HTTP or HTTPS requests. It's a blocking call and will only return on an unrecoverable error.

Returns:

  • error: An error if the server fails to start

func (*Server) Stop

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

Stop gracefully shuts down the API server without interrupting any active connections.

Parameters:

  • ctx: The context for graceful shutdown

Returns:

  • error: An error if the server fails to stop

func (*Server) UpdateClients

func (s *Server) UpdateClients(cfg *config.Config)

UpdateClients updates the server's client list and configuration. This method is called when the configuration or authentication tokens change.

Parameters:

  • clients: The new slice of AI service clients
  • cfg: The new application configuration

type ServerOption

type ServerOption func(*serverOptionConfig)

ServerOption customises HTTP server construction.

func WithEngineConfigurator

func WithEngineConfigurator(fn func(*gin.Engine)) ServerOption

WithEngineConfigurator allows callers to mutate the Gin engine prior to middleware setup.

func WithIntelligenceService

func WithIntelligenceService(svc IntelligenceService) ServerOption

WithIntelligenceService sets the intelligence service for the server.

func WithKeepAliveEndpoint

func WithKeepAliveEndpoint(timeout time.Duration, onTimeout func()) ServerOption

WithKeepAliveEndpoint enables a keep-alive endpoint with the provided timeout and callback.

func WithLocalManagementPassword

func WithLocalManagementPassword(password string) ServerOption

WithLocalManagementPassword stores a runtime-only management password accepted for localhost requests.

func WithMiddleware

func WithMiddleware(mw ...gin.HandlerFunc) ServerOption

WithMiddleware appends additional Gin middleware during server construction.

func WithPipelineIntegrator

func WithPipelineIntegrator(pi handlers.PipelineIntegrator) ServerOption

WithPipelineIntegrator sets the pipeline integrator for intelligent systems integration.

func WithRequestLoggerFactory

func WithRequestLoggerFactory(factory func(*config.Config, string) logging.RequestLogger) ServerOption

WithRequestLoggerFactory customises request logger creation.

func WithRouterConfigurator

func WithRouterConfigurator(fn func(*gin.Engine, *handlers.BaseAPIHandler, *config.Config)) ServerOption

WithRouterConfigurator appends a callback after default routes are registered.

func WithServiceCoordinator

func WithServiceCoordinator(sc ServiceCoordinator) ServerOption

WithServiceCoordinator sets the service coordinator for intelligent systems integration. This option will automatically create and configure a RequestPipelineIntegrator from the coordinator.

func WithStateBox

func WithStateBox(sb *util.StateBox) ServerOption

WithStateBox sets the StateBox for the server.

type ServiceCoordinator

type ServiceCoordinator interface {
	GetMemory() interface{}
	GetHeartbeat() interface{}
	GetSteering() interface{}
	GetHooks() interface{}
	GetEventBus() interface{}
}

ServiceCoordinator defines the interface for accessing intelligent systems. This interface allows the server to access the service coordinator without creating a direct dependency on the integration package.

type StateBoxStatus

type StateBoxStatus struct {
	RootPath          string      `json:"root_path"`
	ReadOnly          bool        `json:"read_only"`
	Initialized       bool        `json:"initialized"`
	DiscoveryRegistry *FileStatus `json:"discovery_registry,omitempty"`
	FeedbackDatabase  *FileStatus `json:"feedback_database,omitempty"`
	PermissionStatus  string      `json:"permission_status"` // "ok", "warning", "error"
	Warnings          []string    `json:"warnings,omitempty"`
	Errors            []string    `json:"errors,omitempty"`
}

StateBoxStatus represents the State Box status for API responses.

Directories

Path Synopsis
handlers
management
Package management provides the management API handlers and middleware for configuring the server and managing auth files.
Package management provides the management API handlers and middleware for configuring the server and managing auth files.
Package middleware provides HTTP middleware components for the switchAILocal server.
Package middleware provides HTTP middleware components for the switchAILocal server.
Package modules provides a pluggable routing module system for extending the API server with optional features without modifying core routing logic.
Package modules provides a pluggable routing module system for extending the API server with optional features without modifying core routing logic.
amp
Package amp implements the Amp CLI routing module, providing OAuth-based integration with Amp CLI for ChatGPT and Anthropic subscriptions.
Package amp implements the Amp CLI routing module, providing OAuth-based integration with Amp CLI for ChatGPT and Anthropic subscriptions.

Jump to

Keyboard shortcuts

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