agent

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2026 License: GPL-3.0 Imports: 24 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package agent implements the application service for the agent bounded context — orchestrates pkg/domain/agent entities and cross-cutting concerns (audit, notifications, RBAC).

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoAgentAvailable is returned when no suitable agent is found.
	ErrNoAgentAvailable = errors.New("no suitable agent available")
)

Functions

This section is empty.

Types

type AgentAvailabilityResult

type AgentAvailabilityResult struct {
	HasTenantAgent bool
	Available      bool
	Message        string
}

AgentAvailabilityResult represents agent availability status.

type AgentConfigTemplateService

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

AgentConfigTemplateService renders agent configuration templates (yaml, env, docker, cli) from filesystem-loaded templates.

Templates live in <templates_dir>/{yaml,env,docker,cli}.tmpl and use Go text/template syntax. Operators can edit the .tmpl files in place without rebuilding the API or frontend — changes are picked up on restart, or live if Reload() is called.

The service caches parsed templates after first load. Call Reload() to pick up file changes without restart.

func NewAgentConfigTemplateService

func NewAgentConfigTemplateService(templatesDir string, log *logger.Logger) *AgentConfigTemplateService

NewAgentConfigTemplateService loads templates from the given directory. If the directory doesn't exist or any template fails to parse, the service falls back to built-in defaults so the API never fails to start.

func (*AgentConfigTemplateService) Reload

func (s *AgentConfigTemplateService) Reload() error

Reload re-reads all template files from disk. Safe to call at runtime.

func (*AgentConfigTemplateService) Render

Render renders all four template formats with the given agent data. Returns user-friendly content (no internal errors leaked).

type AgentHeartbeatData

type AgentHeartbeatData struct {
	Version       string
	Hostname      string
	CPUPercent    float64
	MemoryPercent float64
	CurrentJobs   int
	Region        string

	// Disk/network throughput in MB/s. Optional — agents that do not report
	// them leave the corresponding load-score terms at zero.
	DiskReadMBPS  float64
	DiskWriteMBPS float64
	NetworkRxMBPS float64
	NetworkTxMBPS float64
}

AgentHeartbeatData represents the data received from agent heartbeat.

type AgentHeartbeatInput

type AgentHeartbeatInput struct {
	AgentID   shared.ID
	Status    string
	Message   string
	Version   string
	Hostname  string
	IPAddress string
}

AgentHeartbeatInput represents the input for agent heartbeat.

type AgentSelectionMode

type AgentSelectionMode string

AgentSelectionMode defines which agents to consider.

const (
	// SelectTenantOnly only considers tenant's own agents.
	SelectTenantOnly AgentSelectionMode = "tenant_only"
	// SelectAny selects from any available agent.
	SelectAny AgentSelectionMode = "any"
)

type AgentSelector

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

AgentSelector handles intelligent agent selection for job execution.

func NewAgentSelector

func NewAgentSelector(
	agentRepo agentdom.Repository,
	commandRepo command.Repository,
	agentState *redis.AgentStateStore,
	log *logger.Logger,
) *AgentSelector

NewAgentSelector creates a new AgentSelector.

func (*AgentSelector) CheckAgentAvailability

func (s *AgentSelector) CheckAgentAvailability(ctx context.Context, tenantID shared.ID, toolName string, tenantOnly bool) *AgentAvailabilityResult

CheckAgentAvailability checks if any agent is available for the given scan configuration. This should be called before creating a scan to ensure execution is possible.

func (*AgentSelector) SelectAgent

SelectAgent selects the best agent for a job based on the selection mode.

func (*AgentSelector) SetLoadBalancingWeights added in v0.4.0

func (s *AgentSelector) SetLoadBalancingWeights(w agentdom.LoadBalancingWeights)

SetLoadBalancingWeights installs the operator-configured load-balancing weights (AGENT_LB_*). Call once at boot, before the selector serves traffic. An all-zero weight set is ignored — it would score every agent at 0 and make selection arbitrary.

type AgentService

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

AgentService handles agent-related business operations.

func NewAgentService

func NewAgentService(repo agentdom.Repository, auditService *auditapp.AuditService, log *logger.Logger) *AgentService

NewAgentService creates a new AgentService.

func (*AgentService) ActivateAgent

func (s *AgentService) ActivateAgent(ctx context.Context, tenantID, agentID string, auditCtx *auditapp.AuditContext) (*agentdom.Agent, error)

ActivateAgent activates an agent (admin action).

func (*AgentService) AuthenticateByAPIKey

func (s *AgentService) AuthenticateByAPIKey(ctx context.Context, apiKey string) (*agentdom.Agent, error)

AuthenticateByAPIKey authenticates an agent by API key. Authentication is based on admin-controlled Status field only: - Active: allowed to authenticate - Disabled: admin has disabled the agent - Revoked: access permanently revoked The Health field (unknown/online/offline/error) is for monitoring only.

func (*AgentService) ClaimJob

func (s *AgentService) ClaimJob(ctx context.Context, agentID shared.ID) error

ClaimJob claims a job slot on an agent for load balancing.

func (*AgentService) CreateAgent

func (s *AgentService) CreateAgent(ctx context.Context, input CreateAgentInput) (*CreateAgentOutput, error)

CreateAgent creates a new agent and generates an API key.

func (*AgentService) DeleteAgent

func (s *AgentService) DeleteAgent(ctx context.Context, tenantID, agentID string, auditCtx *auditapp.AuditContext) error

DeleteAgent deletes an agent.

func (*AgentService) DisableAgent

func (s *AgentService) DisableAgent(ctx context.Context, tenantID, agentID, reason string, auditCtx *auditapp.AuditContext) (*agentdom.Agent, error)

DisableAgent disables an agent (admin action).

func (*AgentService) FindAvailableAgents

func (s *AgentService) FindAvailableAgents(ctx context.Context, tenantID shared.ID, capabilities []string, tool string) ([]*agentdom.Agent, error)

FindAvailableAgents finds agents that can handle a task.

func (*AgentService) FindAvailableWithCapacity

func (s *AgentService) FindAvailableWithCapacity(ctx context.Context, tenantID shared.ID, capabilities []string, tool string) ([]*agentdom.Agent, error)

FindAvailableWithCapacity finds agents with available job capacity for load balancing.

func (*AgentService) GetAgent

func (s *AgentService) GetAgent(ctx context.Context, tenantID, agentID string) (*agentdom.Agent, error)

GetAgent retrieves an agent by ID.

func (*AgentService) GetAvailableCapabilitiesForTenant

func (s *AgentService) GetAvailableCapabilitiesForTenant(ctx context.Context, tenantID shared.ID) (*TenantAvailableCapabilitiesOutput, error)

GetAvailableCapabilitiesForTenant returns all capabilities available to a tenant. This aggregates capabilities from the tenant's own agents (if status=active and health=online).

func (*AgentService) GetPlatformStats

func (s *AgentService) GetPlatformStats(ctx context.Context, tenantID shared.ID) (*PlatformStatsOutput, error)

GetPlatformStats returns aggregate statistics for platform agents accessible to the tenant.

func (*AgentService) GetTenantAgentStats

func (s *AgentService) GetTenantAgentStats(ctx context.Context, tenantID string) (*agentdom.TenantAgentStats, error)

GetTenantAgentStats returns aggregate statistics for the tenant's agents. Computed via SQL aggregation in a single round-trip — replaces the previous client-side .filter().length pattern that only saw the current page of results.

func (*AgentService) HasCapability

func (s *AgentService) HasCapability(ctx context.Context, tenantID shared.ID, capability string) (bool, error)

HasCapability checks if a tenant has access to a specific capability.

func (*AgentService) Heartbeat

func (s *AgentService) Heartbeat(ctx context.Context, input AgentHeartbeatInput) error

Heartbeat updates agent status from heartbeat.

func (*AgentService) IncrementStats

func (s *AgentService) IncrementStats(ctx context.Context, agentID shared.ID, findings, scans, errors int64) error

IncrementStats increments agent statistics.

func (*AgentService) ListAgents

ListAgents lists agents with filters.

func (*AgentService) RegenerateAPIKey

func (s *AgentService) RegenerateAPIKey(ctx context.Context, tenantID, agentID string, auditCtx *auditapp.AuditContext) (string, error)

RegenerateAPIKey generates a new API key for an agent.

func (*AgentService) ReleaseJob

func (s *AgentService) ReleaseJob(ctx context.Context, agentID shared.ID) error

ReleaseJob releases a job slot on an agent.

func (*AgentService) RenewAPIKey added in v0.4.0

func (s *AgentService) RenewAPIKey(ctx context.Context, a *agentdom.Agent) (string, *time.Time, error)

RenewAPIKey lets an already-authenticated agent rotate its own credential.

Unlike RegenerateAPIKey (an admin action, tenant+id scoped), this is the self-service, kubelet-style renewal an agent drives itself: it presents its current key, gets authenticated by AuthenticateByAPIKey upstream, and calls this to mint a fresh one. The building block for auto-rotating credentials.

The passed agent is the one resolved from the presented key. We re-read it by ID so a concurrent admin status change (disable/revoke) is not clobbered by a stale in-memory copy, and re-check CanAuthenticate to refuse renewal for an agent that was disabled/revoked in the auth→renew window. Works for both tenant and platform (nil-tenant) agents since the lookup/update key on ID.

When a key TTL is configured (SetKeyTTL), the new key carries a fresh expiry and the agent is expected to renew again before it lapses; otherwise the key never expires (today's behavior). Returns the new key and its expiry (nil = never expires) so the agent can schedule its next renewal.

func (*AgentService) RevokeAgent

func (s *AgentService) RevokeAgent(ctx context.Context, tenantID, agentID, reason string, auditCtx *auditapp.AuditContext) (*agentdom.Agent, error)

RevokeAgent permanently revokes an agent's access (admin action).

func (*AgentService) SetAPIKeyRepository added in v0.4.0

func (s *AgentService) SetAPIKeyRepository(repo agentdom.APIKeyRepository)

SetAPIKeyRepository wires the multi-key store (RFC-014 Phase 3). Optional; when nil the service uses only the single inline key per agent.

func (*AgentService) SetKeyTTL added in v0.4.0

func (s *AgentService) SetKeyTTL(ttl time.Duration)

SetKeyTTL configures how long a self-renewed API key stays valid. Zero (the default) disables expiry — renewed keys never expire. Should be called once at boot before the service handles traffic.

func (*AgentService) SetLoadBalancingWeights added in v0.4.0

func (s *AgentService) SetLoadBalancingWeights(w agentdom.LoadBalancingWeights)

SetLoadBalancingWeights configures the weights used to compute the persisted load_score on each heartbeat. Call once at boot. An all-zero weight set is ignored so a misconfiguration cannot flatten every agent's score to 0.

func (*AgentService) SetPepper

func (s *AgentService) SetPepper(pepper string)

SetPepper configures the HMAC pepper used by the API-key hash. Empty string disables peppering (backward-compat with pre-existing SHA-256 hashes). Should be called once at boot before the service handles any traffic.

func (*AgentService) UpdateAgent

func (s *AgentService) UpdateAgent(ctx context.Context, input UpdateAgentInput) (*agentdom.Agent, error)

UpdateAgent updates an agent.

func (*AgentService) UpdateHeartbeat

func (s *AgentService) UpdateHeartbeat(ctx context.Context, agentID shared.ID, data AgentHeartbeatData) error

UpdateHeartbeat updates agent metrics from heartbeat.

type AgentTemplateData

type AgentTemplateData struct {
	Agent       *agentdom.Agent
	APIKey      string // May be empty if not freshly created/regenerated
	BaseURL     string // Public API URL agents should connect to
	GeneratedAt string // RFC3339 timestamp
}

AgentTemplateData is the data passed to every agent config template.

type CreateAgentInput

type CreateAgentInput struct {
	TenantID          string   `json:"tenant_id" validate:"required,uuid"`
	Name              string   `json:"name" validate:"required,min=1,max=255"`
	Type              string   `json:"type" validate:"required,oneof=runner worker collector sensor"`
	Description       string   `json:"description" validate:"max=1000"`
	Capabilities      []string `json:"capabilities" validate:"max=20,dive,max=50"`
	Tools             []string `json:"tools" validate:"max=20,dive,max=50"`
	ExecutionMode     string   `json:"execution_mode" validate:"omitempty,oneof=standalone daemon"`
	MaxConcurrentJobs int      `json:"max_concurrent_jobs" validate:"omitempty,min=1,max=100"`
	// Audit context (optional, for audit logging)
	AuditContext *auditapp.AuditContext `json:"-"`
}

CreateAgentInput represents the input for creating an agent.

type CreateAgentOutput

type CreateAgentOutput struct {
	Agent  *agentdom.Agent `json:"agent"`
	APIKey string          `json:"api_key"` // Only returned on creation
}

CreateAgentOutput represents the output after creating an agent.

type ListAgentsInput

type ListAgentsInput struct {
	TenantID      string   `json:"tenant_id" validate:"required,uuid"`
	Type          string   `json:"type" validate:"omitempty,oneof=runner worker collector sensor"`
	Status        string   `json:"status" validate:"omitempty,oneof=active disabled revoked"`      // Admin-controlled
	Health        string   `json:"health" validate:"omitempty,oneof=unknown online offline error"` // Automatic
	ExecutionMode string   `json:"execution_mode" validate:"omitempty,oneof=standalone daemon"`
	Capabilities  []string `json:"capabilities"`
	Tools         []string `json:"tools"`
	Search        string   `json:"search" validate:"max=255"`
	HasCapacity   *bool    `json:"has_capacity"` // Filter by agents with available capacity
	Page          int      `json:"page"`
	PerPage       int      `json:"per_page"`
}

ListAgentsInput represents the input for listing agents.

type PlatformStatsOutput

type PlatformStatsOutput struct {
	Enabled         bool
	MaxTier         string
	AccessibleTiers []string
	MaxConcurrent   int
	MaxQueued       int
	CurrentActive   int
	CurrentQueued   int
	AvailableSlots  int
	TierStats       map[string]PlatformTierStats
}

PlatformStatsOutput represents the output for platform stats.

type PlatformTierStats

type PlatformTierStats struct {
	TotalAgents    int
	OnlineAgents   int
	OfflineAgents  int
	TotalCapacity  int
	CurrentLoad    int
	AvailableSlots int
}

PlatformTierStats represents statistics for a single platform agent tier.

type RenderedTemplates

type RenderedTemplates struct {
	YAML   string `json:"yaml"`
	Env    string `json:"env"`
	Docker string `json:"docker"`
	CLI    string `json:"cli"`
}

RenderedTemplates is the output of rendering all templates for one agent.

type SelectAgentRequest

type SelectAgentRequest struct {
	TenantID     shared.ID
	Capabilities []string
	Tool         string
	Region       string // Preferred region
	Mode         AgentSelectionMode
	AllowQueue   bool // If true, return queue info instead of error when no agent available
}

SelectAgentRequest represents a request to select an agent for a job.

type SelectAgentResult

type SelectAgentResult struct {
	Agent   *agentdom.Agent
	Queued  bool
	Message string
}

SelectAgentResult represents the result of agent selection.

type TenantAvailableCapabilitiesOutput

type TenantAvailableCapabilitiesOutput struct {
	Capabilities []string `json:"capabilities"` // Unique capability names available to tenant
	TotalAgents  int      `json:"total_agents"` // Total number of online agents
}

TenantAvailableCapabilitiesOutput represents the output for available capabilities.

type UpdateAgentInput

type UpdateAgentInput struct {
	TenantID          string   `json:"tenant_id" validate:"required,uuid"`
	AgentID           string   `json:"agent_id" validate:"required,uuid"`
	Name              string   `json:"name" validate:"omitempty,min=1,max=255"`
	Description       string   `json:"description" validate:"max=1000"`
	Capabilities      []string `json:"capabilities" validate:"max=20,dive,max=50"`
	Tools             []string `json:"tools" validate:"max=20,dive,max=50"`
	Status            string   `json:"status" validate:"omitempty,oneof=active disabled revoked"` // Admin-controlled
	MaxConcurrentJobs *int     `json:"max_concurrent_jobs" validate:"omitempty,min=1,max=100"`
	// Audit context (optional, for audit logging)
	AuditContext *auditapp.AuditContext `json:"-"`
}

UpdateAgentInput represents the input for updating an agent.

Jump to

Keyboard shortcuts

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