Documentation
¶
Overview ¶
Package superbrain provides intelligent orchestration and self-healing capabilities for the switchAILocal gateway.
Overview ¶
Superbrain transforms switchAILocal from a passive API gateway into an autonomous, self-healing AI orchestrator. Instead of treating errors as terminal states, Superbrain actively monitors executions, diagnoses failures using AI, and takes autonomous remediation actions to ensure requests succeed.
Architecture ¶
The Superbrain architecture implements an "Observer-Critic" duality where every execution is monitored by a lightweight Supervisor that can:
- Detect failures in real-time (within seconds, not minutes)
- Diagnose issues using AI (permission prompts, auth errors, context limits)
- Take autonomous healing actions (stdin injection, process restart, intelligent failover)
- Report all actions transparently (healing metadata in responses)
Core Components ¶
The Superbrain system consists of several specialized components:
- overwatch: Real-time monitoring of CLI process execution with heartbeat detection
- doctor: AI-powered failure diagnosis using lightweight models
- injector: Autonomous stdin injection to respond to interactive prompts
- recovery: Process restart with corrective flags based on diagnosis
- router: Intelligent failover routing to alternative providers
- sculptor: Pre-flight content analysis and optimization for context limits
- metadata: Aggregation of healing actions for transparent reporting
- audit: Structured logging of all autonomous actions for security review
- metrics: Observability infrastructure for monitoring healing effectiveness
- security: Safety controls and fail-safes for autonomous operations
Usage Example ¶
The SuperbrainExecutor wraps existing provider executors to add self-healing:
// Create a Superbrain-enhanced executor
executor := superbrain.NewSuperbrainExecutor(
baseExecutor,
config.Superbrain,
)
// Execute requests with automatic healing
response, err := executor.Execute(ctx, auth, request, opts)
// Check if healing occurred
if metadata, ok := response.Extra["superbrain"].(map[string]interface{}); ok {
if healed, _ := metadata["healed"].(bool); healed {
log.Info("Request was healed by Superbrain")
}
}
Operational Modes ¶
Superbrain supports multiple operational modes for gradual rollout:
- disabled: Superbrain is completely disabled (legacy pass-through mode)
- observe: Monitor and log, but take no autonomous actions
- diagnose: Diagnose failures and log proposed actions without executing them
- conservative: Heal safe patterns only (whitelisted prompts, known recoverable errors)
- autopilot: Full autonomous healing for all detected issues
Configuration ¶
Superbrain is configured via the config.yaml file:
superbrain:
enabled: true
mode: "conservative"
overwatch:
silence_threshold_ms: 30000
max_restart_attempts: 2
doctor:
model: "gemini-flash"
stdin_injection:
mode: "conservative"
fallback:
enabled: true
providers: ["geminicli", "gemini", "ollama"]
Security & Safety ¶
Superbrain includes multiple safety controls:
- Stdin injection whitelist: Only safe patterns are auto-approved
- Forbidden operations: Security-sensitive operations require human approval
- Audit logging: All autonomous actions are logged for review
- Restart limits: Prevents infinite healing loops
- Emergency disable: Single config flag reverts to pass-through mode
Monitoring ¶
Superbrain exposes comprehensive metrics for observability:
- Total healing attempts and success rate
- Healing actions by type (stdin injection, restart, fallback, etc.)
- Average healing latency
- Silence detections and diagnoses performed
Access metrics via the management endpoint:
curl http://localhost:18080/management/metrics
Documentation ¶
For detailed user documentation, see docs/user/superbrain.md
For implementation details, see the design document at .kiro/specs/superbrain-intelligence/design.md
Package superbrain provides intelligent orchestration and self-healing capabilities for the switchAILocal gateway.
Package superbrain provides intelligent orchestration and self-healing capabilities for the switchAILocal gateway. It transforms the gateway from a passive proxy into an autonomous system that can detect failures, diagnose issues, and take remediation actions.
Index ¶
- Constants
- type Diagnosis
- type DiagnosticSnapshot
- type FailureType
- type HealingAction
- type HealingMetadata
- type HeartbeatIntegration
- type HighDensityMap
- type NegotiatedFailureResponse
- type ProviderExecutor
- type RemediationType
- type SuperbrainExecutor
- func (se *SuperbrainExecutor) CountTokens(ctx context.Context, auth *sdkauth.Auth, req switchailocalexecutor.Request, ...) (switchailocalexecutor.Response, error)
- func (se *SuperbrainExecutor) Execute(ctx context.Context, auth *sdkauth.Auth, req switchailocalexecutor.Request, ...) (switchailocalexecutor.Response, error)
- func (se *SuperbrainExecutor) ExecuteStream(ctx context.Context, auth *sdkauth.Auth, req switchailocalexecutor.Request, ...) (<-chan switchailocalexecutor.StreamChunk, error)
- func (se *SuperbrainExecutor) GetConfig() *config.SuperbrainConfig
- func (se *SuperbrainExecutor) Identifier() string
- func (se *SuperbrainExecutor) Refresh(ctx context.Context, auth *sdkauth.Auth) (*sdkauth.Auth, error)
- func (se *SuperbrainExecutor) Stop()
- func (se *SuperbrainExecutor) UpdateConfig(cfg *config.SuperbrainConfig)
- type SuperbrainExecutorOption
- func WithAuditLogger(al *audit.Logger) SuperbrainExecutorOption
- func WithDoctor(d *doctor.InternalDoctor) SuperbrainExecutorOption
- func WithFallbackRouter(fr *router.FallbackRouter) SuperbrainExecutorOption
- func WithInjector(i *injector.StdinInjector) SuperbrainExecutorOption
- func WithMetricsCollector(mc *metrics.Metrics) SuperbrainExecutorOption
- func WithMonitor(m *overwatch.Monitor) SuperbrainExecutorOption
- func WithRestartManager(rm *recovery.RestartManager) SuperbrainExecutorOption
Constants ¶
const ( FailureTypePermissionPrompt = types.FailureTypePermissionPrompt FailureTypeAuthError = types.FailureTypeAuthError FailureTypeContextExceeded = types.FailureTypeContextExceeded FailureTypeRateLimit = types.FailureTypeRateLimit FailureTypeNetworkError = types.FailureTypeNetworkError FailureTypeProcessCrash = types.FailureTypeProcessCrash FailureTypeUnknown = types.FailureTypeUnknown RemediationStdinInject = types.RemediationStdinInject RemediationRestartFlags = types.RemediationRestartFlags RemediationFallback = types.RemediationFallback RemediationRetry = types.RemediationRetry RemediationAbort = types.RemediationAbort )
Re-export constants for backward compatibility
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type DiagnosticSnapshot ¶
type DiagnosticSnapshot = types.DiagnosticSnapshot
type FailureType ¶
type FailureType = types.FailureType
type HealingAction ¶
type HealingAction = types.HealingAction
Type aliases for backward compatibility
type HealingMetadata ¶
type HealingMetadata = types.HealingMetadata
type HeartbeatIntegration ¶
type HeartbeatIntegration struct {
// contains filtered or unexported fields
}
HeartbeatIntegration manages the connection between HeartbeatMonitor and Superbrain.
func NewHeartbeatIntegration ¶
func NewHeartbeatIntegration(monitor heartbeat.HeartbeatMonitor) *HeartbeatIntegration
NewHeartbeatIntegration creates a new integration instance.
func (*HeartbeatIntegration) HandleEvent ¶
func (hi *HeartbeatIntegration) HandleEvent(event *heartbeat.HeartbeatEvent) error
HandleEvent implements the HeartbeatEventHandler interface.
func (*HeartbeatIntegration) Start ¶
func (hi *HeartbeatIntegration) Start() error
Start enables the integration by registering as an event handler.
func (*HeartbeatIntegration) Stop ¶
func (hi *HeartbeatIntegration) Stop() error
Stop disables the integration.
type HighDensityMap ¶
type HighDensityMap = types.HighDensityMap
type NegotiatedFailureResponse ¶
type NegotiatedFailureResponse = types.NegotiatedFailureResponse
type ProviderExecutor ¶
type ProviderExecutor interface {
Identifier() string
Execute(ctx context.Context, auth *sdkauth.Auth, req switchailocalexecutor.Request, opts switchailocalexecutor.Options) (switchailocalexecutor.Response, error)
ExecuteStream(ctx context.Context, auth *sdkauth.Auth, req switchailocalexecutor.Request, opts switchailocalexecutor.Options) (<-chan switchailocalexecutor.StreamChunk, error)
Refresh(ctx context.Context, auth *sdkauth.Auth) (*sdkauth.Auth, error)
CountTokens(ctx context.Context, auth *sdkauth.Auth, req switchailocalexecutor.Request, opts switchailocalexecutor.Options) (switchailocalexecutor.Response, error)
}
ProviderExecutor defines the contract for provider executors that can be wrapped by Superbrain.
type RemediationType ¶
type RemediationType = types.RemediationType
type SuperbrainExecutor ¶
type SuperbrainExecutor struct {
// contains filtered or unexported fields
}
SuperbrainExecutor wraps existing executors with Superbrain monitoring and healing capabilities. It implements the ProviderExecutor interface and adds intelligent orchestration.
func NewSuperbrainExecutor ¶
func NewSuperbrainExecutor(wrapped ProviderExecutor, cfg *config.SuperbrainConfig, opts ...SuperbrainExecutorOption) *SuperbrainExecutor
NewSuperbrainExecutor creates a new SuperbrainExecutor wrapping the given executor.
func (*SuperbrainExecutor) CountTokens ¶
func (se *SuperbrainExecutor) CountTokens(ctx context.Context, auth *sdkauth.Auth, req switchailocalexecutor.Request, opts switchailocalexecutor.Options) (switchailocalexecutor.Response, error)
CountTokens returns the token count for the given request.
func (*SuperbrainExecutor) Execute ¶
func (se *SuperbrainExecutor) Execute(ctx context.Context, auth *sdkauth.Auth, req switchailocalexecutor.Request, opts switchailocalexecutor.Options) (switchailocalexecutor.Response, error)
Execute handles non-streaming execution with Superbrain monitoring and healing.
func (*SuperbrainExecutor) ExecuteStream ¶
func (se *SuperbrainExecutor) ExecuteStream(ctx context.Context, auth *sdkauth.Auth, req switchailocalexecutor.Request, opts switchailocalexecutor.Options) (<-chan switchailocalexecutor.StreamChunk, error)
ExecuteStream handles streaming execution with Superbrain monitoring and healing.
func (*SuperbrainExecutor) GetConfig ¶
func (se *SuperbrainExecutor) GetConfig() *config.SuperbrainConfig
GetConfig returns the current Superbrain configuration.
func (*SuperbrainExecutor) Identifier ¶
func (se *SuperbrainExecutor) Identifier() string
Identifier returns the provider key handled by this executor.
func (*SuperbrainExecutor) Refresh ¶
func (se *SuperbrainExecutor) Refresh(ctx context.Context, auth *sdkauth.Auth) (*sdkauth.Auth, error)
Refresh attempts to refresh provider credentials.
func (*SuperbrainExecutor) Stop ¶
func (se *SuperbrainExecutor) Stop()
Stop stops the Superbrain executor and cleans up resources.
func (*SuperbrainExecutor) UpdateConfig ¶
func (se *SuperbrainExecutor) UpdateConfig(cfg *config.SuperbrainConfig)
UpdateConfig updates the Superbrain configuration at runtime.
type SuperbrainExecutorOption ¶
type SuperbrainExecutorOption func(*SuperbrainExecutor)
SuperbrainExecutorOption is a functional option for configuring the SuperbrainExecutor.
func WithAuditLogger ¶
func WithAuditLogger(al *audit.Logger) SuperbrainExecutorOption
WithAuditLogger sets a custom audit logger.
func WithDoctor ¶
func WithDoctor(d *doctor.InternalDoctor) SuperbrainExecutorOption
WithDoctor sets a custom doctor.
func WithFallbackRouter ¶
func WithFallbackRouter(fr *router.FallbackRouter) SuperbrainExecutorOption
WithFallbackRouter sets a custom fallback router.
func WithInjector ¶
func WithInjector(i *injector.StdinInjector) SuperbrainExecutorOption
WithInjector sets a custom injector.
func WithMetricsCollector ¶
func WithMetricsCollector(mc *metrics.Metrics) SuperbrainExecutorOption
WithMetricsCollector sets a custom metrics collector.
func WithMonitor ¶
func WithMonitor(m *overwatch.Monitor) SuperbrainExecutorOption
WithMonitor sets a custom monitor.
func WithRestartManager ¶
func WithRestartManager(rm *recovery.RestartManager) SuperbrainExecutorOption
WithRestartManager sets a custom restart manager.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package audit provides structured logging for Superbrain autonomous actions.
|
Package audit provides structured logging for Superbrain autonomous actions. |
|
Package doctor provides AI-powered failure diagnosis for the Superbrain system.
|
Package doctor provides AI-powered failure diagnosis for the Superbrain system. |
|
Package injector provides autonomous stdin injection capabilities for the Superbrain system.
|
Package injector provides autonomous stdin injection capabilities for the Superbrain system. |
|
Package metadata provides functionality for aggregating and managing healing metadata throughout the request lifecycle.
|
Package metadata provides functionality for aggregating and managing healing metadata throughout the request lifecycle. |
|
Package metrics provides observability infrastructure for the Superbrain system.
|
Package metrics provides observability infrastructure for the Superbrain system. |
|
Package overwatch provides real-time execution monitoring capabilities for the Superbrain system.
|
Package overwatch provides real-time execution monitoring capabilities for the Superbrain system. |
|
Package recovery provides process recovery and restart capabilities for the Superbrain system.
|
Package recovery provides process recovery and restart capabilities for the Superbrain system. |
|
Package response provides response enrichment capabilities for the Superbrain system.
|
Package response provides response enrichment capabilities for the Superbrain system. |
|
Package router provides intelligent failover routing between AI providers.
|
Package router provides intelligent failover routing between AI providers. |
|
Package sculptor provides pre-flight content analysis and optimization for the Superbrain system.
|
Package sculptor provides pre-flight content analysis and optimization for the Superbrain system. |
|
Package security provides security controls and fail-safes for the Superbrain system.
|
Package security provides security controls and fail-safes for the Superbrain system. |
|
Package types provides shared type definitions for the Superbrain system.
|
Package types provides shared type definitions for the Superbrain system. |