Documentation
¶
Overview ¶
Package client provides usage examples demonstrating the new configuration system while maintaining backward compatibility with existing code.
Package client provides helper functions for common configuration patterns and convenience methods to simplify complex configuration scenarios.
Package client provides configuration profiles and validation helpers to reduce configuration complexity and provide a more user-friendly configuration experience.
Package client provides configuration validation methods to ensure configuration integrity and provide clear error messages.
Package client provides the client SDK for connecting to AG-UI servers.
This package enables Go applications to connect to AG-UI servers and interact with AI agents. It provides a high-level API for sending events, receiving responses, and managing the connection lifecycle.
The client supports multiple transport mechanisms including HTTP/SSE and WebSocket connections, with automatic reconnection and error handling.
Example usage:
import "github.com/mattsp1290/ag-ui/go-sdk/pkg/client"
// Create a new client
c, err := client.New("http://localhost:8080/ag-ui")
if err != nil {
log.Fatal(err)
}
defer c.Close()
// Send an event to an agent
event := &client.MessageEvent{
Content: "Hello, agent!",
}
response, err := c.SendEvent(ctx, "my-agent", event)
if err != nil {
log.Fatal(err)
}
// Process the response
fmt.Println(response)
Package client provides request/response management utilities for the ag-ui Go SDK.
Package client provides resilience patterns for robust HTTP operations. This module implements comprehensive failure handling, recovery mechanisms, and reliability patterns to ensure high availability and fault tolerance.
Index ¶
- Constants
- Variables
- func ConvertSSEToEvent(sseEvent *SSEEvent) (events.Event, error)
- func ExampleBackwardCompatibility()
- func ExampleConfigValidation()
- func ExampleDevelopmentSetup()
- func ExampleMicroserviceMesh()
- func ExampleMigrationPath()
- func ExampleNewWayAdvanced()
- func ExampleNewWaySimple()
- func ExampleOldWay()
- func ExamplePerformanceComparison()
- func ExampleQuickHelpers()
- func ExampleTemplateUsage()
- func ExampleWebAPIServer()
- type APIKeyConfig
- type APIKeyInfo
- type APIKeyManager
- func (akm *APIKeyManager) Cleanup() error
- func (akm *APIKeyManager) CreateAPIKey(userID, username, email string, roles, permissions, scopes []string, ...) (*APIKeyInfo, error)
- func (akm *APIKeyManager) GetAPIKeyInfo(keyID string) (*APIKeyInfo, error)
- func (akm *APIKeyManager) ListAPIKeys(userID string) ([]*APIKeyInfo, error)
- func (akm *APIKeyManager) RevokeAPIKey(keyID string) error
- func (akm *APIKeyManager) UpdateAPIKey(keyID string, updates map[string]interface{}) error
- func (akm *APIKeyManager) ValidateAPIKey(apiKey string) (*UserInfo, error)
- type APIKeyStore
- type Agent
- type AgentCapabilities
- type AgentConfig
- type AgentConfigManager
- func (acm *AgentConfigManager) AddConfigChangeListener(agentName string, listener ConfigChangeListener)
- func (acm *AgentConfigManager) AddSource(source ConfigSource)
- func (acm *AgentConfigManager) GetMetrics() ConfigMetrics
- func (acm *AgentConfigManager) LoadConfig(ctx context.Context, agentName string) (*AgentConfig, error)
- func (acm *AgentConfigManager) RegisterSchema(schema *ConfigSchema)
- func (acm *AgentConfigManager) ReloadConfig(ctx context.Context, agentName string) (*AgentConfig, error)
- func (acm *AgentConfigManager) Start(ctx context.Context) error
- func (acm *AgentConfigManager) Stop(ctx context.Context) error
- func (acm *AgentConfigManager) UpdateConfigValue(ctx context.Context, agentName, path string, value interface{}) error
- type AgentEventProcessor
- type AgentHealthStatus
- type AgentMetadata
- type AgentMetrics
- type AgentState
- type AgentStateManager
- func (sm *AgentStateManager) Cleanup() error
- func (sm *AgentStateManager) GetMetrics() StateManagerMetrics
- func (sm *AgentStateManager) GetState(ctx context.Context) (interface{}, error)
- func (sm *AgentStateManager) GetVersion(versionID string) (*StateVersion, error)
- func (sm *AgentStateManager) IsHealthy() bool
- func (sm *AgentStateManager) RollbackToVersion(ctx context.Context, versionID string) error
- func (sm *AgentStateManager) Start(ctx context.Context) error
- func (sm *AgentStateManager) Stop(ctx context.Context) error
- func (sm *AgentStateManager) Subscribe(path string, callback func(StateChangeEvent), filter StateFilter) string
- func (sm *AgentStateManager) Unsubscribe(subscriptionID string)
- func (sm *AgentStateManager) UpdateState(ctx context.Context, delta interface{}) error
- type AgentStatus
- type AgentToolManager
- func (tm *AgentToolManager) CancelExecution(executionID string) error
- func (tm *AgentToolManager) Cleanup() error
- func (tm *AgentToolManager) ExecuteTool(ctx context.Context, name string, params interface{}) (interface{}, error)
- func (tm *AgentToolManager) ExecuteToolStreaming(ctx context.Context, name string, params interface{}) (<-chan StreamingResult, error)
- func (tm *AgentToolManager) GetExecution(executionID string) (*ToolExecution, error)
- func (tm *AgentToolManager) GetMetrics() ToolManagerMetrics
- func (tm *AgentToolManager) IsHealthy() bool
- func (tm *AgentToolManager) ListTools() []ToolDefinition
- func (tm *AgentToolManager) RegisterTool(tool *tools.Tool) error
- func (tm *AgentToolManager) Start(ctx context.Context) error
- func (tm *AgentToolManager) Stop(ctx context.Context) error
- func (tm *AgentToolManager) UnregisterTool(name string) error
- type AuditLogEntry
- type AuditLogger
- func (al *AuditLogger) Cleanup() error
- func (al *AuditLogger) GetAuditStats() map[string]interface{}
- func (al *AuditLogger) LogAuthenticationEvent(eventType string, userID string, ipAddress string, success bool, ...)
- func (al *AuditLogger) LogAuthorizationEvent(userID, resource, action, ipAddress string, success bool, errorMsg string, ...)
- func (al *AuditLogger) LogDataAccessEvent(userID, resource, action, ipAddress string, success bool, ...)
- func (al *AuditLogger) LogEvent(event *SecurityEvent)
- func (al *AuditLogger) LogSecurityEvent(...)
- func (al *AuditLogger) LogTokenEvent(eventType, userID, tokenType, ipAddress string, ...)
- type AuditLoggingConfig
- type AuthMethod
- type AuthenticationResult
- type BackpressureManager
- type BackpressureMode
- type BaseAgent
- func (a *BaseAgent) Capabilities() AgentCapabilities
- func (a *BaseAgent) Cleanup() error
- func (a *BaseAgent) Description() string
- func (a *BaseAgent) ExecuteTool(ctx context.Context, name string, params interface{}) (interface{}, error)
- func (a *BaseAgent) ExecuteToolAsync(ctx context.Context, name string, params interface{}, priority int) (string, <-chan *tools.AsyncResult, error)
- func (a *BaseAgent) ExecuteToolStream(ctx context.Context, name string, params interface{}) (<-chan *tools.ToolStreamChunk, error)
- func (a *BaseAgent) GetState(ctx context.Context) (*AgentState, error)
- func (a *BaseAgent) GetToolMetrics() *tools.ExecutionMetrics
- func (a *BaseAgent) Health() AgentHealthStatus
- func (a *BaseAgent) Initialize(ctx context.Context, config *AgentConfig) error
- func (a *BaseAgent) ListTools() []ToolDefinition
- func (a *BaseAgent) Name() string
- func (a *BaseAgent) ProcessEvent(ctx context.Context, event events.Event) ([]events.Event, error)
- func (a *BaseAgent) RegisterCustomTool(tool *tools.Tool) error
- func (a *BaseAgent) Start(ctx context.Context) error
- func (a *BaseAgent) Stop(ctx context.Context) error
- func (a *BaseAgent) StreamEvents(ctx context.Context) (<-chan events.Event, error)
- func (a *BaseAgent) UnregisterCustomTool(toolID string) error
- func (a *BaseAgent) UpdateState(ctx context.Context, delta *StateDelta) error
- type BasicAuthConfig
- type BasicAuthManager
- func (bam *BasicAuthManager) Cleanup() error
- func (bam *BasicAuthManager) CreateUser(username, password, email, fullName string, roles, permissions []string) (*BasicAuthUser, error)
- func (bam *BasicAuthManager) DeleteUser(username string) error
- func (bam *BasicAuthManager) GetUser(username string) (*BasicAuthUser, error)
- func (bam *BasicAuthManager) ListUsers() ([]*BasicAuthUser, error)
- func (bam *BasicAuthManager) UpdateUser(username string, updates map[string]interface{}) error
- func (bam *BasicAuthManager) ValidateCredentials(username, password string) (*UserInfo, error)
- type BasicAuthStore
- type BasicAuthUser
- type Bulkhead
- type BulkheadConfig
- type CORSConfig
- type CachedConfig
- type CachedResult
- type CertValidationConfig
- type CertificateInfo
- type CertificateManager
- func (cm *CertificateManager) CheckCertificateExpiry(warnDays int) []string
- func (cm *CertificateManager) Cleanup() error
- func (cm *CertificateManager) GetCertificateInfo() ([]*CertificateInfo, error)
- func (cm *CertificateManager) GetLastReloadTime() time.Time
- func (cm *CertificateManager) GetTLSConfig() (*tls.Config, error)
- func (cm *CertificateManager) ReloadCertificates() error
- func (cm *CertificateManager) ValidateCertificateChain(certChain []*x509.Certificate) error
- type CertificateWatcher
- type CircuitBreaker
- type CircuitBreakerConfig
- type CircuitBreakerState
- type Client
- func (c *Client) Close() error
- func (c *Client) GetAgent(name string) (Agent, error)
- func (c *Client) GetConfig() Config
- func (c *Client) IsClosed() bool
- func (c *Client) ListAgents() []string
- func (c *Client) RegisterAgent(agent Agent) error
- func (c *Client) SendEvent(ctx context.Context, agentName string, event any) (responses []any, err error)
- func (c *Client) SendEventToAgent(ctx context.Context, agentName string, event any) ([]any, error)
- func (c *Client) Stream(ctx context.Context, agentName string) (eventChan <-chan any, err error)
- func (c *Client) UnregisterAgent(name string) error
- type Config
- type ConfigBuilder
- func APIGatewayConfig() *ConfigBuilder
- func BatchProcessingConfig(batchName string) *ConfigBuilder
- func DatabaseAgentConfig(dbName string) *ConfigBuilder
- func EdgeComputingConfig(edgeName string) *ConfigBuilder
- func LoadBalancerConfig(lbName string) *ConfigBuilder
- func MicroserviceConfig(serviceName, baseURL string) *ConfigBuilder
- func NewConfigBuilder() *ConfigBuilder
- func NewDevelopmentConfig() *ConfigBuilder
- func NewMinimalConfig() *ConfigBuilder
- func NewProductionConfig() *ConfigBuilder
- func StreamingConfig(streamName string) *ConfigBuilder
- func TestingConfig(testName string) *ConfigBuilder
- func (cb *ConfigBuilder) Build() (*AgentConfig, *HttpConfig, *SecurityConfig, *SSEClientConfig, ...)
- func (cb *ConfigBuilder) BuildAgentConfig() (*AgentConfig, error)
- func (cb *ConfigBuilder) BuildHttpConfig() (*HttpConfig, error)
- func (cb *ConfigBuilder) BuildSecurityConfig() (*SecurityConfig, error)
- func (cb *ConfigBuilder) ForDevelopment() *ConfigBuilder
- func (cb *ConfigBuilder) ForHighPerformance() *ConfigBuilder
- func (cb *ConfigBuilder) ForProduction() *ConfigBuilder
- func (cb *ConfigBuilder) ForSecure() *ConfigBuilder
- func (cb *ConfigBuilder) Validate() error
- func (cb *ConfigBuilder) WithAPIKeyAuth(headerName, prefix string) *ConfigBuilder
- func (cb *ConfigBuilder) WithAgent(config *AgentConfig) *ConfigBuilder
- func (cb *ConfigBuilder) WithAgentDescription(description string) *ConfigBuilder
- func (cb *ConfigBuilder) WithAgentName(name string) *ConfigBuilder
- func (cb *ConfigBuilder) WithAuthMethod(method AuthMethod) *ConfigBuilder
- func (cb *ConfigBuilder) WithCORS(allowedOrigins, allowedMethods, allowedHeaders []string) *ConfigBuilder
- func (cb *ConfigBuilder) WithCircuitBreaker(enabled bool, failureThreshold, successThreshold int, timeout time.Duration) *ConfigBuilder
- func (cb *ConfigBuilder) WithHTTP(config *HttpConfig) *ConfigBuilder
- func (cb *ConfigBuilder) WithHTTP2(enabled, force bool) *ConfigBuilder
- func (cb *ConfigBuilder) WithHTTPConnectionLimits(maxIdle, maxIdlePerHost, maxPerHost int) *ConfigBuilder
- func (cb *ConfigBuilder) WithHTTPTimeouts(dial, request, response time.Duration) *ConfigBuilder
- func (cb *ConfigBuilder) WithInsecureTLS() *ConfigBuilder
- func (cb *ConfigBuilder) WithJWTAuth(signingMethod, secretKey string, accessTTL, refreshTTL time.Duration) *ConfigBuilder
- func (cb *ConfigBuilder) WithRateLimit(requestsPerSecond float64, burstSize int) *ConfigBuilder
- func (cb *ConfigBuilder) WithResilience(config *ResilienceConfig) *ConfigBuilder
- func (cb *ConfigBuilder) WithRetry(maxAttempts int, baseDelay, maxDelay time.Duration) *ConfigBuilder
- func (cb *ConfigBuilder) WithSSE(config *SSEClientConfig) *ConfigBuilder
- func (cb *ConfigBuilder) WithSSEBackoff(initial, max time.Duration, multiplier float64) *ConfigBuilder
- func (cb *ConfigBuilder) WithSecurity(config *SecurityConfig) *ConfigBuilder
- func (cb *ConfigBuilder) WithTLS(enabled bool, certFile, keyFile, caFile string) *ConfigBuilder
- type ConfigChangeEvent
- type ConfigChangeListener
- type ConfigFormat
- type ConfigMetrics
- type ConfigProfile
- type ConfigSchema
- type ConfigSource
- type ConfigTemplate
- type ConfigValidator
- type ConfigWatcher
- type ConflictResolutionStrategy
- type ConflictResolver
- type ConnectionPool
- type ConnectionPoolStats
- type Conversation
- type DatabaseConfig
- type DropStrategy
- type EncryptedTokenData
- type EncryptionConfig
- type EnvConfigSource
- type EventHandler
- type EventProcessingConfig
- type EventProcessor
- func (ep *EventProcessor) Cleanup() error
- func (ep *EventProcessor) GetMetrics() EventProcessorMetrics
- func (ep *EventProcessor) IsHealthy() bool
- func (ep *EventProcessor) ProcessEvent(ctx context.Context, event events.Event) ([]events.Event, error)
- func (ep *EventProcessor) RegisterHandler(eventType events.EventType, handler EventHandler)
- func (ep *EventProcessor) SetDefaultHandler(handler EventHandler)
- func (ep *EventProcessor) Start(ctx context.Context) error
- func (ep *EventProcessor) Stop(ctx context.Context) error
- type EventProcessorMetrics
- type EventSequenceTracker
- type EvictionPolicy
- type ExecutionStatus
- type FileConfigSource
- type FileHistoryPersister
- func (fhp *FileHistoryPersister) DeleteConversation(conversationID string) error
- func (fhp *FileHistoryPersister) DeleteMessage(messageID string) error
- func (fhp *FileHistoryPersister) DeleteThread(threadID string) error
- func (fhp *FileHistoryPersister) LoadAllMessages() ([]*StoredMessage, error)
- func (fhp *FileHistoryPersister) LoadConversation(conversationID string) (*Conversation, error)
- func (fhp *FileHistoryPersister) LoadMessage(messageID string) (*StoredMessage, error)
- func (fhp *FileHistoryPersister) LoadThread(threadID string) (*Thread, error)
- func (fhp *FileHistoryPersister) SaveConversation(conversation *Conversation) error
- func (fhp *FileHistoryPersister) SaveMessage(message *StoredMessage) error
- func (fhp *FileHistoryPersister) SaveThread(thread *Thread) error
- type FileTokenStorage
- func (fts *FileTokenStorage) Cleanup() error
- func (fts *FileTokenStorage) CleanupExpiredTokens() error
- func (fts *FileTokenStorage) GetToken(token string) (*TokenInfo, error)
- func (fts *FileTokenStorage) ListTokens(userID string) ([]*TokenInfo, error)
- func (fts *FileTokenStorage) RevokeToken(token string) error
- func (fts *FileTokenStorage) StoreToken(token string, info *TokenInfo) error
- type FirstWriterWinsResolver
- type HMACConfig
- type HMACManager
- func (hm *HMACManager) AddSecretKey(keyID, secretKey string)
- func (hm *HMACManager) Cleanup() error
- func (hm *HMACManager) GetSignatureInfo(req *http.Request) (*HMACSignatureInfo, error)
- func (hm *HMACManager) ListKeyIDs() []string
- func (hm *HMACManager) RemoveSecretKey(keyID string)
- func (hm *HMACManager) SignRequest(req *http.Request, keyID, secretKey string) error
- func (hm *HMACManager) ValidateSignature(req *http.Request) (*UserInfo, error)
- func (hm *HMACManager) VerifySignatureComponents(req *http.Request) map[string]interface{}
- type HMACSignatureInfo
- type HTTPMetrics
- type HTTPTransport
- func (h *HTTPTransport) GetConnectionPoolStats() ConnectionPoolStats
- func (h *HTTPTransport) GetMetrics() *HTTPMetrics
- func (h *HTTPTransport) GetPerformanceStats() *PerformanceStats
- func (h *HTTPTransport) GetProtocolVersion() string
- func (h *HTTPTransport) IsHealthy() bool
- func (h *HTTPTransport) SendRequest(ctx context.Context, method, path string, body []byte) (*http.Response, error)
- func (h *HTTPTransport) Start(ctx context.Context) error
- func (h *HTTPTransport) Stop(ctx context.Context) error
- type HTTPTransportConfig
- type HealthCheckConfig
- type HealthChecker
- type HealthStatus
- type HistoryConfig
- type HistoryMemoryManager
- type HistoryMetrics
- type HistoryPersister
- type HttpAgent
- func (h *HttpAgent) Cleanup() error
- func (h *HttpAgent) GetHttpMetrics() *HttpMetrics
- func (h *HttpAgent) HttpClient() *http.Client
- func (h *HttpAgent) Initialize(ctx context.Context, config *AgentConfig) error
- func (h *HttpAgent) SendRequest(ctx context.Context, req *http.Request) (*http.Response, error)
- func (h *HttpAgent) Start(ctx context.Context) error
- func (h *HttpAgent) Stop(ctx context.Context) error
- type HttpConfig
- type HttpMetrics
- type HttpProtocolVersion
- type JWTConfig
- type JWTManager
- func (jm *JWTManager) BlacklistToken(tokenString string) error
- func (jm *JWTManager) Cleanup() error
- func (jm *JWTManager) GenerateRefreshToken(subject string, claims jwt.MapClaims) (string, error)
- func (jm *JWTManager) GenerateToken(subject string, claims jwt.MapClaims) (string, error)
- func (jm *JWTManager) GetTokenInfo(tokenString string) (*TokenInfo, error)
- func (jm *JWTManager) RefreshAccessToken(refreshTokenString string) (string, error)
- func (jm *JWTManager) ShouldRefresh(tokenInfo *TokenInfo) bool
- func (jm *JWTManager) ValidateRefreshToken(tokenString string) (jwt.MapClaims, error)
- func (jm *JWTManager) ValidateToken(tokenString string) (jwt.MapClaims, error)
- type KeepAliveManager
- type LastWriterWinsResolver
- type LifecycleManager
- type LogRotator
- type MemoryTokenStorage
- func (mts *MemoryTokenStorage) Cleanup() error
- func (mts *MemoryTokenStorage) CleanupExpiredTokens() error
- func (mts *MemoryTokenStorage) GetToken(token string) (*TokenInfo, error)
- func (mts *MemoryTokenStorage) ListTokens(userID string) ([]*TokenInfo, error)
- func (mts *MemoryTokenStorage) RevokeToken(token string) error
- func (mts *MemoryTokenStorage) StoreToken(token string, info *TokenInfo) error
- type MergeResolver
- type MessageHistoryManager
- func (mhm *MessageHistoryManager) AddMessage(ctx context.Context, message *messages.Message, conversationID string) error
- func (mhm *MessageHistoryManager) Cleanup() error
- func (mhm *MessageHistoryManager) DeleteMessage(ctx context.Context, messageID string) error
- func (mhm *MessageHistoryManager) GetConversation(ctx context.Context, conversationID string) (*Conversation, error)
- func (mhm *MessageHistoryManager) GetConversationMessages(ctx context.Context, conversationID string) ([]*messages.Message, error)
- func (mhm *MessageHistoryManager) GetMessage(ctx context.Context, messageID string) (*messages.Message, error)
- func (mhm *MessageHistoryManager) GetMetrics() HistoryMetrics
- func (mhm *MessageHistoryManager) IsHealthy() bool
- func (mhm *MessageHistoryManager) SearchMessages(ctx context.Context, query MessageQuery) ([]*messages.Message, error)
- func (mhm *MessageHistoryManager) Start(ctx context.Context) error
- func (mhm *MessageHistoryManager) Stop(ctx context.Context) error
- type MessageIndices
- type MessageQuery
- type MetricsCollector
- func (mc *MetricsCollector) GetMetrics() map[string]interface{}
- func (mc *MetricsCollector) RecordBulkheadReject()
- func (mc *MetricsCollector) RecordCircuitBreakerReject()
- func (mc *MetricsCollector) RecordFailure(duration time.Duration)
- func (mc *MetricsCollector) RecordRateLimitReject()
- func (mc *MetricsCollector) RecordSuccess(duration time.Duration)
- type MetricsConfig
- type Middleware
- type NetworkPolicy
- type PasswordPolicy
- type PerformanceStats
- type PropertyConstraints
- type PropertySpec
- func (ps *PropertySpec) WithDefault(value interface{}) *PropertySpec
- func (ps *PropertySpec) WithEnum(values ...interface{}) *PropertySpec
- func (ps *PropertySpec) WithEnvVar(envVar string) *PropertySpec
- func (ps *PropertySpec) WithLength(minLength, maxLength int) *PropertySpec
- func (ps *PropertySpec) WithMinMax(min, max float64) *PropertySpec
- func (ps *PropertySpec) WithRequired(required bool) *PropertySpec
- func (ps *PropertySpec) WithSensitive(sensitive bool) *PropertySpec
- type RateLimitConfig
- type RateLimiter
- type RedisConfig
- type RemoteConfigSource
- type RequestCorrelation
- type RequestManager
- func (rm *RequestManager) AddMiddleware(middleware Middleware)
- func (rm *RequestManager) Close() error
- func (rm *RequestManager) Do(ctx context.Context, req *http.Request) (*http.Response, error)
- func (rm *RequestManager) GetActiveCorrelations() map[string]*RequestCorrelation
- func (rm *RequestManager) GetCircuitBreakerState() CircuitBreakerState
- func (rm *RequestManager) GetCorrelationMapStats() map[string]interface{}
- type RequestManagerConfig
- type RequestMetrics
- type ResilienceConfig
- type ResilienceManager
- type ResourceLimits
- type ResourceMonitor
- type RetryConfig
- type RetryManager
- type RetryPolicy
- type SSEClient
- func (c *SSEClient) BufferLength() int
- func (c *SSEClient) Close() error
- func (c *SSEClient) Connect(ctx context.Context) error
- func (c *SSEClient) Events() <-chan *SSEEvent
- func (c *SSEClient) IsBackpressureActive() bool
- func (c *SSEClient) LastEventID() string
- func (c *SSEClient) ReconnectCount() int
- func (c *SSEClient) State() SSEConnectionState
- type SSEClientConfig
- type SSEClientState
- type SSEConnectionState
- type SSEEvent
- type SecurityConfig
- type SecurityEvent
- type SecurityHeaderManager
- func (shm *SecurityHeaderManager) AddCustomHeader(name, value string)
- func (shm *SecurityHeaderManager) ApplySecurityHeaders(w http.ResponseWriter, r *http.Request)
- func (shm *SecurityHeaderManager) GenerateNonce() (string, error)
- func (shm *SecurityHeaderManager) GetCSPViolationHandler() http.HandlerFunc
- func (shm *SecurityHeaderManager) GetSecurityHeadersInfo() map[string]interface{}
- func (shm *SecurityHeaderManager) Middleware() func(http.Handler) http.Handler
- func (shm *SecurityHeaderManager) RemoveCustomHeader(name string)
- func (shm *SecurityHeaderManager) UpdateCSPPolicy(policy string) error
- func (shm *SecurityHeaderManager) ValidateCSPPolicy(policy string) []string
- type SecurityHeadersConfig
- type SecurityManager
- func (sm *SecurityManager) Authenticate(ctx context.Context, req *http.Request) (*AuthenticationResult, error)
- func (sm *SecurityManager) AuthenticationMiddleware() func(http.Handler) http.Handler
- func (sm *SecurityManager) AuthorizeRequest(ctx context.Context, user *UserInfo, resource string, action string) error
- func (sm *SecurityManager) Cleanup() error
- func (sm *SecurityManager) RefreshToken(ctx context.Context, refreshToken string) (*TokenInfo, error)
- func (sm *SecurityManager) RevokeToken(ctx context.Context, token string) error
- type SequenceState
- type SessionConfig
- type SessionInfo
- type StateCache
- type StateChangeEvent
- type StateCondition
- type StateConfig
- type StateDelta
- type StateFilter
- type StateManager
- type StateManagerMetrics
- type StateOperation
- type StateOperationType
- type StateSubscription
- type StateVersion
- type StoredMessage
- type StreamingResult
- type TLSConfig
- type Thread
- type TimeRange
- type TimeoutConfig
- type TimestampIndex
- type TokenEncryptor
- type TokenInfo
- type TokenStorage
- type TokenStorageConfig
- type TokenStore
- type TokenType
- type ToolCache
- type ToolDefinition
- type ToolExecution
- type ToolExecutionFramework
- func (f *ToolExecutionFramework) CancelAll()
- func (f *ToolExecutionFramework) Execute(ctx context.Context, name string, params map[string]interface{}) (*tools.ToolExecutionResult, error)
- func (f *ToolExecutionFramework) ExecuteStream(ctx context.Context, name string, params map[string]interface{}) (<-chan *tools.ToolStreamChunk, error)
- func (f *ToolExecutionFramework) GetExecutionEngine() *tools.ExecutionEngine
- func (f *ToolExecutionFramework) GetMetrics() *tools.ExecutionMetrics
- func (f *ToolExecutionFramework) GetRegistry() *tools.Registry
- func (f *ToolExecutionFramework) GetTool(toolID string) (tools.ReadOnlyTool, error)
- func (f *ToolExecutionFramework) ListTools() []tools.ReadOnlyTool
- func (f *ToolExecutionFramework) RegisterTool(tool *tools.Tool) error
- func (f *ToolExecutionFramework) Shutdown(ctx context.Context) error
- func (f *ToolExecutionFramework) UnregisterTool(toolID string) error
- type ToolExecutor
- type ToolManagerMetrics
- type ToolRunner
- type ToolSandbox
- type ToolsConfig
- type UserInfo
Constants ¶
const ( // Validation errors ErrConfigNil = "config_nil" ErrNameRequired = "name_required" ErrBufferSizeInvalid = "buffer_size_invalid" ErrBatchSizeInvalid = "batch_size_invalid" ErrMaxConcurrentInvalid = "max_concurrent_invalid" ErrMaxMessagesInvalid = "max_messages_invalid" // Operation errors ErrEmptyPath = "empty_path" ErrConditionNotMet = "condition_not_met" ErrUnknownOperation = "unknown_operation" // Tool execution errors ErrToolSerializeFailed = "tool_serialize_failed" ErrToolDeserializeFailed = "tool_deserialize_failed" ErrToolExecutionFailed = "tool_execution_failed" ErrToolExecutionError = "tool_execution_error" )
Common error conditions for BaseAgent
const ( // HTTP configuration errors ErrHTTPConfigNil = "config_nil" ErrMaxIdleConnsInvalid = "max_idle_conns_invalid" ErrMaxIdleConnsPerHostInvalid = "max_idle_conns_per_host_invalid" ErrMaxConnsPerHostInvalid = "max_conns_per_host_invalid" ErrDialTimeoutInvalid = "dial_timeout_invalid" ErrRequestTimeoutInvalid = "request_timeout_invalid" ErrMaxResponseBodySizeInvalid = "max_response_body_size_invalid" )
Common error conditions for HttpAgent
Variables ¶
var ( ErrClientClosed = errors.New("client is closed") ErrAgentNotFound = errors.New("agent not found") ErrAgentAlreadyRegistered = errors.New("agent already registered") )
Common client errors
var ( // Request manager errors ErrRequestCancelled = fmt.Errorf("request cancelled") ErrRequestTimeout = fmt.Errorf("request timeout") ErrInvalidURL = fmt.Errorf("invalid URL") ErrInvalidMethod = fmt.Errorf("invalid HTTP method") ErrSecurityViolation = fmt.Errorf("security validation failed") ErrRateLimitExceeded = fmt.Errorf("rate limit exceeded") ErrCircuitBreakerOpen = fmt.Errorf("circuit breaker open") )
Functions ¶
func ConvertSSEToEvent ¶
ConvertSSEToEvent converts an SSE event to an AG-UI event
func ExampleBackwardCompatibility ¶
func ExampleBackwardCompatibility()
ExampleBackwardCompatibility demonstrates that old code still works
func ExampleConfigValidation ¶
func ExampleConfigValidation()
ExampleConfigValidation demonstrates configuration validation
func ExampleDevelopmentSetup ¶
func ExampleDevelopmentSetup()
ExampleDevelopmentSetup demonstrates development environment setup
func ExampleMicroserviceMesh ¶
func ExampleMicroserviceMesh()
ExampleMicroserviceMesh demonstrates configuration for service mesh
func ExampleMigrationPath ¶
func ExampleMigrationPath()
ExampleMigrationPath demonstrates how to migrate from old to new configuration
func ExampleNewWayAdvanced ¶
func ExampleNewWayAdvanced()
ExampleNewWayAdvanced demonstrates advanced configuration building
func ExampleNewWaySimple ¶
func ExampleNewWaySimple()
ExampleNewWaySimple demonstrates the new simple way using profiles
func ExampleOldWay ¶
func ExampleOldWay()
ExampleOldWay demonstrates the old way of creating configurations
func ExamplePerformanceComparison ¶
func ExamplePerformanceComparison()
ExamplePerformanceComparison demonstrates the efficiency of new approach
func ExampleQuickHelpers ¶
func ExampleQuickHelpers()
ExampleQuickHelpers demonstrates using quick helper functions
func ExampleTemplateUsage ¶
func ExampleTemplateUsage()
ExampleTemplateUsage demonstrates using predefined templates
func ExampleWebAPIServer ¶
func ExampleWebAPIServer()
ExampleWebAPIServer demonstrates configuration for a web API server
Types ¶
type APIKeyConfig ¶
type APIKeyConfig struct {
HeaderName string `json:"header_name" yaml:"header_name"`
QueryParam string `json:"query_param" yaml:"query_param"`
Prefix string `json:"prefix" yaml:"prefix"`
KeysFile string `json:"keys_file" yaml:"keys_file"`
HashingAlgorithm string `json:"hashing_algorithm" yaml:"hashing_algorithm"`
EnableKeyRotation bool `json:"enable_key_rotation" yaml:"enable_key_rotation"`
KeyRotationInterval time.Duration `json:"key_rotation_interval" yaml:"key_rotation_interval"`
}
APIKeyConfig contains API key authentication configuration
func QuickAPIKeyConfig ¶
func QuickAPIKeyConfig(headerName, prefix string) *APIKeyConfig
QuickAPIKeyConfig creates a simple API key configuration
func (*APIKeyConfig) Validate ¶
func (akc *APIKeyConfig) Validate() error
Validate validates APIKeyConfig
type APIKeyInfo ¶
type APIKeyInfo struct {
ID string `json:"id"`
Key string `json:"key"`
HashedKey string `json:"hashed_key"`
UserID string `json:"user_id"`
Username string `json:"username"`
Email string `json:"email"`
Roles []string `json:"roles"`
Permissions []string `json:"permissions"`
Scopes []string `json:"scopes"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
IsActive bool `json:"is_active"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
// Usage tracking
UsageCount int64 `json:"usage_count"`
RateLimit int `json:"rate_limit,omitempty"` // requests per minute
QuotaLimit int64 `json:"quota_limit,omitempty"` // total requests allowed
QuotaUsed int64 `json:"quota_used"`
QuotaReset time.Time `json:"quota_reset,omitempty"`
}
APIKeyInfo contains information about an API key
type APIKeyManager ¶
type APIKeyManager struct {
// contains filtered or unexported fields
}
APIKeyManager handles API key validation and management
func NewAPIKeyManager ¶
func NewAPIKeyManager(config *APIKeyConfig, logger *zap.Logger) (*APIKeyManager, error)
NewAPIKeyManager creates a new API key manager
func (*APIKeyManager) Cleanup ¶
func (akm *APIKeyManager) Cleanup() error
Cleanup performs cleanup operations
func (*APIKeyManager) CreateAPIKey ¶
func (akm *APIKeyManager) CreateAPIKey(userID, username, email string, roles, permissions, scopes []string, expiresIn *time.Duration) (*APIKeyInfo, error)
CreateAPIKey creates a new API key
func (*APIKeyManager) GetAPIKeyInfo ¶
func (akm *APIKeyManager) GetAPIKeyInfo(keyID string) (*APIKeyInfo, error)
GetAPIKeyInfo returns information about an API key
func (*APIKeyManager) ListAPIKeys ¶
func (akm *APIKeyManager) ListAPIKeys(userID string) ([]*APIKeyInfo, error)
ListAPIKeys returns a list of API keys for a user
func (*APIKeyManager) RevokeAPIKey ¶
func (akm *APIKeyManager) RevokeAPIKey(keyID string) error
RevokeAPIKey revokes an API key
func (*APIKeyManager) UpdateAPIKey ¶
func (akm *APIKeyManager) UpdateAPIKey(keyID string, updates map[string]interface{}) error
UpdateAPIKey updates an existing API key
func (*APIKeyManager) ValidateAPIKey ¶
func (akm *APIKeyManager) ValidateAPIKey(apiKey string) (*UserInfo, error)
ValidateAPIKey validates an API key and returns user information
type APIKeyStore ¶
type APIKeyStore struct {
Keys map[string]*APIKeyInfo `json:"keys"`
LastUpdated time.Time `json:"last_updated"`
Version string `json:"version"`
}
APIKeyStore represents stored API keys data
type Agent ¶
type Agent interface {
LifecycleManager
AgentEventProcessor
StateManager
ToolRunner
AgentMetadata
}
Agent defines the complete interface that all AG-UI agents must implement. This interface composes smaller, focused interfaces following the Interface Segregation Principle. Each component interface has a single responsibility:
- LifecycleManager: handles agent lifecycle (init, start, stop, cleanup)
- AgentEventProcessor: handles event processing and streaming
- StateManager: handles agent state operations
- ToolRunner: handles tool execution and discovery
- AgentMetadata: provides agent metadata and health status
This design allows for better testing, easier mocking, and more flexible implementations while maintaining backward compatibility.
type AgentCapabilities ¶
type AgentCapabilities struct {
Tools []string `json:"tools"`
Streaming bool `json:"streaming"`
StateSync bool `json:"state_sync"`
MessageHistory bool `json:"message_history"`
CustomCapabilities map[string]interface{} `json:"custom_capabilities,omitempty"`
}
AgentCapabilities describes what features an agent supports.
type AgentConfig ¶
type AgentConfig struct {
Name string `json:"name" yaml:"name"`
Description string `json:"description" yaml:"description"`
Capabilities AgentCapabilities `json:"capabilities" yaml:"capabilities"`
EventProcessing EventProcessingConfig `json:"event_processing" yaml:"event_processing"`
State StateConfig `json:"state" yaml:"state"`
Tools ToolsConfig `json:"tools" yaml:"tools"`
History HistoryConfig `json:"history" yaml:"history"`
Custom map[string]interface{} `json:"custom,omitempty" yaml:"custom,omitempty"`
}
AgentConfig contains configuration options for agent initialization.
func DefaultAgentConfig ¶
func DefaultAgentConfig() *AgentConfig
DefaultAgentConfig returns a default configuration for agents.
func (*AgentConfig) Validate ¶
func (ac *AgentConfig) Validate() error
Validate validates the AgentConfig and returns detailed errors
type AgentConfigManager ¶
type AgentConfigManager struct {
// contains filtered or unexported fields
}
AgentConfigManager provides comprehensive agent configuration management with agent-specific configuration schemas, dynamic configuration updates, validation with defaults, environment-based configuration loading, and configuration inheritance and overrides.
Key features:
- Type-safe configuration structures
- Validation with clear error messages
- Hot-reloading capabilities
- Integration with global configuration system
- Environment variable support
- Configuration inheritance and composition
- Dynamic configuration updates
- Schema validation and defaults
func NewAgentConfigManager ¶
func NewAgentConfigManager() *AgentConfigManager
NewAgentConfigManager creates a new agent configuration manager.
func (*AgentConfigManager) AddConfigChangeListener ¶
func (acm *AgentConfigManager) AddConfigChangeListener(agentName string, listener ConfigChangeListener)
AddConfigChangeListener adds a listener for configuration changes.
func (*AgentConfigManager) AddSource ¶
func (acm *AgentConfigManager) AddSource(source ConfigSource)
AddSource adds a configuration source.
func (*AgentConfigManager) GetMetrics ¶
func (acm *AgentConfigManager) GetMetrics() ConfigMetrics
GetMetrics returns current configuration metrics.
func (*AgentConfigManager) LoadConfig ¶
func (acm *AgentConfigManager) LoadConfig(ctx context.Context, agentName string) (*AgentConfig, error)
LoadConfig loads configuration for the specified agent.
func (*AgentConfigManager) RegisterSchema ¶
func (acm *AgentConfigManager) RegisterSchema(schema *ConfigSchema)
RegisterSchema registers a configuration schema for validation.
func (*AgentConfigManager) ReloadConfig ¶
func (acm *AgentConfigManager) ReloadConfig(ctx context.Context, agentName string) (*AgentConfig, error)
ReloadConfig reloads configuration for the specified agent.
func (*AgentConfigManager) Start ¶
func (acm *AgentConfigManager) Start(ctx context.Context) error
Start begins configuration management.
func (*AgentConfigManager) Stop ¶
func (acm *AgentConfigManager) Stop(ctx context.Context) error
Stop gracefully stops configuration management.
func (*AgentConfigManager) UpdateConfigValue ¶
func (acm *AgentConfigManager) UpdateConfigValue(ctx context.Context, agentName, path string, value interface{}) error
UpdateConfigValue updates a specific configuration value dynamically.
type AgentEventProcessor ¶
type AgentEventProcessor interface {
// ProcessEvent handles a single incoming event and returns response events.
// The agent must be running for this to succeed.
ProcessEvent(ctx context.Context, event events.Event) ([]events.Event, error)
// StreamEvents returns a channel for receiving events from the agent.
// The agent must be running and support streaming for this to succeed.
StreamEvents(ctx context.Context) (<-chan events.Event, error)
}
AgentEventProcessor handles event processing and streaming operations. This interface is responsible for all event-related functionality including single event processing and continuous event streaming.
type AgentHealthStatus ¶
type AgentHealthStatus struct {
Status string `json:"status"`
LastCheck time.Time `json:"last_check"`
Details map[string]interface{} `json:"details,omitempty"`
Errors []string `json:"errors,omitempty"`
}
HealthStatus represents the current health of an agent.
type AgentMetadata ¶
type AgentMetadata interface {
// Name returns the unique identifier for this agent instance.
Name() string
// Description returns a human-readable description of the agent's purpose.
Description() string
// Capabilities returns information about what this agent can do.
Capabilities() AgentCapabilities
// Health returns the current health status of the agent.
Health() AgentHealthStatus
}
AgentMetadata provides access to agent metadata and status information. This interface handles read-only agent properties and health status.
type AgentMetrics ¶
type AgentMetrics struct {
EventsProcessed int64 `json:"events_processed"`
EventsPerSecond float64 `json:"events_per_second"`
AverageProcessingTime time.Duration `json:"average_processing_time"`
ToolsExecuted int64 `json:"tools_executed"`
StateUpdates int64 `json:"state_updates"`
ErrorCount int64 `json:"error_count"`
MemoryUsage int64 `json:"memory_usage"`
StartTime time.Time `json:"start_time"`
LastActivity time.Time `json:"last_activity"`
// contains filtered or unexported fields
}
AgentMetrics contains performance and operational metrics for an agent. Fields are padded to prevent false sharing between frequently accessed atomic counters.
type AgentState ¶
type AgentState struct {
// Status is the current lifecycle status
Status AgentStatus `json:"status"`
// Name is the agent identifier
Name string `json:"name"`
// Version is the state version for conflict resolution
Version int64 `json:"version"`
// Data contains the agent's custom state data
Data map[string]interface{} `json:"data"`
// Metadata contains additional state information
Metadata map[string]interface{} `json:"metadata"`
// LastModified is when the state was last updated
LastModified time.Time `json:"last_modified"`
// Checksum for state integrity verification
Checksum string `json:"checksum,omitempty"`
}
AgentState represents the complete state of an agent
type AgentStateManager ¶
type AgentStateManager struct {
// contains filtered or unexported fields
}
AgentStateManager provides agent-specific state management with local caching, remote synchronization, conflict resolution, state versioning, and performance optimization for state operations.
Key features:
- Integration with existing state management system
- Configurable synchronization policies
- Efficient state diff computation
- Memory and storage optimization
- Local state caching and persistence
- Conflict resolution strategies
- State versioning and rollback
func NewAgentStateManager ¶
func NewAgentStateManager(config StateConfig) (*AgentStateManager, error)
NewAgentStateManager creates a new agent state manager with the given configuration.
func (*AgentStateManager) Cleanup ¶
func (sm *AgentStateManager) Cleanup() error
Cleanup releases all resources.
func (*AgentStateManager) GetMetrics ¶
func (sm *AgentStateManager) GetMetrics() StateManagerMetrics
GetMetrics returns current state manager metrics.
func (*AgentStateManager) GetState ¶
func (sm *AgentStateManager) GetState(ctx context.Context) (interface{}, error)
GetState returns the current state of the agent.
func (*AgentStateManager) GetVersion ¶
func (sm *AgentStateManager) GetVersion(versionID string) (*StateVersion, error)
GetVersion returns a specific state version.
func (*AgentStateManager) IsHealthy ¶
func (sm *AgentStateManager) IsHealthy() bool
IsHealthy returns the health status.
func (*AgentStateManager) RollbackToVersion ¶
func (sm *AgentStateManager) RollbackToVersion(ctx context.Context, versionID string) error
RollbackToVersion rolls back the state to a specific version.
func (*AgentStateManager) Start ¶
func (sm *AgentStateManager) Start(ctx context.Context) error
Start begins state management operations.
func (*AgentStateManager) Stop ¶
func (sm *AgentStateManager) Stop(ctx context.Context) error
Stop gracefully stops state management.
func (*AgentStateManager) Subscribe ¶
func (sm *AgentStateManager) Subscribe(path string, callback func(StateChangeEvent), filter StateFilter) string
Subscribe to state changes.
func (*AgentStateManager) Unsubscribe ¶
func (sm *AgentStateManager) Unsubscribe(subscriptionID string)
Unsubscribe from state changes.
func (*AgentStateManager) UpdateState ¶
func (sm *AgentStateManager) UpdateState(ctx context.Context, delta interface{}) error
UpdateState applies a state change delta.
type AgentStatus ¶
type AgentStatus string
AgentStatus represents the lifecycle status of an agent.
const ( AgentStatusUninitialized AgentStatus = "uninitialized" AgentStatusInitialized AgentStatus = "initialized" AgentStatusStarting AgentStatus = "starting" AgentStatusRunning AgentStatus = "running" AgentStatusStopping AgentStatus = "stopping" AgentStatusStopped AgentStatus = "stopped" AgentStatusError AgentStatus = "error" )
type AgentToolManager ¶
type AgentToolManager struct {
// contains filtered or unexported fields
}
AgentToolManager provides seamless tool integration for agents with tool discovery, registration, execution with parameter validation, streaming responses, result caching, security sandboxing, and comprehensive error handling.
Key features:
- Integration with existing tool system
- Asynchronous tool execution
- Resource limits and timeout handling
- Tool discovery and registration
- Streaming tool responses
- Security and sandboxing for tool execution
- Tool result caching and optimization
func NewAgentToolManager ¶
func NewAgentToolManager(config ToolsConfig) (*AgentToolManager, error)
NewAgentToolManager creates a new agent tool manager with the given configuration.
func (*AgentToolManager) CancelExecution ¶
func (tm *AgentToolManager) CancelExecution(executionID string) error
CancelExecution cancels a running execution.
func (*AgentToolManager) Cleanup ¶
func (tm *AgentToolManager) Cleanup() error
Cleanup releases all resources.
func (*AgentToolManager) ExecuteTool ¶
func (tm *AgentToolManager) ExecuteTool(ctx context.Context, name string, params interface{}) (interface{}, error)
ExecuteTool executes a tool with the given name and parameters.
func (*AgentToolManager) ExecuteToolStreaming ¶
func (tm *AgentToolManager) ExecuteToolStreaming(ctx context.Context, name string, params interface{}) (<-chan StreamingResult, error)
ExecuteToolStreaming executes a tool with streaming results.
func (*AgentToolManager) GetExecution ¶
func (tm *AgentToolManager) GetExecution(executionID string) (*ToolExecution, error)
GetExecution returns information about a specific execution.
func (*AgentToolManager) GetMetrics ¶
func (tm *AgentToolManager) GetMetrics() ToolManagerMetrics
GetMetrics returns current tool manager metrics.
func (*AgentToolManager) IsHealthy ¶
func (tm *AgentToolManager) IsHealthy() bool
IsHealthy returns the health status.
func (*AgentToolManager) ListTools ¶
func (tm *AgentToolManager) ListTools() []ToolDefinition
ListTools returns a list of available tools.
func (*AgentToolManager) RegisterTool ¶
func (tm *AgentToolManager) RegisterTool(tool *tools.Tool) error
RegisterTool registers a new tool with the manager.
func (*AgentToolManager) Start ¶
func (tm *AgentToolManager) Start(ctx context.Context) error
Start begins tool management operations.
func (*AgentToolManager) Stop ¶
func (tm *AgentToolManager) Stop(ctx context.Context) error
Stop gracefully stops tool management.
func (*AgentToolManager) UnregisterTool ¶
func (tm *AgentToolManager) UnregisterTool(name string) error
UnregisterTool removes a tool from the manager.
type AuditLogEntry ¶
type AuditLogEntry struct {
Timestamp time.Time `json:"timestamp"`
Level string `json:"level"`
EventType string `json:"event_type"`
UserID string `json:"user_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
IPAddress string `json:"ip_address,omitempty"`
UserAgent string `json:"user_agent,omitempty"`
Resource string `json:"resource,omitempty"`
Action string `json:"action,omitempty"`
Result string `json:"result"`
Error string `json:"error,omitempty"`
Duration string `json:"duration,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
Sensitive bool `json:"sensitive,omitempty"`
TraceID string `json:"trace_id,omitempty"`
RequestID string `json:"request_id,omitempty"`
}
AuditLogEntry represents a structured audit log entry
type AuditLogger ¶
type AuditLogger struct {
// contains filtered or unexported fields
}
AuditLogger handles security audit logging
func NewAuditLogger ¶
func NewAuditLogger(config *AuditLoggingConfig, logger *zap.Logger) (*AuditLogger, error)
NewAuditLogger creates a new audit logger
func (*AuditLogger) Cleanup ¶
func (al *AuditLogger) Cleanup() error
Cleanup performs cleanup operations
func (*AuditLogger) GetAuditStats ¶
func (al *AuditLogger) GetAuditStats() map[string]interface{}
GetAuditStats returns statistics about audit logging
func (*AuditLogger) LogAuthenticationEvent ¶
func (al *AuditLogger) LogAuthenticationEvent(eventType string, userID string, ipAddress string, success bool, errorMsg string, metadata map[string]interface{})
LogAuthenticationEvent logs authentication-related events
func (*AuditLogger) LogAuthorizationEvent ¶
func (al *AuditLogger) LogAuthorizationEvent(userID, resource, action, ipAddress string, success bool, errorMsg string, metadata map[string]interface{})
LogAuthorizationEvent logs authorization-related events
func (*AuditLogger) LogDataAccessEvent ¶
func (al *AuditLogger) LogDataAccessEvent(userID, resource, action, ipAddress string, success bool, metadata map[string]interface{})
LogDataAccessEvent logs data access events
func (*AuditLogger) LogEvent ¶
func (al *AuditLogger) LogEvent(event *SecurityEvent)
LogEvent logs a security event
func (*AuditLogger) LogSecurityEvent ¶
func (al *AuditLogger) LogSecurityEvent(eventType, userID, sessionID, ipAddress, userAgent, resource, action, result, errorMsg string, metadata map[string]interface{})
LogSecurityEvent is a convenience method for logging security events
func (*AuditLogger) LogTokenEvent ¶
func (al *AuditLogger) LogTokenEvent(eventType, userID, tokenType, ipAddress string, metadata map[string]interface{})
LogTokenEvent logs token-related events
type AuditLoggingConfig ¶
type AuditLoggingConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
LogLevel string `json:"log_level" yaml:"log_level"`
LogFile string `json:"log_file" yaml:"log_file"`
LogFormat string `json:"log_format" yaml:"log_format"`
RotateSize int64 `json:"rotate_size" yaml:"rotate_size"`
RotateCount int `json:"rotate_count" yaml:"rotate_count"`
LogSensitiveData bool `json:"log_sensitive_data" yaml:"log_sensitive_data"`
EventTypes []string `json:"event_types" yaml:"event_types"`
IncludeRequestBody bool `json:"include_request_body" yaml:"include_request_body"`
IncludeResponseBody bool `json:"include_response_body" yaml:"include_response_body"`
}
AuditLoggingConfig contains audit logging configuration
func (*AuditLoggingConfig) Validate ¶
func (alc *AuditLoggingConfig) Validate() error
Validate validates AuditLoggingConfig (stub implementation)
type AuthMethod ¶
type AuthMethod string
AuthMethod represents the type of authentication method
const ( // AuthMethodJWT uses JSON Web Tokens for authentication AuthMethodJWT AuthMethod = "jwt" // AuthMethodAPIKey uses API key-based authentication AuthMethodAPIKey AuthMethod = "api_key" // AuthMethodBasic uses HTTP Basic authentication AuthMethodBasic AuthMethod = "basic" // AuthMethodBearer uses Bearer token authentication AuthMethodBearer AuthMethod = "bearer" // AuthMethodMTLS uses mutual TLS authentication AuthMethodMTLS AuthMethod = "mtls" // AuthMethodHMAC uses HMAC signature-based authentication AuthMethodHMAC AuthMethod = "hmac" )
type AuthenticationResult ¶
type AuthenticationResult struct {
Success bool `json:"success"`
User *UserInfo `json:"user,omitempty"`
Token *TokenInfo `json:"token,omitempty"`
Session *SessionInfo `json:"session,omitempty"`
Error error `json:"error,omitempty"`
RequiredScopes []string `json:"required_scopes,omitempty"`
GrantedScopes []string `json:"granted_scopes,omitempty"`
}
AuthenticationResult contains the result of an authentication attempt
type BackpressureManager ¶
type BackpressureManager struct {
// contains filtered or unexported fields
}
BackpressureManager handles backpressure for event processing.
type BackpressureMode ¶
type BackpressureMode int
BackpressureMode defines how backpressure is handled.
const ( BackpressureModeBlock BackpressureMode = iota BackpressureModeDrop BackpressureModeCircuitBreaker )
type BaseAgent ¶
type BaseAgent struct {
// contains filtered or unexported fields
}
BaseAgent provides a common implementation of the Agent interface that can be embedded by specific agent implementations.
func NewBaseAgent ¶
NewBaseAgent creates a new base agent with default configuration.
func (*BaseAgent) Capabilities ¶
func (a *BaseAgent) Capabilities() AgentCapabilities
Capabilities returns information about what this agent can do.
func (*BaseAgent) Description ¶
Description returns a human-readable description of the agent's purpose.
func (*BaseAgent) ExecuteTool ¶
func (a *BaseAgent) ExecuteTool(ctx context.Context, name string, params interface{}) (interface{}, error)
ExecuteTool executes a tool with the given name and parameters.
func (*BaseAgent) ExecuteToolAsync ¶
func (a *BaseAgent) ExecuteToolAsync(ctx context.Context, name string, params interface{}, priority int) (string, <-chan *tools.AsyncResult, error)
ExecuteToolAsync executes a tool asynchronously and returns a job ID and result channel.
func (*BaseAgent) ExecuteToolStream ¶
func (a *BaseAgent) ExecuteToolStream(ctx context.Context, name string, params interface{}) (<-chan *tools.ToolStreamChunk, error)
ExecuteToolStream executes a streaming tool and returns a channel of stream chunks.
func (*BaseAgent) GetState ¶
func (a *BaseAgent) GetState(ctx context.Context) (*AgentState, error)
GetState returns the current state of the agent.
func (*BaseAgent) GetToolMetrics ¶
func (a *BaseAgent) GetToolMetrics() *tools.ExecutionMetrics
GetToolMetrics returns tool execution metrics for this agent.
func (*BaseAgent) Health ¶
func (a *BaseAgent) Health() AgentHealthStatus
Health returns the current health status of the agent.
func (*BaseAgent) Initialize ¶
func (a *BaseAgent) Initialize(ctx context.Context, config *AgentConfig) error
Initialize prepares the agent with the given configuration.
func (*BaseAgent) ListTools ¶
func (a *BaseAgent) ListTools() []ToolDefinition
ListTools returns a list of tools available to this agent.
func (*BaseAgent) ProcessEvent ¶
ProcessEvent handles a single incoming event and returns response events.
func (*BaseAgent) RegisterCustomTool ¶
RegisterCustomTool registers a custom tool for this agent. This allows specific agent implementations to add their own tools.
func (*BaseAgent) StreamEvents ¶
StreamEvents returns a channel for receiving events from the agent.
func (*BaseAgent) UnregisterCustomTool ¶
UnregisterCustomTool removes a custom tool from this agent.
func (*BaseAgent) UpdateState ¶
func (a *BaseAgent) UpdateState(ctx context.Context, delta *StateDelta) error
UpdateState applies a state change delta to the agent's state.
type BasicAuthConfig ¶
type BasicAuthConfig struct {
Realm string `json:"realm" yaml:"realm"`
UsersFile string `json:"users_file" yaml:"users_file"`
HashingAlgorithm string `json:"hashing_algorithm" yaml:"hashing_algorithm"`
EnablePasswordPolicy bool `json:"enable_password_policy" yaml:"enable_password_policy"`
PasswordPolicy PasswordPolicy `json:"password_policy" yaml:"password_policy"`
}
BasicAuthConfig contains Basic authentication configuration
func (*BasicAuthConfig) Validate ¶
func (bac *BasicAuthConfig) Validate() error
Validate validates BasicAuthConfig
type BasicAuthManager ¶
type BasicAuthManager struct {
// contains filtered or unexported fields
}
BasicAuthManager handles Basic authentication
func NewBasicAuthManager ¶
func NewBasicAuthManager(config *BasicAuthConfig, logger *zap.Logger) (*BasicAuthManager, error)
NewBasicAuthManager creates a new Basic auth manager
func (*BasicAuthManager) Cleanup ¶
func (bam *BasicAuthManager) Cleanup() error
Cleanup performs cleanup operations
func (*BasicAuthManager) CreateUser ¶
func (bam *BasicAuthManager) CreateUser(username, password, email, fullName string, roles, permissions []string) (*BasicAuthUser, error)
CreateUser creates a new user
func (*BasicAuthManager) DeleteUser ¶
func (bam *BasicAuthManager) DeleteUser(username string) error
DeleteUser deletes a user
func (*BasicAuthManager) GetUser ¶
func (bam *BasicAuthManager) GetUser(username string) (*BasicAuthUser, error)
GetUser returns information about a specific user
func (*BasicAuthManager) ListUsers ¶
func (bam *BasicAuthManager) ListUsers() ([]*BasicAuthUser, error)
ListUsers returns a list of all users
func (*BasicAuthManager) UpdateUser ¶
func (bam *BasicAuthManager) UpdateUser(username string, updates map[string]interface{}) error
UpdateUser updates an existing user
func (*BasicAuthManager) ValidateCredentials ¶
func (bam *BasicAuthManager) ValidateCredentials(username, password string) (*UserInfo, error)
ValidateCredentials validates username and password
type BasicAuthStore ¶
type BasicAuthStore struct {
Users map[string]*BasicAuthUser `json:"users"`
LastUpdated time.Time `json:"last_updated"`
Version string `json:"version"`
}
BasicAuthStore represents the stored users data
type BasicAuthUser ¶
type BasicAuthUser struct {
Username string `json:"username"`
PasswordHash string `json:"password_hash"`
UserID string `json:"user_id"`
Email string `json:"email"`
FullName string `json:"full_name"`
Roles []string `json:"roles"`
Permissions []string `json:"permissions"`
IsActive bool `json:"is_active"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
LastLoginAt *time.Time `json:"last_login_at,omitempty"`
LoginCount int64 `json:"login_count"`
PasswordSet time.Time `json:"password_set"`
MustChangePassword bool `json:"must_change_password"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
// Account security
FailedLoginAttempts int `json:"failed_login_attempts"`
LastFailedLogin *time.Time `json:"last_failed_login,omitempty"`
AccountLockedUntil *time.Time `json:"account_locked_until,omitempty"`
}
BasicAuthUser represents a user in the Basic auth system
type Bulkhead ¶
type Bulkhead struct {
// contains filtered or unexported fields
}
Bulkhead implements resource isolation using semaphores
func NewBulkhead ¶
func NewBulkhead(config BulkheadConfig) *Bulkhead
NewBulkhead creates a new bulkhead
func (*Bulkhead) GetMetrics ¶
GetMetrics returns bulkhead metrics
type BulkheadConfig ¶
type BulkheadConfig struct {
// Enabled indicates if bulkhead isolation is active
Enabled bool `json:"enabled"`
// MaxConcurrentRequests is the maximum concurrent requests
MaxConcurrentRequests int `json:"max_concurrent_requests"`
// QueueSize is the size of the request queue
QueueSize int `json:"queue_size"`
// QueueTimeout is the maximum time to wait in queue
QueueTimeout time.Duration `json:"queue_timeout"`
// SemaphoreTimeout is the timeout for acquiring semaphore
SemaphoreTimeout time.Duration `json:"semaphore_timeout"`
}
BulkheadConfig configures resource isolation patterns
type CORSConfig ¶
type CORSConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
AllowedOrigins []string `json:"allowed_origins" yaml:"allowed_origins"`
AllowedMethods []string `json:"allowed_methods" yaml:"allowed_methods"`
AllowedHeaders []string `json:"allowed_headers" yaml:"allowed_headers"`
ExposedHeaders []string `json:"exposed_headers" yaml:"exposed_headers"`
AllowCredentials bool `json:"allow_credentials" yaml:"allow_credentials"`
MaxAge int `json:"max_age" yaml:"max_age"`
}
CORSConfig contains CORS configuration
func QuickCORSConfig ¶
func QuickCORSConfig(allowedOrigins []string) *CORSConfig
QuickCORSConfig creates a permissive CORS configuration for development
type CachedConfig ¶
type CachedConfig struct {
Data map[string]interface{} `json:"data"`
Source string `json:"source"`
LoadTime time.Time `json:"load_time"`
ExpiresAt time.Time `json:"expires_at"`
Version string `json:"version"`
Checksum string `json:"checksum"`
}
CachedConfig represents cached configuration data.
type CachedResult ¶
type CachedResult struct {
Result interface{} `json:"result"`
Error string `json:"error,omitempty"`
Cached time.Time `json:"cached"`
Hits int64 `json:"hits"`
ExpiresAt time.Time `json:"expires_at"`
}
CachedResult represents a cached tool execution result.
type CertValidationConfig ¶
type CertValidationConfig struct {
ValidateCertChain bool `json:"validate_cert_chain" yaml:"validate_cert_chain"`
ValidateHostname bool `json:"validate_hostname" yaml:"validate_hostname"`
CustomCAPool bool `json:"custom_ca_pool" yaml:"custom_ca_pool"`
CRLCheckEnabled bool `json:"crl_check_enabled" yaml:"crl_check_enabled"`
OCSPCheckEnabled bool `json:"ocsp_check_enabled" yaml:"ocsp_check_enabled"`
}
type CertificateInfo ¶
type CertificateInfo struct {
Subject string `json:"subject"`
Issuer string `json:"issuer"`
SerialNumber string `json:"serial_number"`
NotBefore time.Time `json:"not_before"`
NotAfter time.Time `json:"not_after"`
DNSNames []string `json:"dns_names"`
IPAddresses []string `json:"ip_addresses"`
KeyUsage []string `json:"key_usage"`
IsCA bool `json:"is_ca"`
IsExpired bool `json:"is_expired"`
DaysUntilExpiry int `json:"days_until_expiry"`
}
CertificateInfo contains information about a certificate
type CertificateManager ¶
type CertificateManager struct {
// contains filtered or unexported fields
}
CertificateManager handles TLS certificate management and validation
func NewCertificateManager ¶
func NewCertificateManager(config *TLSConfig, logger *zap.Logger) (*CertificateManager, error)
NewCertificateManager creates a new certificate manager
func (*CertificateManager) CheckCertificateExpiry ¶
func (cm *CertificateManager) CheckCertificateExpiry(warnDays int) []string
CheckCertificateExpiry checks if certificates are close to expiration
func (*CertificateManager) Cleanup ¶
func (cm *CertificateManager) Cleanup() error
Cleanup performs cleanup operations
func (*CertificateManager) GetCertificateInfo ¶
func (cm *CertificateManager) GetCertificateInfo() ([]*CertificateInfo, error)
GetCertificateInfo returns information about the loaded certificates
func (*CertificateManager) GetLastReloadTime ¶
func (cm *CertificateManager) GetLastReloadTime() time.Time
GetLastReloadTime returns the last time certificates were reloaded
func (*CertificateManager) GetTLSConfig ¶
func (cm *CertificateManager) GetTLSConfig() (*tls.Config, error)
GetTLSConfig returns the current TLS configuration
func (*CertificateManager) ReloadCertificates ¶
func (cm *CertificateManager) ReloadCertificates() error
ReloadCertificates reloads certificates from files
func (*CertificateManager) ValidateCertificateChain ¶
func (cm *CertificateManager) ValidateCertificateChain(certChain []*x509.Certificate) error
ValidateCertificateChain validates a certificate chain
type CertificateWatcher ¶
type CertificateWatcher struct {
// contains filtered or unexported fields
}
CertificateWatcher monitors certificate files for changes
type CircuitBreaker ¶
type CircuitBreaker struct {
// contains filtered or unexported fields
}
CircuitBreaker implements the circuit breaker pattern
func NewCircuitBreaker ¶
func NewCircuitBreaker(config CircuitBreakerConfig) *CircuitBreaker
NewCircuitBreaker creates a new circuit breaker
func (*CircuitBreaker) Allow ¶
func (cb *CircuitBreaker) Allow() bool
Circuit breaker implementation
func (*CircuitBreaker) AllowRequest ¶
func (cb *CircuitBreaker) AllowRequest() bool
AllowRequest determines if a request should be allowed
func (*CircuitBreaker) GetMetrics ¶
func (cb *CircuitBreaker) GetMetrics() map[string]interface{}
GetMetrics returns circuit breaker metrics
func (*CircuitBreaker) GetState ¶
func (cb *CircuitBreaker) GetState() CircuitBreakerState
GetState returns the current circuit breaker state
func (*CircuitBreaker) RecordFailure ¶
func (cb *CircuitBreaker) RecordFailure()
RecordFailure records a failed operation
func (*CircuitBreaker) RecordSuccess ¶
func (cb *CircuitBreaker) RecordSuccess()
RecordSuccess records a successful operation
type CircuitBreakerConfig ¶
type CircuitBreakerConfig struct {
// Enabled indicates if circuit breaker is active
Enabled bool `json:"enabled"`
// FailureThreshold is the number of failures before opening
FailureThreshold int `json:"failure_threshold"`
// SuccessThreshold is the number of successes needed to close
SuccessThreshold int `json:"success_threshold"`
// Timeout is how long to wait before attempting to close
Timeout time.Duration `json:"timeout"`
// HalfOpenMaxCalls is max calls allowed in half-open state
HalfOpenMaxCalls int `json:"half_open_max_calls"`
// FailureRateThreshold is the failure rate threshold (0.0 to 1.0)
FailureRateThreshold float64 `json:"failure_rate_threshold"`
// MinimumRequestThreshold is minimum requests before rate calculation
MinimumRequestThreshold int `json:"minimum_request_threshold"`
}
CircuitBreakerConfig configures circuit breaker behavior
func QuickCircuitBreakerConfig ¶
func QuickCircuitBreakerConfig(failureThreshold int, timeout time.Duration) *CircuitBreakerConfig
QuickCircuitBreakerConfig creates a circuit breaker configuration
func (*CircuitBreakerConfig) Validate ¶
func (cbc *CircuitBreakerConfig) Validate() error
Validate validates CircuitBreakerConfig
type CircuitBreakerState ¶
type CircuitBreakerState int
CircuitBreakerState represents the state of a circuit breaker
const ( // CircuitBreakerClosed indicates normal operation CircuitBreakerClosed CircuitBreakerState = iota // CircuitBreakerOpen indicates circuit is open (failing fast) CircuitBreakerOpen // CircuitBreakerHalfOpen indicates testing if service recovered CircuitBreakerHalfOpen )
func (CircuitBreakerState) String ¶
func (s CircuitBreakerState) String() string
String returns the string representation of circuit breaker state
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client represents a connection to an AG-UI server.
func (*Client) ListAgents ¶
ListAgents returns a list of names of all registered agents.
func (*Client) RegisterAgent ¶
RegisterAgent registers an agent with the client for local processing.
func (*Client) SendEvent ¶
func (c *Client) SendEvent(ctx context.Context, agentName string, event any) (responses []any, err error)
SendEvent sends an event to the specified agent and returns the response. If the agent is registered locally, it will process the event directly. Otherwise, it will send the event over the network (when transport layer is implemented).
func (*Client) SendEventToAgent ¶
SendEventToAgent sends an event to a specific registered agent and returns the response. This method bridges the type differences between Client (uses `any`) and Agent (uses `events.Event`).
func (*Client) UnregisterAgent ¶
UnregisterAgent removes an agent from the client.
type Config ¶
type Config struct {
// BaseURL is the base URL of the AG-UI server
BaseURL string
// Timeout for requests (default: 30 seconds)
Timeout time.Duration
// Authentication configuration
AuthToken string
// Retry configuration
MaxRetries int
// User agent string
UserAgent string
}
Config contains configuration options for the client.
type ConfigBuilder ¶
type ConfigBuilder struct {
// contains filtered or unexported fields
}
ConfigBuilder provides a fluent interface for building complex configurations
func APIGatewayConfig ¶
func APIGatewayConfig() *ConfigBuilder
APIGatewayConfig creates a configuration suitable for API gateway scenarios
func BatchProcessingConfig ¶
func BatchProcessingConfig(batchName string) *ConfigBuilder
BatchProcessingConfig creates a configuration for batch processing
func DatabaseAgentConfig ¶
func DatabaseAgentConfig(dbName string) *ConfigBuilder
DatabaseAgentConfig creates a configuration suitable for database operations
func EdgeComputingConfig ¶
func EdgeComputingConfig(edgeName string) *ConfigBuilder
EdgeComputingConfig creates configuration for edge computing scenarios
func LoadBalancerConfig ¶
func LoadBalancerConfig(lbName string) *ConfigBuilder
LoadBalancerConfig creates configuration for load balancer scenarios
func MicroserviceConfig ¶
func MicroserviceConfig(serviceName, baseURL string) *ConfigBuilder
MicroserviceConfig creates a configuration suitable for microservice communication
func NewConfigBuilder ¶
func NewConfigBuilder() *ConfigBuilder
NewConfigBuilder creates a new configuration builder
func NewDevelopmentConfig ¶
func NewDevelopmentConfig() *ConfigBuilder
NewDevelopmentConfig creates a configuration optimized for development and testing
func NewMinimalConfig ¶
func NewMinimalConfig() *ConfigBuilder
NewMinimalConfig creates a configuration with basic functionality only
func NewProductionConfig ¶
func NewProductionConfig() *ConfigBuilder
NewProductionConfig creates a configuration optimized for production deployment
func StreamingConfig ¶
func StreamingConfig(streamName string) *ConfigBuilder
StreamingConfig creates a configuration optimized for streaming operations
func TestingConfig ¶
func TestingConfig(testName string) *ConfigBuilder
TestingConfig creates configuration optimized for testing
func (*ConfigBuilder) Build ¶
func (cb *ConfigBuilder) Build() (*AgentConfig, *HttpConfig, *SecurityConfig, *SSEClientConfig, *ResilienceConfig, error)
Build finalizes the configuration and returns the complete configuration objects
func (*ConfigBuilder) BuildAgentConfig ¶
func (cb *ConfigBuilder) BuildAgentConfig() (*AgentConfig, error)
BuildAgentConfig returns just the agent configuration
func (*ConfigBuilder) BuildHttpConfig ¶
func (cb *ConfigBuilder) BuildHttpConfig() (*HttpConfig, error)
BuildHttpConfig returns just the HTTP configuration
func (*ConfigBuilder) BuildSecurityConfig ¶
func (cb *ConfigBuilder) BuildSecurityConfig() (*SecurityConfig, error)
BuildSecurityConfig returns just the security configuration
func (*ConfigBuilder) ForDevelopment ¶
func (cb *ConfigBuilder) ForDevelopment() *ConfigBuilder
ForDevelopment applies development-friendly settings to existing configuration
func (*ConfigBuilder) ForHighPerformance ¶
func (cb *ConfigBuilder) ForHighPerformance() *ConfigBuilder
ForHighPerformance applies performance-optimized settings
func (*ConfigBuilder) ForProduction ¶
func (cb *ConfigBuilder) ForProduction() *ConfigBuilder
ForProduction applies production-ready settings to existing configuration
func (*ConfigBuilder) ForSecure ¶
func (cb *ConfigBuilder) ForSecure() *ConfigBuilder
ForSecure applies security-focused settings
func (*ConfigBuilder) Validate ¶
func (cb *ConfigBuilder) Validate() error
Validate validates all configurations in the builder
func (*ConfigBuilder) WithAPIKeyAuth ¶
func (cb *ConfigBuilder) WithAPIKeyAuth(headerName, prefix string) *ConfigBuilder
WithAPIKeyAuth configures API key authentication
func (*ConfigBuilder) WithAgent ¶
func (cb *ConfigBuilder) WithAgent(config *AgentConfig) *ConfigBuilder
WithAgent sets the agent configuration
func (*ConfigBuilder) WithAgentDescription ¶
func (cb *ConfigBuilder) WithAgentDescription(description string) *ConfigBuilder
WithAgentDescription sets the agent description
func (*ConfigBuilder) WithAgentName ¶
func (cb *ConfigBuilder) WithAgentName(name string) *ConfigBuilder
WithAgentName sets the agent name
func (*ConfigBuilder) WithAuthMethod ¶
func (cb *ConfigBuilder) WithAuthMethod(method AuthMethod) *ConfigBuilder
WithAuthMethod sets the primary authentication method
func (*ConfigBuilder) WithCORS ¶
func (cb *ConfigBuilder) WithCORS(allowedOrigins, allowedMethods, allowedHeaders []string) *ConfigBuilder
WithCORS configures CORS settings
func (*ConfigBuilder) WithCircuitBreaker ¶
func (cb *ConfigBuilder) WithCircuitBreaker(enabled bool, failureThreshold, successThreshold int, timeout time.Duration) *ConfigBuilder
WithCircuitBreaker configures circuit breaker behavior
func (*ConfigBuilder) WithHTTP ¶
func (cb *ConfigBuilder) WithHTTP(config *HttpConfig) *ConfigBuilder
WithHTTP sets the HTTP configuration
func (*ConfigBuilder) WithHTTP2 ¶
func (cb *ConfigBuilder) WithHTTP2(enabled, force bool) *ConfigBuilder
WithHTTP2 enables or disables HTTP/2
func (*ConfigBuilder) WithHTTPConnectionLimits ¶
func (cb *ConfigBuilder) WithHTTPConnectionLimits(maxIdle, maxIdlePerHost, maxPerHost int) *ConfigBuilder
WithHTTPConnectionLimits sets HTTP connection limits
func (*ConfigBuilder) WithHTTPTimeouts ¶
func (cb *ConfigBuilder) WithHTTPTimeouts(dial, request, response time.Duration) *ConfigBuilder
WithHTTPTimeouts sets common HTTP timeout values
func (*ConfigBuilder) WithInsecureTLS ¶
func (cb *ConfigBuilder) WithInsecureTLS() *ConfigBuilder
WithInsecureTLS enables insecure TLS (skip verification)
func (*ConfigBuilder) WithJWTAuth ¶
func (cb *ConfigBuilder) WithJWTAuth(signingMethod, secretKey string, accessTTL, refreshTTL time.Duration) *ConfigBuilder
WithJWTAuth configures JWT authentication
func (*ConfigBuilder) WithRateLimit ¶
func (cb *ConfigBuilder) WithRateLimit(requestsPerSecond float64, burstSize int) *ConfigBuilder
WithRateLimit configures rate limiting
func (*ConfigBuilder) WithResilience ¶
func (cb *ConfigBuilder) WithResilience(config *ResilienceConfig) *ConfigBuilder
WithResilience sets the resilience configuration
func (*ConfigBuilder) WithRetry ¶
func (cb *ConfigBuilder) WithRetry(maxAttempts int, baseDelay, maxDelay time.Duration) *ConfigBuilder
WithRetry configures retry behavior
func (*ConfigBuilder) WithSSE ¶
func (cb *ConfigBuilder) WithSSE(config *SSEClientConfig) *ConfigBuilder
WithSSE sets the SSE configuration
func (*ConfigBuilder) WithSSEBackoff ¶
func (cb *ConfigBuilder) WithSSEBackoff(initial, max time.Duration, multiplier float64) *ConfigBuilder
WithSSEBackoff configures SSE reconnection backoff
func (*ConfigBuilder) WithSecurity ¶
func (cb *ConfigBuilder) WithSecurity(config *SecurityConfig) *ConfigBuilder
WithSecurity sets the security configuration
func (*ConfigBuilder) WithTLS ¶
func (cb *ConfigBuilder) WithTLS(enabled bool, certFile, keyFile, caFile string) *ConfigBuilder
WithTLS configures TLS settings
type ConfigChangeEvent ¶
type ConfigChangeEvent struct {
Source string `json:"source"`
Path string `json:"path,omitempty"`
OldValue interface{} `json:"old_value"`
NewValue interface{} `json:"new_value"`
Timestamp time.Time `json:"timestamp"`
Version string `json:"version"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
ConfigChangeEvent represents a configuration change event.
type ConfigChangeListener ¶
type ConfigChangeListener func(ConfigChangeEvent)
ConfigChangeListener is called when configuration changes.
type ConfigFormat ¶
type ConfigFormat string
ConfigFormat represents configuration file formats.
const ( ConfigFormatJSON ConfigFormat = "json" ConfigFormatYAML ConfigFormat = "yaml" ConfigFormatTOML ConfigFormat = "toml" )
type ConfigMetrics ¶
type ConfigMetrics struct {
ConfigLoads int64 `json:"config_loads"`
ConfigReloads int64 `json:"config_reloads"`
ValidationErrors int64 `json:"validation_errors"`
SourceErrors int64 `json:"source_errors"`
WatcherErrors int64 `json:"watcher_errors"`
AverageLoadTime time.Duration `json:"average_load_time"`
LastLoadTime time.Time `json:"last_load_time"`
ActiveWatchers int32 `json:"active_watchers"`
}
ConfigMetrics contains metrics for configuration management.
type ConfigProfile ¶
type ConfigProfile string
ConfigProfile represents different pre-configured setups for common use cases
const ( // ProfileDevelopment provides settings optimized for development and testing ProfileDevelopment ConfigProfile = "development" // ProfileProduction provides settings optimized for production deployment ProfileProduction ConfigProfile = "production" // ProfileMinimal provides basic functionality with minimal configuration ProfileMinimal ConfigProfile = "minimal" )
type ConfigSchema ¶
type ConfigSchema struct {
Name string `json:"name" yaml:"name"`
Version string `json:"version" yaml:"version"`
Properties map[string]*PropertySpec `json:"properties" yaml:"properties"`
Required []string `json:"required" yaml:"required"`
Defaults map[string]interface{} `json:"defaults" yaml:"defaults"`
Validators []ConfigValidator `json:"-" yaml:"-"`
}
ConfigSchema defines validation rules for configuration.
func NewConfigSchema ¶
func NewConfigSchema(name, version string) *ConfigSchema
NewConfigSchema creates a new configuration schema.
func (*ConfigSchema) AddProperty ¶
func (cs *ConfigSchema) AddProperty(name string, spec *PropertySpec) *ConfigSchema
AddProperty adds a property specification to the schema.
func (*ConfigSchema) AddValidator ¶
func (cs *ConfigSchema) AddValidator(validator ConfigValidator) *ConfigSchema
AddValidator adds a custom validator to the schema.
type ConfigSource ¶
type ConfigSource interface {
// Load loads configuration data
Load(ctx context.Context) (map[string]interface{}, error)
// Watch watches for configuration changes
Watch(ctx context.Context, callback func(map[string]interface{})) error
// Name returns the name of the configuration source
Name() string
// Priority returns the priority of this source (higher = more important)
Priority() int
}
ConfigSource represents a source of configuration data.
type ConfigTemplate ¶
type ConfigTemplate struct {
Name string
Description string
Builder func() *ConfigBuilder
}
ConfigTemplate represents a reusable configuration template
func GetConfigTemplate ¶
func GetConfigTemplate(name string) (*ConfigTemplate, error)
GetConfigTemplate returns a specific configuration template by name
func GetConfigTemplates ¶
func GetConfigTemplates() []ConfigTemplate
GetConfigTemplates returns a list of predefined configuration templates
type ConfigValidator ¶
ConfigValidator is a function that validates configuration.
type ConfigWatcher ¶
type ConfigWatcher struct {
// contains filtered or unexported fields
}
ConfigWatcher watches configuration changes and triggers reloads.
type ConflictResolutionStrategy ¶
type ConflictResolutionStrategy string
ConflictResolutionStrategy defines available conflict resolution strategies.
const ( StrategyLastWriterWins ConflictResolutionStrategy = "last-writer-wins" StrategyFirstWriterWins ConflictResolutionStrategy = "first-writer-wins" StrategyMerge ConflictResolutionStrategy = "merge" StrategyCustom ConflictResolutionStrategy = "custom" // Compatibility aliases for constants used in other files ConflictResolutionLastWriterWins ConflictResolutionStrategy = "last-writer-wins" ConflictResolutionFirstWriterWins ConflictResolutionStrategy = "first-writer-wins" ConflictResolutionMerge ConflictResolutionStrategy = "merge" ConflictResolutionReject ConflictResolutionStrategy = "reject" )
type ConflictResolver ¶
type ConflictResolver interface {
ResolveConflict(local, remote interface{}, path string) (interface{}, error)
}
ConflictResolver handles state conflicts using various strategies.
type ConnectionPool ¶
type ConnectionPool struct {
// contains filtered or unexported fields
}
ConnectionPool manages HTTP connection pooling
func NewConnectionPool ¶
func NewConnectionPool(maxIdle int, idleTimeout time.Duration) *ConnectionPool
NewConnectionPool creates a new connection pool with the specified configuration
func (*ConnectionPool) Close ¶
func (cp *ConnectionPool) Close()
Close gracefully shuts down the connection pool
func (*ConnectionPool) Size ¶
func (cp *ConnectionPool) Size() int64
Size returns the total number of connections in the pool
type ConnectionPoolStats ¶
type ConnectionPoolStats struct {
TotalConnections int64 `json:"total_connections"`
ActiveConnections int64 `json:"active_connections"`
IdleConnections int64 `json:"idle_connections"`
ConnectionsReused int64 `json:"connections_reused"`
ConnectionsCreated int64 `json:"connections_created"`
AverageLifetime time.Duration `json:"average_lifetime"`
}
type Conversation ¶
type Conversation struct {
ID string `json:"id"`
Title string `json:"title,omitempty"`
Participants []string `json:"participants"`
Messages []string `json:"messages"` // Message IDs in order
StartTime time.Time `json:"start_time"`
LastActivity time.Time `json:"last_activity"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
ThreadCount int `json:"thread_count"`
}
Conversation represents a conversation context with multiple messages.
type DatabaseConfig ¶
type DropStrategy ¶
type DropStrategy int
DropStrategy defines which events to drop under backpressure.
const ( DropStrategyOldest DropStrategy = iota DropStrategyNewest DropStrategyPriority )
type EncryptedTokenData ¶
type EncryptedTokenData struct {
Nonce []byte `json:"nonce"`
Ciphertext []byte `json:"ciphertext"`
}
EncryptedTokenData represents encrypted token data
type EncryptionConfig ¶
type EncryptionConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
Algorithm string `json:"algorithm" yaml:"algorithm"`
KeyFile string `json:"key_file" yaml:"key_file"`
KeyRotationInterval time.Duration `json:"key_rotation_interval" yaml:"key_rotation_interval"`
}
func (*EncryptionConfig) Validate ¶
func (ec *EncryptionConfig) Validate() error
Validate validates EncryptionConfig
type EnvConfigSource ¶
type EnvConfigSource struct {
// contains filtered or unexported fields
}
Environment variable configuration source
func NewEnvConfigSource ¶
func NewEnvConfigSource(prefix string, priority int) *EnvConfigSource
NewEnvConfigSource creates an environment variable configuration source.
func (*EnvConfigSource) Load ¶
func (ecs *EnvConfigSource) Load(ctx context.Context) (map[string]interface{}, error)
func (*EnvConfigSource) Name ¶
func (ecs *EnvConfigSource) Name() string
func (*EnvConfigSource) Priority ¶
func (ecs *EnvConfigSource) Priority() int
type EventHandler ¶
EventHandler is a function type for handling specific event types.
type EventProcessingConfig ¶
type EventProcessingConfig struct {
BufferSize int `json:"buffer_size" yaml:"buffer_size"`
BatchSize int `json:"batch_size" yaml:"batch_size"`
Timeout time.Duration `json:"timeout" yaml:"timeout"`
EnableValidation bool `json:"enable_validation" yaml:"enable_validation"`
EnableMetrics bool `json:"enable_metrics" yaml:"enable_metrics"`
}
EventProcessingConfig contains configuration for event processing.
type EventProcessor ¶
type EventProcessor struct {
// contains filtered or unexported fields
}
EventProcessor provides sophisticated event processing capabilities for agents. It handles event routing, transformation, validation, streaming with backpressure, ordering, sequence management, and custom event handler registration.
Key features:
- High-performance event processing (>10,000 events/second)
- Configurable event handling strategies
- Support for custom event types
- Integration with validation system
- Event routing and dispatch
- Streaming event handling with backpressure
- Event ordering and sequence management
func NewEventProcessor ¶
func NewEventProcessor(config EventProcessingConfig) (*EventProcessor, error)
NewEventProcessor creates a new event processor with the given configuration.
func (*EventProcessor) Cleanup ¶
func (ep *EventProcessor) Cleanup() error
Cleanup releases resources.
func (*EventProcessor) GetMetrics ¶
func (ep *EventProcessor) GetMetrics() EventProcessorMetrics
GetMetrics returns current processing metrics.
func (*EventProcessor) IsHealthy ¶
func (ep *EventProcessor) IsHealthy() bool
IsHealthy returns the health status of the processor.
func (*EventProcessor) ProcessEvent ¶
func (ep *EventProcessor) ProcessEvent(ctx context.Context, event events.Event) ([]events.Event, error)
ProcessEvent processes a single event and returns response events.
func (*EventProcessor) RegisterHandler ¶
func (ep *EventProcessor) RegisterHandler(eventType events.EventType, handler EventHandler)
RegisterHandler registers an event handler for a specific event type.
func (*EventProcessor) SetDefaultHandler ¶
func (ep *EventProcessor) SetDefaultHandler(handler EventHandler)
SetDefaultHandler sets a default handler for unhandled event types.
type EventProcessorMetrics ¶
type EventProcessorMetrics struct {
EventsReceived int64 `json:"events_received"`
EventsProcessed int64 `json:"events_processed"`
EventsDropped int64 `json:"events_dropped"`
BatchesProcessed int64 `json:"batches_processed"`
AverageLatency time.Duration `json:"average_latency"`
ThroughputPerSec float64 `json:"throughput_per_sec"`
BackpressureEvents int64 `json:"backpressure_events"`
ValidationErrors int64 `json:"validation_errors"`
HandlerErrors int64 `json:"handler_errors"`
LastProcessedTime time.Time `json:"last_processed_time"`
}
EventProcessorMetrics contains performance metrics for the event processor.
type EventSequenceTracker ¶
type EventSequenceTracker struct {
// contains filtered or unexported fields
}
EventSequenceTracker tracks event sequences and ensures proper ordering.
type EvictionPolicy ¶
type EvictionPolicy int
EvictionPolicy defines how cache entries are evicted.
const ( EvictionPolicyLRU EvictionPolicy = iota EvictionPolicyLFU EvictionPolicyTTL )
type ExecutionStatus ¶
type ExecutionStatus string
ExecutionStatus represents the status of a tool execution.
const ( ExecutionStatusPending ExecutionStatus = "pending" ExecutionStatusRunning ExecutionStatus = "running" ExecutionStatusCompleted ExecutionStatus = "completed" ExecutionStatusFailed ExecutionStatus = "failed" ExecutionStatusCancelled ExecutionStatus = "cancelled" ExecutionStatusTimeout ExecutionStatus = "timeout" )
type FileConfigSource ¶
type FileConfigSource struct {
// contains filtered or unexported fields
}
File-based configuration source
func NewFileConfigSource ¶
func NewFileConfigSource(filePath string, format ConfigFormat, priority int) *FileConfigSource
NewFileConfigSource creates a file-based configuration source.
func (*FileConfigSource) Load ¶
func (fcs *FileConfigSource) Load(ctx context.Context) (map[string]interface{}, error)
func (*FileConfigSource) Name ¶
func (fcs *FileConfigSource) Name() string
func (*FileConfigSource) Priority ¶
func (fcs *FileConfigSource) Priority() int
type FileHistoryPersister ¶
type FileHistoryPersister struct {
// contains filtered or unexported fields
}
FileHistoryPersister is a simple file-based persistence implementation
func (*FileHistoryPersister) DeleteConversation ¶
func (fhp *FileHistoryPersister) DeleteConversation(conversationID string) error
func (*FileHistoryPersister) DeleteMessage ¶
func (fhp *FileHistoryPersister) DeleteMessage(messageID string) error
func (*FileHistoryPersister) DeleteThread ¶
func (fhp *FileHistoryPersister) DeleteThread(threadID string) error
func (*FileHistoryPersister) LoadAllMessages ¶
func (fhp *FileHistoryPersister) LoadAllMessages() ([]*StoredMessage, error)
func (*FileHistoryPersister) LoadConversation ¶
func (fhp *FileHistoryPersister) LoadConversation(conversationID string) (*Conversation, error)
func (*FileHistoryPersister) LoadMessage ¶
func (fhp *FileHistoryPersister) LoadMessage(messageID string) (*StoredMessage, error)
func (*FileHistoryPersister) LoadThread ¶
func (fhp *FileHistoryPersister) LoadThread(threadID string) (*Thread, error)
func (*FileHistoryPersister) SaveConversation ¶
func (fhp *FileHistoryPersister) SaveConversation(conversation *Conversation) error
func (*FileHistoryPersister) SaveMessage ¶
func (fhp *FileHistoryPersister) SaveMessage(message *StoredMessage) error
func (*FileHistoryPersister) SaveThread ¶
func (fhp *FileHistoryPersister) SaveThread(thread *Thread) error
type FileTokenStorage ¶
type FileTokenStorage struct {
// contains filtered or unexported fields
}
FileTokenStorage stores tokens in encrypted files
func NewFileTokenStorage ¶
func NewFileTokenStorage(config *TokenStorageConfig, logger *zap.Logger) (*FileTokenStorage, error)
NewFileTokenStorage creates a new file-based token storage
func (*FileTokenStorage) Cleanup ¶
func (fts *FileTokenStorage) Cleanup() error
Cleanup performs cleanup operations for file storage
func (*FileTokenStorage) CleanupExpiredTokens ¶
func (fts *FileTokenStorage) CleanupExpiredTokens() error
CleanupExpiredTokens removes expired tokens from file
func (*FileTokenStorage) GetToken ¶
func (fts *FileTokenStorage) GetToken(token string) (*TokenInfo, error)
GetToken retrieves a token from file
func (*FileTokenStorage) ListTokens ¶
func (fts *FileTokenStorage) ListTokens(userID string) ([]*TokenInfo, error)
ListTokens returns all tokens for a user from file
func (*FileTokenStorage) RevokeToken ¶
func (fts *FileTokenStorage) RevokeToken(token string) error
RevokeToken removes a token from file
func (*FileTokenStorage) StoreToken ¶
func (fts *FileTokenStorage) StoreToken(token string, info *TokenInfo) error
StoreToken stores a token in file
type FirstWriterWinsResolver ¶
type FirstWriterWinsResolver struct{}
func (*FirstWriterWinsResolver) ResolveConflict ¶
func (r *FirstWriterWinsResolver) ResolveConflict(local, remote interface{}, path string) (interface{}, error)
type HMACConfig ¶
type HMACConfig struct {
SecretKey string `json:"secret_key" yaml:"secret_key"`
Algorithm string `json:"algorithm" yaml:"algorithm"`
HeaderName string `json:"header_name" yaml:"header_name"`
TimestampHeader string `json:"timestamp_header" yaml:"timestamp_header"`
NonceHeader string `json:"nonce_header" yaml:"nonce_header"`
MaxClockSkew time.Duration `json:"max_clock_skew" yaml:"max_clock_skew"`
IncludeHeaders []string `json:"include_headers" yaml:"include_headers"`
}
HMACConfig contains HMAC signature configuration
type HMACManager ¶
type HMACManager struct {
// contains filtered or unexported fields
}
HMACManager handles HMAC signature-based authentication
func NewHMACManager ¶
func NewHMACManager(config *HMACConfig, logger *zap.Logger) (*HMACManager, error)
NewHMACManager creates a new HMAC manager
func (*HMACManager) AddSecretKey ¶
func (hm *HMACManager) AddSecretKey(keyID, secretKey string)
AddSecretKey adds a secret key for a given key ID
func (*HMACManager) Cleanup ¶
func (hm *HMACManager) Cleanup() error
Cleanup performs cleanup operations
func (*HMACManager) GetSignatureInfo ¶
func (hm *HMACManager) GetSignatureInfo(req *http.Request) (*HMACSignatureInfo, error)
GetSignatureInfo extracts signature information from a request for debugging
func (*HMACManager) ListKeyIDs ¶
func (hm *HMACManager) ListKeyIDs() []string
ListKeyIDs returns a list of configured key IDs
func (*HMACManager) RemoveSecretKey ¶
func (hm *HMACManager) RemoveSecretKey(keyID string)
RemoveSecretKey removes a secret key
func (*HMACManager) SignRequest ¶
func (hm *HMACManager) SignRequest(req *http.Request, keyID, secretKey string) error
SignRequest signs an HTTP request with HMAC
func (*HMACManager) ValidateSignature ¶
func (hm *HMACManager) ValidateSignature(req *http.Request) (*UserInfo, error)
ValidateSignature validates an HMAC signature from an HTTP request
func (*HMACManager) VerifySignatureComponents ¶
func (hm *HMACManager) VerifySignatureComponents(req *http.Request) map[string]interface{}
VerifySignatureComponents verifies individual components of a signature
type HMACSignatureInfo ¶
type HMACSignatureInfo struct {
Signature string `json:"signature"`
KeyID string `json:"key_id"`
Timestamp time.Time `json:"timestamp"`
Nonce string `json:"nonce"`
Headers map[string]string `json:"headers"`
Method string `json:"method"`
Path string `json:"path"`
Body string `json:"body,omitempty"`
}
HMACSignatureInfo contains information about an HMAC signature
type HTTPMetrics ¶
type HTTPMetrics struct {
// Request metrics
TotalRequests int64 `json:"total_requests"`
SuccessfulRequests int64 `json:"successful_requests"`
FailedRequests int64 `json:"failed_requests"`
// Timing metrics
TotalDuration time.Duration `json:"total_duration"`
AverageDuration time.Duration `json:"average_duration"`
MinDuration time.Duration `json:"min_duration"`
MaxDuration time.Duration `json:"max_duration"`
// Data transfer
BytesSent int64 `json:"bytes_sent"`
BytesReceived int64 `json:"bytes_received"`
// Protocol statistics
HTTP1Requests int64 `json:"http1_requests"`
HTTP2Requests int64 `json:"http2_requests"`
// Error breakdown
ConnectionErrors int64 `json:"connection_errors"`
TimeoutErrors int64 `json:"timeout_errors"`
ProtocolErrors int64 `json:"protocol_errors"`
// Compression stats
CompressionRatio float64 `json:"compression_ratio"`
CompressedRequests int64 `json:"compressed_requests"`
// contains filtered or unexported fields
}
HTTPMetrics collects detailed HTTP metrics
type HTTPTransport ¶
type HTTPTransport struct {
// contains filtered or unexported fields
}
HTTPTransport implements a high-performance HTTP transport layer
func NewHTTPTransport ¶
func NewHTTPTransport(config *HTTPTransportConfig) (*HTTPTransport, error)
NewHTTPTransport creates a new HTTP transport instance
func (*HTTPTransport) GetConnectionPoolStats ¶
func (h *HTTPTransport) GetConnectionPoolStats() ConnectionPoolStats
func (*HTTPTransport) GetMetrics ¶
func (h *HTTPTransport) GetMetrics() *HTTPMetrics
Public API methods
func (*HTTPTransport) GetPerformanceStats ¶
func (h *HTTPTransport) GetPerformanceStats() *PerformanceStats
func (*HTTPTransport) GetProtocolVersion ¶
func (h *HTTPTransport) GetProtocolVersion() string
func (*HTTPTransport) IsHealthy ¶
func (h *HTTPTransport) IsHealthy() bool
func (*HTTPTransport) SendRequest ¶
func (h *HTTPTransport) SendRequest(ctx context.Context, method, path string, body []byte) (*http.Response, error)
SendRequest sends an HTTP request with full feature support
type HTTPTransportConfig ¶
type HTTPTransportConfig struct {
// Core connection settings
BaseURL string `json:"base_url" yaml:"base_url"`
Headers map[string]string `json:"headers" yaml:"headers"`
AuthToken string `json:"auth_token" yaml:"auth_token"`
UserAgent string `json:"user_agent" yaml:"user_agent"`
// Protocol settings
ForceHTTP1 bool `json:"force_http1" yaml:"force_http1"`
EnableHTTP2 bool `json:"enable_http2" yaml:"enable_http2"`
// Connection pooling
MaxIdleConns int `json:"max_idle_conns" yaml:"max_idle_conns"`
MaxIdleConnsPerHost int `json:"max_idle_conns_per_host" yaml:"max_idle_conns_per_host"`
MaxConnsPerHost int `json:"max_conns_per_host" yaml:"max_conns_per_host"`
IdleConnTimeout time.Duration `json:"idle_conn_timeout" yaml:"idle_conn_timeout"`
// Timeouts
ConnectTimeout time.Duration `json:"connect_timeout" yaml:"connect_timeout"`
RequestTimeout time.Duration `json:"request_timeout" yaml:"request_timeout"`
ResponseTimeout time.Duration `json:"response_timeout" yaml:"response_timeout"`
KeepAliveTimeout time.Duration `json:"keep_alive_timeout" yaml:"keep_alive_timeout"`
TLSHandshakeTimeout time.Duration `json:"tls_handshake_timeout" yaml:"tls_handshake_timeout"`
// Retry and resilience
MaxRetries int `json:"max_retries" yaml:"max_retries"`
BaseRetryDelay time.Duration `json:"base_retry_delay" yaml:"base_retry_delay"`
MaxRetryDelay time.Duration `json:"max_retry_delay" yaml:"max_retry_delay"`
RetryJitter bool `json:"retry_jitter" yaml:"retry_jitter"`
CircuitBreakerConfig *CircuitBreakerConfig `json:"circuit_breaker" yaml:"circuit_breaker"`
// Security
TLSConfig *tls.Config `json:"-" yaml:"-"`
InsecureSkipVerify bool `json:"insecure_skip_verify" yaml:"insecure_skip_verify"`
SecurityHeaders map[string]string `json:"security_headers" yaml:"security_headers"`
// Performance
EnableCompression bool `json:"enable_compression" yaml:"enable_compression"`
CompressionLevel int `json:"compression_level" yaml:"compression_level"`
BufferSize int `json:"buffer_size" yaml:"buffer_size"`
// Monitoring
EnableMetrics bool `json:"enable_metrics" yaml:"enable_metrics"`
MetricsPrefix string `json:"metrics_prefix" yaml:"metrics_prefix"`
}
HTTPTransportConfig holds the configuration for HTTP transport
func DefaultHTTPTransportConfig ¶
func DefaultHTTPTransportConfig() *HTTPTransportConfig
DefaultHTTPTransportConfig returns a sensible default configuration
type HealthCheckConfig ¶
type HealthCheckConfig struct {
// Enabled indicates if health checks are active
Enabled bool `json:"enabled"`
// Interval is the health check interval
Interval time.Duration `json:"interval"`
// Timeout is the health check timeout
Timeout time.Duration `json:"timeout"`
// FailureThreshold is failures needed to mark unhealthy
FailureThreshold int `json:"failure_threshold"`
// RecoveryThreshold is successes needed to mark healthy
RecoveryThreshold int `json:"recovery_threshold"`
// Endpoint is the health check endpoint
Endpoint string `json:"endpoint"`
// ExpectedStatusCodes are the expected healthy status codes
ExpectedStatusCodes []int `json:"expected_status_codes"`
}
HealthCheckConfig configures health monitoring and recovery
type HealthChecker ¶
type HealthChecker struct {
// contains filtered or unexported fields
}
HealthChecker monitors service health and implements recovery mechanisms
func NewHealthChecker ¶
func NewHealthChecker(config HealthCheckConfig) *HealthChecker
NewHealthChecker creates a new health checker
func (*HealthChecker) GetMetrics ¶
func (hc *HealthChecker) GetMetrics() map[string]interface{}
GetMetrics returns health check metrics
func (*HealthChecker) GetStatus ¶
func (hc *HealthChecker) GetStatus() HealthStatus
GetStatus returns the current health status
func (*HealthChecker) IsHealthy ¶
func (hc *HealthChecker) IsHealthy() bool
IsHealthy returns true if the service is healthy
type HealthStatus ¶
type HealthStatus int
HealthStatus represents the health status of a service
const ( // HealthStatusUnknown indicates health status is unknown HealthStatusUnknown HealthStatus = iota // HealthStatusHealthy indicates service is healthy HealthStatusHealthy // HealthStatusUnhealthy indicates service is unhealthy HealthStatusUnhealthy // HealthStatusDegraded indicates service is degraded HealthStatusDegraded )
func (HealthStatus) String ¶
func (s HealthStatus) String() string
String returns the string representation of health status
type HistoryConfig ¶
type HistoryConfig struct {
MaxMessages int `json:"max_messages" yaml:"max_messages"`
Retention time.Duration `json:"retention" yaml:"retention"`
EnablePersistence bool `json:"enable_persistence" yaml:"enable_persistence"`
EnableCompression bool `json:"enable_compression" yaml:"enable_compression"`
}
HistoryConfig contains configuration for message history management.
type HistoryMemoryManager ¶
type HistoryMemoryManager struct {
// contains filtered or unexported fields
}
HistoryMemoryManager manages memory usage for large histories.
type HistoryMetrics ¶
type HistoryMetrics struct {
TotalMessages int64 `json:"total_messages"`
TotalConversations int64 `json:"total_conversations"`
TotalThreads int64 `json:"total_threads"`
MessagesAdded int64 `json:"messages_added"`
MessagesDeleted int64 `json:"messages_deleted"`
SearchQueries int64 `json:"search_queries"`
AverageSearchTime time.Duration `json:"average_search_time"`
MemoryUsage int64 `json:"memory_usage"`
CompressionRatio float64 `json:"compression_ratio"`
PersistenceOps int64 `json:"persistence_ops"`
LastCleanupTime time.Time `json:"last_cleanup_time"`
}
HistoryMetrics contains metrics for the history manager.
type HistoryPersister ¶
type HistoryPersister interface {
SaveMessage(message *StoredMessage) error
LoadMessage(messageID string) (*StoredMessage, error)
SaveConversation(conversation *Conversation) error
LoadConversation(conversationID string) (*Conversation, error)
SaveThread(thread *Thread) error
LoadThread(threadID string) (*Thread, error)
DeleteMessage(messageID string) error
DeleteConversation(conversationID string) error
DeleteThread(threadID string) error
LoadAllMessages() ([]*StoredMessage, error)
}
HistoryPersister handles persistence of message history.
type HttpAgent ¶
type HttpAgent struct {
*BaseAgent
// contains filtered or unexported fields
}
HttpAgent provides HTTP-specific functionality by embedding BaseAgent. It implements the Agent interface through BaseAgent and adds HTTP client management, connection pooling, and protocol support for HTTP/1.1 and HTTP/2.
func NewHttpAgent ¶
func NewHttpAgent(name, description string, httpConfig *HttpConfig) (*HttpAgent, error)
NewHttpAgent creates a new HTTP agent with the specified configuration.
func (*HttpAgent) GetHttpMetrics ¶
func (h *HttpAgent) GetHttpMetrics() *HttpMetrics
GetHttpMetrics returns HTTP-specific metrics.
func (*HttpAgent) HttpClient ¶
HttpClient returns the configured HTTP client.
func (*HttpAgent) Initialize ¶
func (h *HttpAgent) Initialize(ctx context.Context, config *AgentConfig) error
Initialize prepares the HTTP agent with the given configuration.
func (*HttpAgent) SendRequest ¶
SendRequest sends an HTTP request using the configured client.
type HttpConfig ¶
type HttpConfig struct {
// Protocol settings
ProtocolVersion HttpProtocolVersion `json:"protocol_version" yaml:"protocol_version"`
EnableHTTP2 bool `json:"enable_http2" yaml:"enable_http2"`
ForceHTTP2 bool `json:"force_http2" yaml:"force_http2"`
// Connection settings
MaxIdleConns int `json:"max_idle_conns" yaml:"max_idle_conns"`
MaxIdleConnsPerHost int `json:"max_idle_conns_per_host" yaml:"max_idle_conns_per_host"`
MaxConnsPerHost int `json:"max_conns_per_host" yaml:"max_conns_per_host"`
IdleConnTimeout time.Duration `json:"idle_conn_timeout" yaml:"idle_conn_timeout"`
KeepAlive time.Duration `json:"keep_alive" yaml:"keep_alive"`
// Timeout settings
DialTimeout time.Duration `json:"dial_timeout" yaml:"dial_timeout"`
RequestTimeout time.Duration `json:"request_timeout" yaml:"request_timeout"`
ResponseTimeout time.Duration `json:"response_timeout" yaml:"response_timeout"`
TLSHandshakeTimeout time.Duration `json:"tls_handshake_timeout" yaml:"tls_handshake_timeout"`
// TLS settings
TLSConfig *tls.Config `json:"-" yaml:"-"` // Not serializable
InsecureSkipVerify bool `json:"insecure_skip_verify" yaml:"insecure_skip_verify"`
// Advanced settings
DisableCompression bool `json:"disable_compression" yaml:"disable_compression"`
DisableKeepAlives bool `json:"disable_keep_alives" yaml:"disable_keep_alives"`
UserAgent string `json:"user_agent" yaml:"user_agent"`
MaxResponseBodySize int64 `json:"max_response_body_size" yaml:"max_response_body_size"`
// Circuit breaker settings
EnableCircuitBreaker bool `json:"enable_circuit_breaker" yaml:"enable_circuit_breaker"`
CircuitBreakerConfig *CircuitBreakerConfig `json:"circuit_breaker" yaml:"circuit_breaker"`
}
HttpConfig contains HTTP-specific configuration options.
func DefaultHttpConfig ¶
func DefaultHttpConfig() *HttpConfig
DefaultHttpConfig returns a default HTTP configuration.
func QuickHTTPConfig ¶
func QuickHTTPConfig(timeout time.Duration) *HttpConfig
QuickHTTPConfig creates a simple HTTP configuration with sensible defaults
func (*HttpConfig) Validate ¶
func (hc *HttpConfig) Validate() error
Validate validates the HttpConfig and returns detailed errors
type HttpMetrics ¶
type HttpMetrics struct {
RequestCount int64 `json:"request_count"`
ResponseCount int64 `json:"response_count"`
ErrorCount int64 `json:"error_count"`
ActiveConnections int64 `json:"active_connections"`
PooledConnections int64 `json:"pooled_connections"`
AverageResponseTime time.Duration `json:"average_response_time"`
TotalBytesReceived int64 `json:"total_bytes_received"`
TotalBytesSent int64 `json:"total_bytes_sent"`
}
HttpMetrics contains HTTP-specific metrics.
type HttpProtocolVersion ¶
type HttpProtocolVersion string
HttpProtocolVersion represents the HTTP protocol version to use.
const ( HttpProtocolVersionAuto HttpProtocolVersion = "auto" HttpProtocolVersion1_1 HttpProtocolVersion = "1.1" HttpProtocolVersion2 HttpProtocolVersion = "2" )
type JWTConfig ¶
type JWTConfig struct {
// Signing configuration
SigningMethod string `json:"signing_method" yaml:"signing_method"`
SecretKey string `json:"secret_key,omitempty" yaml:"secret_key,omitempty"`
PrivateKeyPath string `json:"private_key_path,omitempty" yaml:"private_key_path,omitempty"`
PublicKeyPath string `json:"public_key_path,omitempty" yaml:"public_key_path,omitempty"`
// Token lifecycle
AccessTokenTTL time.Duration `json:"access_token_ttl" yaml:"access_token_ttl"`
RefreshTokenTTL time.Duration `json:"refresh_token_ttl" yaml:"refresh_token_ttl"`
AutoRefresh bool `json:"auto_refresh" yaml:"auto_refresh"`
RefreshThreshold time.Duration `json:"refresh_threshold" yaml:"refresh_threshold"`
// Validation settings
Issuer string `json:"issuer" yaml:"issuer"`
Audience []string `json:"audience" yaml:"audience"`
Subject string `json:"subject" yaml:"subject"`
LeewayTime time.Duration `json:"leeway_time" yaml:"leeway_time"`
// Claims configuration
CustomClaims map[string]interface{} `json:"custom_claims,omitempty" yaml:"custom_claims,omitempty"`
}
JWTConfig contains JWT-specific configuration
func QuickJWTConfig ¶
QuickJWTConfig creates a simple JWT configuration with HMAC-SHA256
type JWTManager ¶
type JWTManager struct {
// contains filtered or unexported fields
}
JWTManager handles JWT token generation, validation, and refresh
func NewJWTManager ¶
func NewJWTManager(config *JWTConfig, logger *zap.Logger) (*JWTManager, error)
NewJWTManager creates a new JWT manager
func (*JWTManager) BlacklistToken ¶
func (jm *JWTManager) BlacklistToken(tokenString string) error
BlacklistToken adds a token to the blacklist
func (*JWTManager) Cleanup ¶
func (jm *JWTManager) Cleanup() error
Cleanup performs cleanup operations
func (*JWTManager) GenerateRefreshToken ¶
GenerateRefreshToken generates a refresh token
func (*JWTManager) GenerateToken ¶
GenerateToken generates a new JWT token
func (*JWTManager) GetTokenInfo ¶
func (jm *JWTManager) GetTokenInfo(tokenString string) (*TokenInfo, error)
GetTokenInfo extracts information from a token without validating it
func (*JWTManager) RefreshAccessToken ¶
func (jm *JWTManager) RefreshAccessToken(refreshTokenString string) (string, error)
RefreshAccessToken refreshes an access token using a refresh token
func (*JWTManager) ShouldRefresh ¶
func (jm *JWTManager) ShouldRefresh(tokenInfo *TokenInfo) bool
ShouldRefresh checks if a token should be refreshed based on configuration
func (*JWTManager) ValidateRefreshToken ¶
func (jm *JWTManager) ValidateRefreshToken(tokenString string) (jwt.MapClaims, error)
ValidateRefreshToken validates a refresh token
func (*JWTManager) ValidateToken ¶
func (jm *JWTManager) ValidateToken(tokenString string) (jwt.MapClaims, error)
ValidateToken validates and parses a JWT token
type KeepAliveManager ¶
type KeepAliveManager struct {
// contains filtered or unexported fields
}
KeepAliveManager handles connection keep-alive
type LastWriterWinsResolver ¶
type LastWriterWinsResolver struct{}
func (*LastWriterWinsResolver) ResolveConflict ¶
func (r *LastWriterWinsResolver) ResolveConflict(local, remote interface{}, path string) (interface{}, error)
type LifecycleManager ¶
type LifecycleManager interface {
// Initialize prepares the agent with the given configuration.
// The agent must be in an uninitialized state for this to succeed.
Initialize(ctx context.Context, config *AgentConfig) error
// Start begins the agent's operation.
// The agent must be initialized or stopped for this to succeed.
Start(ctx context.Context) error
// Stop gracefully shuts down the agent.
// The agent must be running for this to succeed.
Stop(ctx context.Context) error
// Cleanup releases all resources held by the agent.
// This can be called from any state and should be idempotent.
Cleanup() error
}
LifecycleManager handles agent lifecycle operations including initialization, startup, shutdown, and cleanup. This interface follows the single responsibility principle by focusing only on the agent's lifecycle state transitions.
type LogRotator ¶
type LogRotator struct {
// contains filtered or unexported fields
}
LogRotator handles log file rotation
type MemoryTokenStorage ¶
type MemoryTokenStorage struct {
// contains filtered or unexported fields
}
MemoryTokenStorage stores tokens in memory
func NewMemoryTokenStorage ¶
func NewMemoryTokenStorage(config *TokenStorageConfig, logger *zap.Logger) (*MemoryTokenStorage, error)
NewMemoryTokenStorage creates a new memory-based token storage
func (*MemoryTokenStorage) Cleanup ¶
func (mts *MemoryTokenStorage) Cleanup() error
Cleanup performs cleanup operations for memory storage
func (*MemoryTokenStorage) CleanupExpiredTokens ¶
func (mts *MemoryTokenStorage) CleanupExpiredTokens() error
CleanupExpiredTokens removes expired tokens from memory
func (*MemoryTokenStorage) GetToken ¶
func (mts *MemoryTokenStorage) GetToken(token string) (*TokenInfo, error)
GetToken retrieves a token from memory
func (*MemoryTokenStorage) ListTokens ¶
func (mts *MemoryTokenStorage) ListTokens(userID string) ([]*TokenInfo, error)
ListTokens returns all tokens for a user
func (*MemoryTokenStorage) RevokeToken ¶
func (mts *MemoryTokenStorage) RevokeToken(token string) error
RevokeToken removes a token from memory
func (*MemoryTokenStorage) StoreToken ¶
func (mts *MemoryTokenStorage) StoreToken(token string, info *TokenInfo) error
StoreToken stores a token in memory
type MergeResolver ¶
type MergeResolver struct{}
func (*MergeResolver) ResolveConflict ¶
func (r *MergeResolver) ResolveConflict(local, remote interface{}, path string) (interface{}, error)
type MessageHistoryManager ¶
type MessageHistoryManager struct {
// contains filtered or unexported fields
}
MessageHistoryManager provides advanced message history management with conversation context tracking, message threading, history persistence, memory-efficient storage, search and filtering capabilities, and performance optimization for large histories.
Key features:
- Integration with message system
- Configurable retention policies
- Thread-safe operations
- Performance optimization for large histories
- Conversation context tracking
- Message threading and relationships
- History search and filtering capabilities
- Memory-efficient history storage
func NewMessageHistoryManager ¶
func NewMessageHistoryManager(config HistoryConfig) (*MessageHistoryManager, error)
NewMessageHistoryManager creates a new message history manager.
func (*MessageHistoryManager) AddMessage ¶
func (mhm *MessageHistoryManager) AddMessage(ctx context.Context, message *messages.Message, conversationID string) error
AddMessage adds a message to the history.
func (*MessageHistoryManager) Cleanup ¶
func (mhm *MessageHistoryManager) Cleanup() error
Cleanup releases all resources.
func (*MessageHistoryManager) DeleteMessage ¶
func (mhm *MessageHistoryManager) DeleteMessage(ctx context.Context, messageID string) error
DeleteMessage deletes a message from history.
func (*MessageHistoryManager) GetConversation ¶
func (mhm *MessageHistoryManager) GetConversation(ctx context.Context, conversationID string) (*Conversation, error)
GetConversation retrieves a conversation by ID.
func (*MessageHistoryManager) GetConversationMessages ¶
func (mhm *MessageHistoryManager) GetConversationMessages(ctx context.Context, conversationID string) ([]*messages.Message, error)
GetConversationMessages retrieves all messages in a conversation.
func (*MessageHistoryManager) GetMessage ¶
func (mhm *MessageHistoryManager) GetMessage(ctx context.Context, messageID string) (*messages.Message, error)
GetMessage retrieves a message by ID.
func (*MessageHistoryManager) GetMetrics ¶
func (mhm *MessageHistoryManager) GetMetrics() HistoryMetrics
GetMetrics returns current history metrics.
func (*MessageHistoryManager) IsHealthy ¶
func (mhm *MessageHistoryManager) IsHealthy() bool
IsHealthy returns the health status.
func (*MessageHistoryManager) SearchMessages ¶
func (mhm *MessageHistoryManager) SearchMessages(ctx context.Context, query MessageQuery) ([]*messages.Message, error)
SearchMessages searches for messages based on query criteria.
type MessageIndices ¶
type MessageIndices struct {
// contains filtered or unexported fields
}
MessageIndices provides efficient indexing for message search.
type MessageQuery ¶
type MessageQuery struct {
ConversationID string `json:"conversation_id,omitempty"`
ThreadID string `json:"thread_id,omitempty"`
Sender string `json:"sender,omitempty"`
Content string `json:"content,omitempty"`
TimeRange *TimeRange `json:"time_range,omitempty"`
MessageType string `json:"message_type,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
Limit int `json:"limit,omitempty"`
Offset int `json:"offset,omitempty"`
SortBy string `json:"sort_by,omitempty"`
SortOrder string `json:"sort_order,omitempty"`
}
MessageQuery represents a query for searching messages.
type MetricsCollector ¶
type MetricsCollector struct {
// contains filtered or unexported fields
}
MetricsCollector collects and manages resilience metrics
func NewMetricsCollector ¶
func NewMetricsCollector(config MetricsConfig) *MetricsCollector
NewMetricsCollector creates a new metrics collector
func (*MetricsCollector) GetMetrics ¶
func (mc *MetricsCollector) GetMetrics() map[string]interface{}
GetMetrics returns all collected metrics
func (*MetricsCollector) RecordBulkheadReject ¶
func (mc *MetricsCollector) RecordBulkheadReject()
RecordBulkheadReject records a bulkhead rejection
func (*MetricsCollector) RecordCircuitBreakerReject ¶
func (mc *MetricsCollector) RecordCircuitBreakerReject()
RecordCircuitBreakerReject records a circuit breaker rejection
func (*MetricsCollector) RecordFailure ¶
func (mc *MetricsCollector) RecordFailure(duration time.Duration)
RecordFailure records a failed operation
func (*MetricsCollector) RecordRateLimitReject ¶
func (mc *MetricsCollector) RecordRateLimitReject()
RecordRateLimitReject records a rate limit rejection
func (*MetricsCollector) RecordSuccess ¶
func (mc *MetricsCollector) RecordSuccess(duration time.Duration)
RecordSuccess records a successful operation
type MetricsConfig ¶
type MetricsConfig struct {
// Enabled indicates if metrics collection is active
Enabled bool `json:"enabled"`
// CollectionInterval is the metrics collection interval
CollectionInterval time.Duration `json:"collection_interval"`
// RetentionPeriod is how long to retain metrics
RetentionPeriod time.Duration `json:"retention_period"`
// HistogramBuckets defines histogram bucket boundaries
HistogramBuckets []float64 `json:"histogram_buckets"`
// EnableDetailedMetrics enables detailed metric collection
EnableDetailedMetrics bool `json:"enable_detailed_metrics"`
}
MetricsConfig configures metrics collection and monitoring
type Middleware ¶
type Middleware interface {
// ProcessRequest is called before sending the request
ProcessRequest(ctx context.Context, req *http.Request, correlation *RequestCorrelation) error
// ProcessResponse is called after receiving the response
ProcessResponse(ctx context.Context, resp *http.Response, correlation *RequestCorrelation) error
// HandleError is called when an error occurs during request processing
HandleError(ctx context.Context, err error, correlation *RequestCorrelation) error
}
Middleware defines the interface for request/response middleware.
type NetworkPolicy ¶
type NetworkPolicy struct {
AllowOutbound bool `json:"allow_outbound"`
AllowedHosts []string `json:"allowed_hosts"`
BlockedHosts []string `json:"blocked_hosts"`
AllowedPorts []int `json:"allowed_ports"`
}
NetworkPolicy defines network access restrictions.
type PasswordPolicy ¶
type PasswordPolicy struct {
MinLength int `json:"min_length" yaml:"min_length"`
RequireUppercase bool `json:"require_uppercase" yaml:"require_uppercase"`
RequireLowercase bool `json:"require_lowercase" yaml:"require_lowercase"`
RequireNumbers bool `json:"require_numbers" yaml:"require_numbers"`
RequireSpecialChars bool `json:"require_special_chars" yaml:"require_special_chars"`
MaxAge time.Duration `json:"max_age" yaml:"max_age"`
}
Supporting configuration types
type PerformanceStats ¶
type PerformanceStats struct {
// Connection performance
ConnectionSetupTime time.Duration `json:"connection_setup_time"`
TLSHandshakeTime time.Duration `json:"tls_handshake_time"`
DNSLookupTime time.Duration `json:"dns_lookup_time"`
// Request performance
TimeToFirstByte time.Duration `json:"time_to_first_byte"`
ContentDownloadTime time.Duration `json:"content_download_time"`
// Throughput
RequestsPerSecond float64 `json:"requests_per_second"`
BytesPerSecond float64 `json:"bytes_per_second"`
// Resource utilization
GoroutineCount int `json:"goroutine_count"`
MemoryUsage int64 `json:"memory_usage"`
// contains filtered or unexported fields
}
PerformanceStats tracks performance characteristics
type PropertyConstraints ¶
type PropertyConstraints struct {
Min *float64 `json:"min" yaml:"min"`
Max *float64 `json:"max" yaml:"max"`
MinLength *int `json:"min_length" yaml:"min_length"`
MaxLength *int `json:"max_length" yaml:"max_length"`
Pattern string `json:"pattern" yaml:"pattern"`
Enum []interface{} `json:"enum" yaml:"enum"`
Format string `json:"format" yaml:"format"`
}
PropertyConstraints defines constraints for a configuration property.
type PropertySpec ¶
type PropertySpec struct {
Type string `json:"type" yaml:"type"`
Description string `json:"description" yaml:"description"`
Default interface{} `json:"default" yaml:"default"`
Required bool `json:"required" yaml:"required"`
Constraints *PropertyConstraints `json:"constraints" yaml:"constraints"`
EnvVar string `json:"env_var" yaml:"env_var"`
Sensitive bool `json:"sensitive" yaml:"sensitive"`
}
PropertySpec defines a configuration property specification.
func NewPropertySpec ¶
func NewPropertySpec(propType, description string) *PropertySpec
NewPropertySpec creates a new property specification.
func (*PropertySpec) WithDefault ¶
func (ps *PropertySpec) WithDefault(value interface{}) *PropertySpec
WithDefault sets the default value for the property.
func (*PropertySpec) WithEnum ¶
func (ps *PropertySpec) WithEnum(values ...interface{}) *PropertySpec
WithEnum sets enum constraints for the property.
func (*PropertySpec) WithEnvVar ¶
func (ps *PropertySpec) WithEnvVar(envVar string) *PropertySpec
WithEnvVar sets the environment variable name for the property.
func (*PropertySpec) WithLength ¶
func (ps *PropertySpec) WithLength(minLength, maxLength int) *PropertySpec
WithLength sets length constraints for string/array properties.
func (*PropertySpec) WithMinMax ¶
func (ps *PropertySpec) WithMinMax(min, max float64) *PropertySpec
WithMinMax sets min/max constraints for numeric properties.
func (*PropertySpec) WithRequired ¶
func (ps *PropertySpec) WithRequired(required bool) *PropertySpec
WithRequired marks the property as required.
func (*PropertySpec) WithSensitive ¶
func (ps *PropertySpec) WithSensitive(sensitive bool) *PropertySpec
WithSensitive marks the property as sensitive (for logging/debugging).
type RateLimitConfig ¶
type RateLimitConfig struct {
// Enabled indicates if rate limiting is active
Enabled bool `json:"enabled"`
// RequestsPerSecond is the maximum requests per second
RequestsPerSecond float64 `json:"requests_per_second"`
// BurstSize is the maximum burst of requests allowed
BurstSize int `json:"burst_size"`
// WindowSize is the time window for rate calculation
WindowSize time.Duration `json:"window_size"`
// ThrottleDelay is the delay when throttling is applied
ThrottleDelay time.Duration `json:"throttle_delay"`
}
RateLimitConfig configures rate limiting and throttling
func QuickRateLimitConfig ¶
func QuickRateLimitConfig(requestsPerSecond float64, burstSize int) *RateLimitConfig
QuickRateLimitConfig creates a rate limiting configuration
func (*RateLimitConfig) Validate ¶
func (rlc *RateLimitConfig) Validate() error
Validate validates RateLimitConfig
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter implements a token bucket rate limiter
func NewRateLimiter ¶
func NewRateLimiter(rate, burst int) *RateLimiter
NewRateLimiter creates a new rate limiter
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow() bool
Allow checks if a request is allowed under the rate limit
func (*RateLimiter) SetBurst ¶
func (rl *RateLimiter) SetBurst(burst int)
SetBurst updates the burst size
func (*RateLimiter) SetRate ¶
func (rl *RateLimiter) SetRate(rate int)
SetRate updates the rate limit
func (*RateLimiter) Tokens ¶
func (rl *RateLimiter) Tokens() int
Tokens returns the current number of available tokens
type RedisConfig ¶
type RemoteConfigSource ¶
type RemoteConfigSource struct {
// contains filtered or unexported fields
}
Remote configuration source (placeholder)
type RequestCorrelation ¶
type RequestCorrelation struct {
ID string
Method string
URL string
StartTime time.Time
Headers http.Header
UserAgent string
RemoteAddr string
TraceSpan trace.Span
Context context.Context
Retries int
Metadata map[string]interface{}
}
RequestCorrelation tracks request metadata and timing.
type RequestManager ¶
type RequestManager struct {
// contains filtered or unexported fields
}
RequestManager handles HTTP request construction, validation, and response processing with comprehensive error handling, metrics, and middleware support.
func NewRequestManager ¶
func NewRequestManager(config RequestManagerConfig) (*RequestManager, error)
NewRequestManager creates a new RequestManager with the specified configuration.
func (*RequestManager) AddMiddleware ¶
func (rm *RequestManager) AddMiddleware(middleware Middleware)
AddMiddleware adds a middleware to the request manager.
func (*RequestManager) Close ¶
func (rm *RequestManager) Close() error
Close gracefully shuts down the request manager.
func (*RequestManager) Do ¶
Do executes an HTTP request with comprehensive error handling and middleware processing.
func (*RequestManager) GetActiveCorrelations ¶
func (rm *RequestManager) GetActiveCorrelations() map[string]*RequestCorrelation
GetActiveCorrelations returns all active request correlations.
func (*RequestManager) GetCircuitBreakerState ¶
func (rm *RequestManager) GetCircuitBreakerState() CircuitBreakerState
GetCircuitBreakerState returns the current circuit breaker state.
func (*RequestManager) GetCorrelationMapStats ¶
func (rm *RequestManager) GetCorrelationMapStats() map[string]interface{}
GetCorrelationMapStats returns statistics about the correlation map
type RequestManagerConfig ¶
type RequestManagerConfig struct {
// Timeout for requests (default: 30 seconds)
Timeout time.Duration
// Maximum number of idle connections
MaxIdleConns int
// Maximum idle connections per host
MaxIdleConnsPerHost int
// Keep-alive timeout
KeepAlive time.Duration
// TLS handshake timeout
TLSHandshakeTimeout time.Duration
// Response header timeout
ResponseHeaderTimeout time.Duration
// Expect continue timeout
ExpectContinueTimeout time.Duration
// Maximum response size (default: 100MB)
MaxResponseSize int64
// Rate limit requests per second (0 = no limit)
RateLimit float64
// Rate limit burst size
RateLimitBurst int
// Circuit breaker configuration
CircuitBreakerConfig CircuitBreakerConfig
// Security headers to validate
RequiredSecurityHeaders []string
// Allowed content types
AllowedContentTypes []string
// User agent string
UserAgent string
// Enable request/response logging
EnableLogging bool
// Enable metrics collection
EnableMetrics bool
// Enable tracing
EnableTracing bool
// Custom headers to add to all requests
DefaultHeaders map[string]string
}
RequestManagerConfig contains configuration options for the RequestManager.
type RequestMetrics ¶
type RequestMetrics struct {
// contains filtered or unexported fields
}
RequestMetrics tracks request/response metrics.
type ResilienceConfig ¶
type ResilienceConfig struct {
// RetryConfig configures retry behavior
Retry RetryConfig `json:"retry"`
// CircuitBreakerConfig configures circuit breaker behavior
CircuitBreaker CircuitBreakerConfig `json:"circuit_breaker"`
// RateLimiterConfig configures rate limiting
RateLimit RateLimitConfig `json:"rate_limit"`
// TimeoutConfig configures timeout behavior
Timeout TimeoutConfig `json:"timeout"`
// BulkheadConfig configures resource isolation
Bulkhead BulkheadConfig `json:"bulkhead"`
// HealthCheckConfig configures health monitoring
HealthCheck HealthCheckConfig `json:"health_check"`
// MetricsConfig configures metrics collection
Metrics MetricsConfig `json:"metrics"`
}
ResilienceConfig contains configuration for all resilience patterns
func DefaultResilienceConfig ¶
func DefaultResilienceConfig() ResilienceConfig
DefaultResilienceConfig returns a default resilience configuration
func (*ResilienceConfig) Validate ¶
func (rc *ResilienceConfig) Validate() error
Validate validates the ResilienceConfig and returns detailed errors
type ResilienceManager ¶
type ResilienceManager struct {
// contains filtered or unexported fields
}
ResilienceManager coordinates all resilience patterns
func NewResilienceManager ¶
func NewResilienceManager(config ResilienceConfig) *ResilienceManager
NewResilienceManager creates a new resilience manager with the given configuration
type ResourceLimits ¶
type ResourceLimits struct {
MaxMemory int64 `json:"max_memory"` // In bytes
MaxCPUTime time.Duration `json:"max_cpu_time"` // CPU time limit
MaxDiskSpace int64 `json:"max_disk_space"` // In bytes
MaxNetworkIO int64 `json:"max_network_io"` // In bytes
}
ResourceLimits defines resource usage limits for tool execution.
type ResourceMonitor ¶
type ResourceMonitor struct {
// contains filtered or unexported fields
}
ResourceMonitor monitors resource usage during tool execution.
func (*ResourceMonitor) Start ¶
func (rm *ResourceMonitor) Start(execution *ToolExecution)
func (*ResourceMonitor) Stop ¶
func (rm *ResourceMonitor) Stop()
type RetryConfig ¶
type RetryConfig struct {
// MaxAttempts is the maximum number of retry attempts
MaxAttempts int `json:"max_attempts"`
// BaseDelay is the initial delay between retries
BaseDelay time.Duration `json:"base_delay"`
// MaxDelay is the maximum delay between retries
MaxDelay time.Duration `json:"max_delay"`
// BackoffMultiplier is the multiplier for exponential backoff
BackoffMultiplier float64 `json:"backoff_multiplier"`
// JitterEnabled enables random jitter to prevent thundering herd
JitterEnabled bool `json:"jitter_enabled"`
// JitterMaxFactor is the maximum jitter factor (0.0 to 1.0)
JitterMaxFactor float64 `json:"jitter_max_factor"`
// RetryableErrors defines which errors should trigger retries
RetryableErrors []string `json:"retryable_errors"`
}
RetryConfig configures exponential backoff retry logic
func QuickRetryConfig ¶
func QuickRetryConfig(maxAttempts int, baseDelay time.Duration) *RetryConfig
QuickRetryConfig creates a retry configuration with exponential backoff
func (*RetryConfig) Validate ¶
func (rc *RetryConfig) Validate() error
Validate validates RetryConfig
type RetryManager ¶
type RetryManager struct {
// contains filtered or unexported fields
}
RetryManager handles exponential backoff retry logic with jitter
func NewRetryManager ¶
func NewRetryManager(config RetryConfig) *RetryManager
NewRetryManager creates a new retry manager
func (*RetryManager) ExecuteWithRetry ¶
func (rm *RetryManager) ExecuteWithRetry(ctx context.Context, operation func(ctx context.Context) error) error
ExecuteWithRetry executes an operation with retry logic
type RetryPolicy ¶
type RetryPolicy struct {
// contains filtered or unexported fields
}
RetryPolicy implements smart retry logic
type SSEClient ¶
type SSEClient struct {
// contains filtered or unexported fields
}
SSEClient is a robust Server-Sent Events streaming client
func NewSSEClient ¶
func NewSSEClient(config SSEClientConfig) (*SSEClient, error)
NewSSEClient creates a new SSE client with the given configuration
func (*SSEClient) BufferLength ¶
BufferLength returns the current buffer length
func (*SSEClient) IsBackpressureActive ¶
IsBackpressureActive returns true if backpressure is currently active
func (*SSEClient) LastEventID ¶
LastEventID returns the last received event ID
func (*SSEClient) ReconnectCount ¶
ReconnectCount returns the number of reconnection attempts
func (*SSEClient) State ¶
func (c *SSEClient) State() SSEConnectionState
State returns the current connection state
type SSEClientConfig ¶
type SSEClientConfig struct {
// URL is the SSE endpoint URL
URL string
// Headers contains custom headers to send with the request
Headers map[string]string
// InitialBackoff is the initial backoff duration for reconnection (default: 1s)
InitialBackoff time.Duration
// MaxBackoff is the maximum backoff duration for reconnection (default: 30s)
MaxBackoff time.Duration
// BackoffMultiplier is the multiplier for exponential backoff (default: 2.0)
BackoffMultiplier float64
// MaxReconnectAttempts is the maximum number of reconnect attempts (0 = unlimited)
MaxReconnectAttempts int
// EventBufferSize is the size of the event buffer (default: 1000)
EventBufferSize int
// ReadTimeout is the timeout for reading from the connection (default: 0 = no timeout)
ReadTimeout time.Duration
// WriteTimeout is the timeout for writing to the connection (default: 10s)
WriteTimeout time.Duration
// HealthCheckInterval is the interval for connection health checks (default: 30s)
HealthCheckInterval time.Duration
// MaxStreamLifetime is the maximum lifetime for a streaming connection (default: 30m)
// After this duration, the stream will be automatically terminated to prevent goroutine leaks
MaxStreamLifetime time.Duration
// LastEventID is the last event ID for resuming connections
LastEventID string
// RetryInterval is the default retry interval suggested by the server
RetryInterval time.Duration
// TLSConfig for HTTPS connections
TLSConfig *tls.Config
// SkipTLSVerify skips TLS certificate verification (insecure)
SkipTLSVerify bool
// UserAgent is the User-Agent header value
UserAgent string
// EnableCompression enables gzip compression
EnableCompression bool
// EventFilter filters events by event type (nil = no filtering)
EventFilter func(eventType string) bool
// OnConnect is called when the connection is established
OnConnect func()
// OnDisconnect is called when the connection is lost
OnDisconnect func(err error)
// OnReconnect is called when reconnection starts
OnReconnect func(attempt int)
// OnError is called when an error occurs
OnError func(err error)
// FlowControlEnabled enables backpressure handling
FlowControlEnabled bool
// FlowControlThreshold is the buffer threshold for flow control (default: 80%)
FlowControlThreshold float64
}
SSEClientConfig contains configuration options for the SSE client
func (*SSEClientConfig) Validate ¶
func (sc *SSEClientConfig) Validate() error
Validate validates the SSEClientConfig and returns detailed errors
type SSEClientState ¶
type SSEClientState struct {
// contains filtered or unexported fields
}
SSEClientState holds all client state that needs to be read atomically
type SSEConnectionState ¶
type SSEConnectionState int
SSEConnectionState represents the state of the SSE connection
const ( SSEStateDisconnected SSEConnectionState = iota SSEStateConnecting SSEStateConnected SSEStateReconnecting SSEStateClosed )
func (SSEConnectionState) String ¶
func (s SSEConnectionState) String() string
String returns the string representation of the connection state
type SSEEvent ¶
type SSEEvent struct {
ID string `json:"id,omitempty"`
Event string `json:"event,omitempty"`
Data string `json:"data"`
Retry *time.Duration `json:"retry,omitempty"`
Raw string `json:"raw"`
Headers map[string]string `json:"headers,omitempty"`
Timestamp time.Time `json:"timestamp"`
Sequence uint64 `json:"sequence"`
}
SSEEvent represents a parsed Server-Sent Event
type SecurityConfig ¶
type SecurityConfig struct {
// Authentication settings
AuthMethod AuthMethod `json:"auth_method" yaml:"auth_method"`
EnableMultiAuth bool `json:"enable_multi_auth" yaml:"enable_multi_auth"`
SupportedMethods []AuthMethod `json:"supported_methods" yaml:"supported_methods"`
// JWT settings
JWT JWTConfig `json:"jwt" yaml:"jwt"`
// API Key settings
APIKey APIKeyConfig `json:"api_key" yaml:"api_key"`
// Basic Auth settings
BasicAuth BasicAuthConfig `json:"basic_auth" yaml:"basic_auth"`
// TLS/SSL settings
TLS TLSConfig `json:"tls" yaml:"tls"`
// HMAC settings
HMAC HMACConfig `json:"hmac" yaml:"hmac"`
// Security headers
SecurityHeaders SecurityHeadersConfig `json:"security_headers" yaml:"security_headers"`
// Token storage
TokenStorage TokenStorageConfig `json:"token_storage" yaml:"token_storage"`
// Audit logging
AuditLogging AuditLoggingConfig `json:"audit_logging" yaml:"audit_logging"`
// Rate limiting and protection
RateLimit RateLimitConfig `json:"rate_limit" yaml:"rate_limit"`
// Session management
SessionConfig SessionConfig `json:"session" yaml:"session"`
}
SecurityConfig contains comprehensive security configuration
func DevSecurityConfig ¶
func DevSecurityConfig() *SecurityConfig
DevSecurityConfig creates a relaxed security configuration for development
func NewDefaultSecurityConfig ¶
func NewDefaultSecurityConfig() *SecurityConfig
Helper function to create default security configuration
func ProdSecurityConfig ¶
func ProdSecurityConfig(jwtSecret string) *SecurityConfig
ProdSecurityConfig creates a secure configuration for production
func (*SecurityConfig) Validate ¶
func (sc *SecurityConfig) Validate() error
Validate validates the SecurityConfig and returns detailed errors
type SecurityEvent ¶
type SecurityEvent struct {
Type string `json:"type"`
Timestamp time.Time `json:"timestamp"`
UserID string `json:"user_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
IPAddress string `json:"ip_address,omitempty"`
UserAgent string `json:"user_agent,omitempty"`
Resource string `json:"resource,omitempty"`
Action string `json:"action,omitempty"`
Result string `json:"result"`
Error string `json:"error,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
SecurityEvent represents a security-related event for audit logging
type SecurityHeaderManager ¶
type SecurityHeaderManager struct {
// contains filtered or unexported fields
}
SecurityHeaderManager manages security headers and CORS
func NewSecurityHeaderManager ¶
func NewSecurityHeaderManager(config *SecurityHeadersConfig, logger *zap.Logger) (*SecurityHeaderManager, error)
NewSecurityHeaderManager creates a new security header manager
func (*SecurityHeaderManager) AddCustomHeader ¶
func (shm *SecurityHeaderManager) AddCustomHeader(name, value string)
AddCustomHeader adds a custom security header
func (*SecurityHeaderManager) ApplySecurityHeaders ¶
func (shm *SecurityHeaderManager) ApplySecurityHeaders(w http.ResponseWriter, r *http.Request)
ApplySecurityHeaders applies security headers to the HTTP response
func (*SecurityHeaderManager) GenerateNonce ¶
func (shm *SecurityHeaderManager) GenerateNonce() (string, error)
GenerateNonce generates a cryptographically secure nonce for CSP
func (*SecurityHeaderManager) GetCSPViolationHandler ¶
func (shm *SecurityHeaderManager) GetCSPViolationHandler() http.HandlerFunc
GetCSPViolationHandler returns a handler for CSP violation reports
func (*SecurityHeaderManager) GetSecurityHeadersInfo ¶
func (shm *SecurityHeaderManager) GetSecurityHeadersInfo() map[string]interface{}
GetSecurityHeadersInfo returns information about configured security headers
func (*SecurityHeaderManager) Middleware ¶
func (shm *SecurityHeaderManager) Middleware() func(http.Handler) http.Handler
Middleware returns an HTTP middleware that applies security headers
func (*SecurityHeaderManager) RemoveCustomHeader ¶
func (shm *SecurityHeaderManager) RemoveCustomHeader(name string)
RemoveCustomHeader removes a custom security header
func (*SecurityHeaderManager) UpdateCSPPolicy ¶
func (shm *SecurityHeaderManager) UpdateCSPPolicy(policy string) error
UpdateCSPPolicy updates the CSP policy
func (*SecurityHeaderManager) ValidateCSPPolicy ¶
func (shm *SecurityHeaderManager) ValidateCSPPolicy(policy string) []string
ValidateCSPPolicy validates a CSP policy string
type SecurityHeadersConfig ¶
type SecurityHeadersConfig struct {
EnableCSP bool `json:"enable_csp" yaml:"enable_csp"`
CSPPolicy string `json:"csp_policy" yaml:"csp_policy"`
EnableHSTS bool `json:"enable_hsts" yaml:"enable_hsts"`
HSTSMaxAge int `json:"hsts_max_age" yaml:"hsts_max_age"`
EnableXFrameOptions bool `json:"enable_x_frame_options" yaml:"enable_x_frame_options"`
XFrameOptions string `json:"x_frame_options" yaml:"x_frame_options"`
EnableXContentType bool `json:"enable_x_content_type" yaml:"enable_x_content_type"`
EnableReferrerPolicy bool `json:"enable_referrer_policy" yaml:"enable_referrer_policy"`
ReferrerPolicy string `json:"referrer_policy" yaml:"referrer_policy"`
CustomHeaders map[string]string `json:"custom_headers" yaml:"custom_headers"`
CORSConfig CORSConfig `json:"cors" yaml:"cors"`
}
SecurityHeadersConfig contains security headers configuration
func (*SecurityHeadersConfig) Validate ¶
func (shc *SecurityHeadersConfig) Validate() error
Validate validates SecurityHeadersConfig
type SecurityManager ¶
type SecurityManager struct {
// contains filtered or unexported fields
}
SecurityManager manages authentication and security features
func NewSecurityManager ¶
func NewSecurityManager(config *SecurityConfig, logger *zap.Logger) (*SecurityManager, error)
NewSecurityManager creates a new security manager with the given configuration
func (*SecurityManager) Authenticate ¶
func (sm *SecurityManager) Authenticate(ctx context.Context, req *http.Request) (*AuthenticationResult, error)
Authenticate performs authentication based on the configured method
func (*SecurityManager) AuthenticationMiddleware ¶
func (sm *SecurityManager) AuthenticationMiddleware() func(http.Handler) http.Handler
Middleware integration
func (*SecurityManager) AuthorizeRequest ¶
func (sm *SecurityManager) AuthorizeRequest(ctx context.Context, user *UserInfo, resource string, action string) error
Authorization methods
func (*SecurityManager) RefreshToken ¶
func (sm *SecurityManager) RefreshToken(ctx context.Context, refreshToken string) (*TokenInfo, error)
Token management methods
func (*SecurityManager) RevokeToken ¶
func (sm *SecurityManager) RevokeToken(ctx context.Context, token string) error
RevokeToken revokes a token
type SequenceState ¶
type SequenceState struct {
// contains filtered or unexported fields
}
SequenceState tracks the state of an event sequence.
type SessionConfig ¶
type SessionConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
CookieName string `json:"cookie_name" yaml:"cookie_name"`
CookieSecure bool `json:"cookie_secure" yaml:"cookie_secure"`
CookieHTTPOnly bool `json:"cookie_http_only" yaml:"cookie_http_only"`
CookieSameSite string `json:"cookie_same_site" yaml:"cookie_same_site"`
SessionTimeout time.Duration `json:"session_timeout" yaml:"session_timeout"`
}
type SessionInfo ¶
type SessionInfo struct {
SessionID string `json:"session_id"`
UserID string `json:"user_id"`
CreatedAt time.Time `json:"created_at"`
LastAccessedAt time.Time `json:"last_accessed_at"`
ExpiresAt time.Time `json:"expires_at"`
IPAddress string `json:"ip_address"`
UserAgent string `json:"user_agent"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
SessionInfo contains information about an active session
type StateCache ¶
type StateCache struct {
// contains filtered or unexported fields
}
StateCache provides efficient local caching of state data.
type StateChangeEvent ¶
type StateChangeEvent struct {
Path string `json:"path"`
OldValue interface{} `json:"old_value"`
NewValue interface{} `json:"new_value"`
Operation string `json:"operation"` // Use string for simple operation types
Timestamp time.Time `json:"timestamp"`
Version string `json:"version"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
StateChangeEvent represents a state change event.
type StateCondition ¶
type StateCondition struct {
// Field path to test
Path string `json:"path"`
// Expected value
Expected interface{} `json:"expected"`
// Comparison operation
Op string `json:"op"` // "eq", "ne", "exists", "not_exists"
}
StateCondition represents a condition for state operations
type StateConfig ¶
type StateConfig struct {
SyncInterval time.Duration `json:"sync_interval" yaml:"sync_interval"`
CacheSize string `json:"cache_size" yaml:"cache_size"`
EnablePersistence bool `json:"enable_persistence" yaml:"enable_persistence"`
ConflictResolution ConflictResolutionStrategy `json:"conflict_resolution" yaml:"conflict_resolution"`
}
StateConfig contains configuration for state management.
type StateDelta ¶
type StateDelta struct {
// Version is the expected current version
Version int64 `json:"version"`
// Operations are the changes to apply
Operations []StateOperation `json:"operations"`
// Metadata for the change
Metadata map[string]interface{} `json:"metadata,omitempty"`
// Timestamp when the delta was created
Timestamp time.Time `json:"timestamp"`
}
StateDelta represents an incremental state change
type StateFilter ¶
type StateFilter func(StateChangeEvent) bool
StateFilter allows filtering of state change events.
type StateManager ¶
type StateManager interface {
// GetState returns the current state of the agent.
// This can be called from any state where the agent is initialized.
GetState(ctx context.Context) (*AgentState, error)
// UpdateState applies a state change delta to the agent's state.
// This uses optimistic concurrency control with version numbers.
UpdateState(ctx context.Context, delta *StateDelta) error
}
StateManager handles agent state operations including retrieval and updates. This interface manages the agent's internal state with support for atomic updates and conflict resolution.
type StateManagerMetrics ¶
type StateManagerMetrics struct {
StateReads int64 `json:"state_reads"`
StateWrites int64 `json:"state_writes"`
CacheHits int64 `json:"cache_hits"`
CacheMisses int64 `json:"cache_misses"`
SyncOperations int64 `json:"sync_operations"`
ConflictResolutions int64 `json:"conflict_resolutions"`
AverageLatency time.Duration `json:"average_latency"`
ErrorCount int64 `json:"error_count"`
LastSyncTime time.Time `json:"last_sync_time"`
}
StateManagerMetrics contains metrics for the state manager.
type StateOperation ¶
type StateOperation struct {
// Operation type (set, delete, merge)
Op StateOperationType `json:"op"`
// Path to the field to modify (JSON pointer style)
Path string `json:"path"`
// Value for set/merge operations
Value interface{} `json:"value,omitempty"`
// Condition for conditional operations
Condition *StateCondition `json:"condition,omitempty"`
}
StateOperation represents a single state change operation
type StateOperationType ¶
type StateOperationType string
StateOperationType defines the type of state operation
const ( StateOpSet StateOperationType = "set" StateOpDelete StateOperationType = "delete" StateOpMerge StateOperationType = "merge" StateOpTest StateOperationType = "test" )
type StateSubscription ¶
type StateSubscription struct {
ID string
Path string
Callback func(StateChangeEvent)
Filter StateFilter
}
StateSubscription represents a subscription to state changes.
type StateVersion ¶
type StateVersion struct {
ID string `json:"id"`
Data map[string]interface{} `json:"data"`
Timestamp time.Time `json:"timestamp"`
Checksum string `json:"checksum"`
ParentID string `json:"parent_id,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
StateVersion represents a versioned state with metadata.
type StoredMessage ¶
type StoredMessage struct {
Message *messages.Message `json:"message"`
ConversationID string `json:"conversation_id"`
ThreadID string `json:"thread_id,omitempty"`
ParentID string `json:"parent_id,omitempty"`
Timestamp time.Time `json:"timestamp"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
CompressedData []byte `json:"compressed_data,omitempty"`
IsCompressed bool `json:"is_compressed"`
}
StoredMessage represents a message stored in history with metadata.
type StreamingResult ¶
type StreamingResult struct {
ExecutionID string `json:"execution_id"`
Chunk interface{} `json:"chunk"`
IsComplete bool `json:"is_complete"`
Error string `json:"error,omitempty"`
Timestamp time.Time `json:"timestamp"`
}
StreamingResult represents a streaming tool execution result.
type TLSConfig ¶
type TLSConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
CertFile string `json:"cert_file" yaml:"cert_file"`
KeyFile string `json:"key_file" yaml:"key_file"`
CAFile string `json:"ca_file" yaml:"ca_file"`
ClientAuth tls.ClientAuthType `json:"client_auth" yaml:"client_auth"`
MinVersion uint16 `json:"min_version" yaml:"min_version"`
MaxVersion uint16 `json:"max_version" yaml:"max_version"`
CipherSuites []uint16 `json:"cipher_suites" yaml:"cipher_suites"`
CurvePreferences []tls.CurveID `json:"curve_preferences" yaml:"curve_preferences"`
EnableSNI bool `json:"enable_sni" yaml:"enable_sni"`
InsecureSkipVerify bool `json:"insecure_skip_verify" yaml:"insecure_skip_verify"`
CertificateValidation CertValidationConfig `json:"certificate_validation" yaml:"certificate_validation"`
}
TLSConfig contains TLS/SSL configuration
func QuickTLSConfig ¶
QuickTLSConfig creates a TLS configuration with secure defaults
type Thread ¶
type Thread struct {
ID string `json:"id"`
ConversationID string `json:"conversation_id"`
Title string `json:"title,omitempty"`
Messages []string `json:"messages"` // Message IDs in order
StartTime time.Time `json:"start_time"`
LastActivity time.Time `json:"last_activity"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
Thread represents a thread within a conversation.
type TimeoutConfig ¶
type TimeoutConfig struct {
// OperationTimeout is the default operation timeout
OperationTimeout time.Duration `json:"operation_timeout"`
// ConnectionTimeout is the connection establishment timeout
ConnectionTimeout time.Duration `json:"connection_timeout"`
// ReadTimeout is the read operation timeout
ReadTimeout time.Duration `json:"read_timeout"`
// WriteTimeout is the write operation timeout
WriteTimeout time.Duration `json:"write_timeout"`
// KeepAliveTimeout is the keep-alive timeout
KeepAliveTimeout time.Duration `json:"keep_alive_timeout"`
// IdleConnectionTimeout is the idle connection timeout
IdleConnectionTimeout time.Duration `json:"idle_connection_timeout"`
}
TimeoutConfig configures timeout and deadline management
type TimestampIndex ¶
TimestampIndex represents a message with its timestamp for sorting.
type TokenEncryptor ¶
type TokenEncryptor struct {
// contains filtered or unexported fields
}
TokenEncryptor handles token encryption/decryption
func NewTokenEncryptor ¶
func NewTokenEncryptor(config *EncryptionConfig, logger *zap.Logger) (*TokenEncryptor, error)
NewTokenEncryptor creates a new token encryptor
func (*TokenEncryptor) Decrypt ¶
func (te *TokenEncryptor) Decrypt(data *EncryptedTokenData) (*TokenInfo, error)
Decrypt decrypts token info
func (*TokenEncryptor) Encrypt ¶
func (te *TokenEncryptor) Encrypt(info *TokenInfo) (*EncryptedTokenData, error)
Encrypt encrypts token info
type TokenInfo ¶
type TokenInfo struct {
Token string `json:"token"`
TokenType TokenType `json:"token_type"`
ExpiresAt time.Time `json:"expires_at"`
IssuedAt time.Time `json:"issued_at"`
Subject string `json:"subject"`
Scopes []string `json:"scopes"`
RefreshToken string `json:"refresh_token,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
TokenInfo contains information about an active token
type TokenStorage ¶
type TokenStorage interface {
StoreToken(token string, info *TokenInfo) error
GetToken(token string) (*TokenInfo, error)
RevokeToken(token string) error
ListTokens(userID string) ([]*TokenInfo, error)
CleanupExpiredTokens() error
Cleanup() error
}
TokenStorage interface for storing and retrieving tokens
func NewTokenStorage ¶
func NewTokenStorage(config *TokenStorageConfig, logger *zap.Logger) (TokenStorage, error)
NewTokenStorage creates a new token storage based on configuration
type TokenStorageConfig ¶
type TokenStorageConfig struct {
StorageType string `json:"storage_type" yaml:"storage_type"`
Encryption EncryptionConfig `json:"encryption" yaml:"encryption"`
FilePath string `json:"file_path,omitempty" yaml:"file_path,omitempty"`
RedisConfig RedisConfig `json:"redis,omitempty" yaml:"redis,omitempty"`
DatabaseConfig DatabaseConfig `json:"database,omitempty" yaml:"database,omitempty"`
}
TokenStorageConfig contains token storage configuration
func (*TokenStorageConfig) Validate ¶
func (tsc *TokenStorageConfig) Validate() error
Validate validates TokenStorageConfig
type TokenStore ¶
type TokenStore struct {
Tokens map[string]*EncryptedTokenData `json:"tokens"`
UserTokens map[string][]string `json:"user_tokens"`
LastUpdated time.Time `json:"last_updated"`
Version string `json:"version"`
}
TokenStore represents the file storage format
type ToolCache ¶
type ToolCache struct {
// contains filtered or unexported fields
}
ToolCache provides efficient caching of tool results.
type ToolDefinition ¶
type ToolDefinition struct {
Name string `json:"name"`
Description string `json:"description"`
Schema *tools.ToolSchema `json:"schema"`
Capabilities map[string]interface{} `json:"capabilities,omitempty"`
}
ToolDefinition describes a tool available to the agent.
type ToolExecution ¶
type ToolExecution struct {
ID string `json:"id"`
ToolName string `json:"tool_name"`
Parameters interface{} `json:"parameters"`
StartTime time.Time `json:"start_time"`
Status ExecutionStatus `json:"status"`
Result interface{} `json:"result,omitempty"`
Error string `json:"error,omitempty"`
Duration time.Duration `json:"duration"`
Context context.Context `json:"-"`
Cancel context.CancelFunc `json:"-"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
ToolExecution represents an active tool execution.
type ToolExecutionFramework ¶
type ToolExecutionFramework struct {
// contains filtered or unexported fields
}
ToolExecutionFramework manages tool execution for the base agent. It provides a complete tool execution system with validation, timeout management, concurrency control, and error handling.
func NewToolExecutionFramework ¶
func NewToolExecutionFramework(config *ToolsConfig) *ToolExecutionFramework
NewToolExecutionFramework creates a new tool execution framework.
func (*ToolExecutionFramework) CancelAll ¶
func (f *ToolExecutionFramework) CancelAll()
CancelAll cancels all active tool executions.
func (*ToolExecutionFramework) Execute ¶
func (f *ToolExecutionFramework) Execute(ctx context.Context, name string, params map[string]interface{}) (*tools.ToolExecutionResult, error)
Execute executes a tool with the given name and parameters.
func (*ToolExecutionFramework) ExecuteStream ¶
func (f *ToolExecutionFramework) ExecuteStream(ctx context.Context, name string, params map[string]interface{}) (<-chan *tools.ToolStreamChunk, error)
ExecuteStream executes a streaming tool with the given name and parameters.
func (*ToolExecutionFramework) GetExecutionEngine ¶
func (f *ToolExecutionFramework) GetExecutionEngine() *tools.ExecutionEngine
GetExecutionEngine returns the execution engine.
func (*ToolExecutionFramework) GetMetrics ¶
func (f *ToolExecutionFramework) GetMetrics() *tools.ExecutionMetrics
GetMetrics returns execution metrics.
func (*ToolExecutionFramework) GetRegistry ¶
func (f *ToolExecutionFramework) GetRegistry() *tools.Registry
GetRegistry returns the tool registry.
func (*ToolExecutionFramework) GetTool ¶
func (f *ToolExecutionFramework) GetTool(toolID string) (tools.ReadOnlyTool, error)
GetTool gets a tool by ID.
func (*ToolExecutionFramework) ListTools ¶
func (f *ToolExecutionFramework) ListTools() []tools.ReadOnlyTool
ListTools lists all available tools.
func (*ToolExecutionFramework) RegisterTool ¶
func (f *ToolExecutionFramework) RegisterTool(tool *tools.Tool) error
RegisterTool registers a custom tool for this agent.
func (*ToolExecutionFramework) Shutdown ¶
func (f *ToolExecutionFramework) Shutdown(ctx context.Context) error
Shutdown gracefully shuts down the tool execution framework.
func (*ToolExecutionFramework) UnregisterTool ¶
func (f *ToolExecutionFramework) UnregisterTool(toolID string) error
UnregisterTool removes a custom tool from this agent.
type ToolExecutor ¶
type ToolExecutor struct {
// contains filtered or unexported fields
}
ToolExecutor manages tool execution with sandboxing and resource limits.
type ToolManagerMetrics ¶
type ToolManagerMetrics struct {
ToolsExecuted int64 `json:"tools_executed"`
SuccessfulExecutions int64 `json:"successful_executions"`
FailedExecutions int64 `json:"failed_executions"`
CachedExecutions int64 `json:"cached_executions"`
AverageExecutionTime time.Duration `json:"average_execution_time"`
ConcurrentExecutions int32 `json:"concurrent_executions"`
SandboxViolations int64 `json:"sandbox_violations"`
ResourceLimitExceeded int64 `json:"resource_limit_exceeded"`
LastExecutionTime time.Time `json:"last_execution_time"`
}
ToolManagerMetrics contains metrics for the tool manager.
type ToolRunner ¶
type ToolRunner interface {
// ExecuteTool executes a tool with the given name and parameters.
// The agent must be running for this to succeed.
ExecuteTool(ctx context.Context, name string, params interface{}) (interface{}, error)
// ListTools returns a list of tools available to this agent.
// This can be called from any state where the agent is initialized.
ListTools() []ToolDefinition
}
ToolRunner handles tool execution and discovery operations. This interface provides the agent's ability to execute tools and expose available tool definitions to clients.
type ToolSandbox ¶
type ToolSandbox struct {
// contains filtered or unexported fields
}
ToolSandbox provides security sandboxing for tool execution.
type ToolsConfig ¶
type ToolsConfig struct {
Timeout time.Duration `json:"timeout" yaml:"timeout"`
MaxConcurrent int `json:"max_concurrent" yaml:"max_concurrent"`
EnableSandboxing bool `json:"enable_sandboxing" yaml:"enable_sandboxing"`
EnableCaching bool `json:"enable_caching" yaml:"enable_caching"`
}
ToolsConfig contains configuration for tool execution.
type UserInfo ¶
type UserInfo struct {
ID string `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
Roles []string `json:"roles"`
Permissions []string `json:"permissions"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
UserInfo contains information about an authenticated user
Source Files
¶
- agent.go
- agent_config.go
- agent_state.go
- agent_tools.go
- apikey_manager.go
- audit_logger.go
- auth.go
- base_agent.go
- basicauth_manager.go
- cert_manager.go
- client.go
- config_examples.go
- config_helpers.go
- config_profiles.go
- config_validation.go
- doc.go
- event_processor.go
- hmac_manager.go
- http_agent.go
- http_transport.go
- jwt_manager.go
- message_history.go
- rate_limiter.go
- request_manager.go
- resilience.go
- security_headers.go
- streaming_client.go
- token_storage.go