agent

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Jan 5, 2026 License: MIT Imports: 40 Imported by: 0

Documentation

Overview

File: internal/agent/agent.go

internal/agent/analysis_executor.go

internal/agent/codebase_executor.go

internal/agent/executors.go

internal/agent/humanoid_executor.go

internal/agent/interfaces.go

internal/agent/kg_adapter.go

internal/agent/llm_mind.go

File: internal/agent/long_term_memory.go

internal/agent/models.go

internal/agent/signup_executor.go

Index

Constants

View Source
const (
	FlagCritical      = "IS_CRITICAL"
	FlagRedundant     = "IS_REDUNDANT"
	FlagError         = "IS_ERROR"
	FlagVulnerability = "IS_VULNERABILITY"
)

Heuristic flags for classifying observations.

Variables

View Source
var (
	ErrConfigIsNil            = errors.New("config must not be nil")
	ErrProvidersNil           = errors.New("providers must not be nil")
	ErrEmbeddedAssetsMissing  = errors.New("failed to load embedded JavaScript assets")
	ErrEssentialSecListsEmpty = errors.New("one or more essential SecLists files are empty or failed to load")
)

Define standard errors.

View Source
var NewGraphStoreFromConfig = func(
	ctx context.Context,
	cfg config.KnowledgeGraphConfig,
	pool *pgxpool.Pool,
	logger *zap.Logger,
) (GraphStore, error) {
	switch cfg.Type {
	case "postgres":
		if pool == nil {
			return nil, fmt.Errorf("PostgreSQL store requires a valid database connection pool")
		}
		return knowledgegraph.NewPostgresKG(pool, logger), nil
	case "in-memory":
		return knowledgegraph.NewInMemoryKG(logger)
	default:
		return nil, fmt.Errorf("unknown knowledge_graph type specified: %s", cfg.Type)
	}
}

NewGraphStoreFromConfig is a factory function that creates a GraphStore based on the provided configuration. It is implemented as a variable to allow for easy mocking in tests.

View Source
var NewLLMClient = llmclient.NewClient

NewLLMClient is a variable that points to the LLM client factory function. This allows for mocking the LLM client during testing.

Functions

This section is empty.

Types

type Action

type Action struct {
	ID        string `json:"id"`         // A unique identifier for this action instance.
	MissionID string `json:"mission_id"` // The ID of the mission this action is a part of.
	ScanID    string `json:"scan_id"`    // The parent scan ID for correlation.

	// Thought provides a step-by-step "chain of thought" from the LLM, showing
	// the reasoning process that led to this specific action. This is invaluable
	// for debugging and understanding the agent's behavior.
	Thought string `json:"thought,omitempty"`

	Type      ActionType             `json:"type"`               // The specific type of action to perform.
	Selector  string                 `json:"selector,omitempty"` // The primary CSS selector for UI-based actions.
	Value     string                 `json:"value,omitempty"`    // The value to be used (e.g., text to type, URL to navigate to).
	Metadata  map[string]interface{} `json:"metadata,omitempty"` // A flexible map for additional, action-specific parameters.
	Rationale string                 `json:"rationale"`          // A concise justification for why this action was chosen.
	Timestamp time.Time              `json:"timestamp"`          // The time the action was decided.
}

Action represents a single, concrete step decided upon by the agent's mind. It includes the type of action, all necessary parameters, and the agent's reasoning (thought process and rationale) behind the decision.

type ActionExecutor

type ActionExecutor interface {
	// Execute performs the action and returns the result of the execution.
	Execute(ctx context.Context, action Action) (*ExecutionResult, error)
}

ActionExecutor defines a standard interface for any component that can execute a specific type of action. This allows for a modular system where different executors handle different capabilities (e.g., browser interaction vs. codebase analysis). This interface is also implemented by the ExecutorRegistry.

type ActionHandler

type ActionHandler func(ctx context.Context, session schemas.SessionContext, action Action) error

ActionHandler is a function signature for a method that handles a specific type of browser action.

type ActionType

type ActionType string

ActionType is an enumeration of all possible actions the agent can decide to perform. This provides a structured vocabulary for the agent's capabilities.

const (
	// -- Environmental Interaction (Basic) --
	ActionNavigate     ActionType = "NAVIGATE"       // Navigates to a URL.
	ActionClick        ActionType = "CLICK"          // Clicks on a UI element.
	ActionInputText    ActionType = "INPUT_TEXT"     // Types text into an input field.
	ActionSubmitForm   ActionType = "SUBMIT_FORM"    // Submits a form.
	ActionScroll       ActionType = "SCROLL"         // Scrolls the page.
	ActionWaitForAsync ActionType = "WAIT_FOR_ASYNC" // Pauses for asynchronous activity to settle.

	// -- High-Level Humanoid Actions --
	ActionHumanoidDragAndDrop ActionType = "HUMANOID_DRAG_AND_DROP" // Performs a human-like drag-and-drop.

	// -- Security Analysis Actions (Active & IAST) --
	// These actions involve injecting payloads, manipulating the environment, or analyzing the live state.
	ActionAnalyzeTaint      ActionType = "ANALYZE_TAINT"       // (IAST/Taint) Taint analysis (XSS, Injection) on the current page state.
	ActionTestRaceCondition ActionType = "TEST_RACE_CONDITION" // (Active/TimeSlip) Tests an endpoint for race conditions (TOCTOU).

	// -- Authentication & Authorization Testing --
	ActionTestATO  ActionType = "TEST_ATO"  // (Active/ATO) Account Takeover: Tests login endpoints for credential stuffing/enumeration.
	ActionTestIDOR ActionType = "TEST_IDOR" // (Active/IDOR) Insecure Direct Object Reference: Compares resource access between sessions.

	// -- Security Analysis Actions (Passive & Static) --
	// These actions analyze artifacts (HAR, DOM, Headers) already collected.
	ActionAnalyzeHeaders ActionType = "ANALYZE_HEADERS" // (Passive/Headers) Analyzes HTTP security headers from collected traffic.
	ActionAnalyzeJWT     ActionType = "ANALYZE_JWT"     // (Passive/JWT) Analyzes captured JWTs for vulnerabilities.

	// -- Codebase Interaction --
	ActionGatherCodebaseContext ActionType = "GATHER_CODEBASE_CONTEXT" // Gathers static analysis context from the agent's own codebase.

	// -- Proactive Self-Improvement --
	ActionEvolveCodebase ActionType = "EVOLVE_CODEBASE" // Initiates the self-improvement (evolution) process.

	// -- High-Level, Complex Actions --
	// Complex tasks that might be decomposed into simpler actions by the executor or the Mind itself.
	ActionExecuteLoginSequence ActionType = "EXECUTE_LOGIN_SEQUENCE" // Executes a predefined or discovered login sequence.
	ActionSignUp               ActionType = "SIGN_UP"                // Executes a sign-up or registration sequence.
	ActionExploreApplication   ActionType = "EXPLORE_APPLICATION"    // Initiates a comprehensive crawl/exploration of the application scope.
	ActionFuzzEndpoint         ActionType = "FUZZ_ENDPOINT"          // Performs fuzzing against a specific API endpoint or form inputs.
	ActionDecideNextStep       ActionType = "DECIDE_NEXT_STEP"       // Ties the scan process into the agents ability to decide, plan, react, replan or reorganize.

	// -- Mission Control --
	ActionConclude ActionType = "CONCLUDE" // Concludes the current mission.
)

type Agent

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

Agent is the core orchestrator for an autonomous security mission. It integrates various components like the cognitive bus, mind (LLM), action executors, and memory systems to achieve a high-level objective.

func New

func New(ctx context.Context, mission Mission, globalCtx *core.GlobalContext, session schemas.SessionContext) (*Agent, error)

New creates and initializes a new Agent instance with all its required components, including the mind, cognitive bus, executors, and memory systems. It wires together all dependencies and prepares the agent for a mission.

func (*Agent) RunMission

func (a *Agent) RunMission(ctx context.Context) (*MissionResult, error)

RunMission starts the agent's main operational loop. It initiates the mind's cognitive processes, starts the action execution loop, and manages the overall mission lifecycle. It blocks until the mission is completed, cancelled, or encounters a critical error.

type AgentState

type AgentState string

AgentState represents the agent's current phase within its OODA (Observe, Orient, Decide, Act) loop. This is used to track the agent's internal cognitive state.

const (
	StateInitializing AgentState = "INITIALIZING" // The agent is setting up its components.
	StateObserving    AgentState = "OBSERVING"    // The agent is processing new information from its environment.
	StateOrienting    AgentState = "ORIENTING"    // The agent is integrating new information and updating its world model.
	StateDeciding     AgentState = "DECIDING"     // The agent is reasoning about the next action to take.
	StateActing       AgentState = "ACTING"       // The agent has dispatched an action and is waiting for the result.
	StatePaused       AgentState = "PAUSED"       // The agent's cognitive loop is temporarily paused.
	StateCompleted    AgentState = "COMPLETED"    // The agent has successfully completed its mission.
	StateFailed       AgentState = "FAILED"       // The agent has encountered a critical, unrecoverable error.
)

type AnalysisExecutor

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

AnalysisExecutor is a specialized action executor responsible for running security analysis adapters. It translates high-level agent actions (like "analyze for taint") into specific analysis tasks, executes the corresponding adapter, and packages the results for the agent's mind.

func NewAnalysisExecutor

func NewAnalysisExecutor(globalCtx *core.GlobalContext, provider SessionProvider) *AnalysisExecutor

NewAnalysisExecutor creates a new instance of the AnalysisExecutor. It requires a logger, the global context for access to adapters, and a session provider to get the current browser session if needed.

func (*AnalysisExecutor) Execute

func (e *AnalysisExecutor) Execute(ctx context.Context, action Action) (*ExecutionResult, error)

Execute triggers the appropriate security analysis based on the incoming action. It handles session and artifact collection, prepares an AnalysisContext, runs the analysis adapter, and returns the findings and knowledge graph updates.

type BrowserExecutor

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

BrowserExecutor is a specialized executor for handling simple, non-interactive browser actions like navigating, submitting forms, and scrolling.

func NewBrowserExecutor

func NewBrowserExecutor(provider SessionProvider) *BrowserExecutor

NewBrowserExecutor creates and initializes a new BrowserExecutor, registering all of its action handlers.

func (*BrowserExecutor) Execute

func (e *BrowserExecutor) Execute(ctx context.Context, action Action) (*ExecutionResult, error)

Execute finds the correct handler for the given browser action and executes it. It retrieves the current browser session and returns a structured result, parsing any errors into a format the agent's mind can understand.

type CodebaseExecutor

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

CodebaseExecutor is a specialized executor for handling static analysis of the Go codebase.

func NewCodebaseExecutor

func NewCodebaseExecutor(projectRoot string) *CodebaseExecutor

NewCodebaseExecutor creates a new instance of the CodebaseExecutor.

func (*CodebaseExecutor) Execute

func (e *CodebaseExecutor) Execute(ctx context.Context, action Action) (*ExecutionResult, error)

Execute handles the GATHER_CODEBASE_CONTEXT action. It performs a deep static analysis of the Go codebase based on a package pattern (e.g., "./..."), gathers the source code of local packages, and identifies the definitions of all external dependencies they use. The result is a comprehensive text blob providing context to the agent's mind.

type CognitiveBus

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

CognitiveBus is the central nervous system of the agent, providing a pub/sub mechanism for decoupled communication between its components (e.g., Mind, Executors). It ensures that messages are delivered reliably and supports graceful shutdown by waiting for all messages to be processed.

func NewCognitiveBus

func NewCognitiveBus(logger *zap.Logger, bufferSize int) *CognitiveBus

NewCognitiveBus creates and initializes a new CognitiveBus with a specified buffer size for subscriber channels.

func (*CognitiveBus) Acknowledge

func (cb *CognitiveBus) Acknowledge(msg CognitiveMessage)

Acknowledge is called by a consumer after it has finished processing a message. This is crucial for the graceful shutdown process, as it allows the bus to track the number of in-flight messages.

func (*CognitiveBus) Post

func (cb *CognitiveBus) Post(ctx context.Context, msg CognitiveMessage) error

Post publishes a message to all subscribers of the message's type. This operation is blocking and will wait until the message can be delivered to all subscriber channels or until the context is cancelled. It provides backpressure.

func (*CognitiveBus) Shutdown

func (cb *CognitiveBus) Shutdown()

Shutdown initiates a graceful shutdown of the CognitiveBus. It stops accepting new messages, closes all subscriber channels, and waits for all in-flight messages to be acknowledged by consumers. This method is safe to call multiple times.

func (*CognitiveBus) Subscribe

func (cb *CognitiveBus) Subscribe(msgTypes ...CognitiveMessageType) (<-chan CognitiveMessage, func())

Subscribe creates a new subscription to one or more message types. It returns a read-only channel for receiving messages and a function to unsubscribe. If no message types are provided, it subscribes to all messages.

type CognitiveMessage

type CognitiveMessage struct {
	ID        string               // Unique identifier for the message.
	Timestamp time.Time            // Timestamp of when the message was created.
	Type      CognitiveMessageType // The type of the message (e.g., ACTION, OBSERVATION).
	Payload   interface{}          // The actual data payload.
}

CognitiveMessage is a generic container for all data that flows through the CognitiveBus. It includes metadata like an ID and timestamp, a type for routing, and a payload carrying the actual data.

type CognitiveMessageType

type CognitiveMessageType string

CognitiveMessageType defines the different types of messages that can be sent over the agent's internal cognitive bus.

const (
	MessageTypeAction      CognitiveMessageType = "ACTION"       // A message containing a new action to be executed.
	MessageTypeObservation CognitiveMessageType = "OBSERVATION"  // A message containing a new observation for the mind to process.
	MessageTypeStateChange CognitiveMessageType = "STATE_CHANGE" // A message indicating a change in the agent's state.
	MessageTypeInterrupt   CognitiveMessageType = "INTERRUPT"    // A message to interrupt the agent's current process.
)

type ControlExecutor

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

ControlExecutor handles high-level control actions like deciding next steps, adjusting tactics, and modifying agent behavior.

func NewControlExecutor

func NewControlExecutor(globalCtx *core.GlobalContext) *ControlExecutor

func (*ControlExecutor) Execute

func (e *ControlExecutor) Execute(ctx context.Context, action Action) (*ExecutionResult, error)

type Definition

type Definition struct {
	FilePath    string // The absolute path to the file containing the definition.
	StartOffset int    // The byte offset of the start of the definition.
	EndOffset   int    // The byte offset of the end of the definition.
}

Definition stores the precise location of a symbol's declaration, including the file path and the start and end offsets within that file. This allows for exact extraction of the source code for a given definition.

type ErrorCode

type ErrorCode string

ErrorCode provides a structured, enumerable way to represent specific error conditions that can occur during an agent's action execution. This allows the agent's mind (LLM) to reason about failures and implement intelligent recovery strategies.

const (
	// -- General Execution Errors --
	ErrCodeExecutionFailure  ErrorCode = "EXECUTION_FAILURE"   // A generic failure during the execution of an action.
	ErrCodeNotImplemented    ErrorCode = "NOT_IMPLEMENTED"     // The requested action or feature is not implemented.
	ErrCodeInvalidParameters ErrorCode = "INVALID_PARAMETERS"  // The parameters provided for the action were invalid.
	ErrCodeJSONMarshalFailed ErrorCode = "JSON_MARSHAL_FAILED" // Failed to marshal data to JSON.
	ErrCodeUnknownAction     ErrorCode = "UNKNOWN_ACTION_TYPE" // The action type is not recognized by any executor.
	ErrCodeFeatureDisabled   ErrorCode = "FEATURE_DISABLED"    // The requested feature is disabled in the configuration.
	ErrCodeTimeoutError      ErrorCode = "TIMEOUT_ERROR"       // An operation timed out.

	// -- Browser/DOM Errors --
	ErrCodeElementNotFound ErrorCode = "ELEMENT_NOT_FOUND" // The target DOM element could not be found.
	ErrCodeNavigationError ErrorCode = "NAVIGATION_ERROR"  // An error occurred while navigating to a URL.

	// ErrCodeHumanoidTargetNotVisible indicates that a target element was found in the DOM
	// but is not currently visible in the viewport (e.g., obscured or off-screen).
	ErrCodeHumanoidTargetNotVisible ErrorCode = "HUMANOID_TARGET_NOT_VISIBLE"

	// ErrCodeHumanoidGeometryInvalid indicates that the geometry of the target element is
	// invalid for interaction (e.g., it has zero width or height).
	ErrCodeHumanoidGeometryInvalid ErrorCode = "HUMANOID_GEOMETRY_INVALID"

	// ErrCodeHumanoidInteractionFailed is a general failure during a complex humanoid
	// interaction like a click or drag.
	ErrCodeHumanoidInteractionFailed ErrorCode = "HUMANOID_INTERACTION_FAILED"

	// -- Analysis & Security Testing Errors --
	ErrCodeAnalysisFailure ErrorCode = "ANALYSIS_FAILURE" // Failure within an analysis module.

	// -- Auth-specific errors --
	ErrCodeAuthWorkflowFailed   ErrorCode = "AUTH_WORKFLOW_FAILED"
	ErrCodeAuthCaptchaDetected  ErrorCode = "AUTH_CAPTCHA_DETECTED"
	ErrCodeAuthValidationFailed ErrorCode = "AUTH_VALIDATION_FAILED"

	// -- Evolution-specific errors --
	ErrCodeEvolutionFailure ErrorCode = "EVOLUTION_FAILURE" // An error occurred during the self-improvement/evolution process.

	// -- Internal System Errors --
	ErrCodeExecutorPanic ErrorCode = "EXECUTOR_PANIC" // An executor experienced an unrecoverable panic.
)

Constants defining the set of specific, structured error codes that can be returned by action executors. (Consolidated from errors.go)

func ParseBrowserError

func ParseBrowserError(err error, action Action) (ErrorCode, map[string]interface{})

ParseBrowserError is a utility function that inspects an error returned from a browser operation (BrowserExecutor or HumanoidExecutor) and classifies it into a structured `ErrorCode`. This provides the agent's mind with granular information about the nature of the failure, enabling intelligent error handling.

type EvolutionEngine

type EvolutionEngine interface {
	// Run initiates the full OODA (Observe, Orient, Decide, Act) loop for a
	// specific improvement objective, blocking until the process completes,
	// fails, or the context is cancelled.
	Run(ctx context.Context, objective string, targetFiles []string) error
}

EvolutionEngine defines the interface for the agent's proactive self-improvement subsystem.

type ExecutionResult

type ExecutionResult struct {
	Status          string                        `json:"status"` // "success" or "failed"
	ObservationType ObservationType               `json:"observation_type"`
	Data            interface{}                   `json:"data,omitempty"`
	ErrorCode       ErrorCode                     `json:"error_code,omitempty"`
	ErrorDetails    map[string]interface{}        `json:"error_details,omitempty"`
	Findings        []schemas.Finding             `json:"findings,omitempty"`   // Findings to be reported.
	KGUpdates       *schemas.KnowledgeGraphUpdate `json:"kg_updates,omitempty"` // Suggested updates for the knowledge graph.
}

ExecutionResult is a standardized structure for reporting the outcome of an action. It provides detailed feedback to the mind, including success/failure status, any discovered findings, suggested knowledge graph updates, and structured error information.

type ExecutorRegistry

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

ExecutorRegistry acts as a dispatcher for various types of agent actions. It holds a map of action types to their corresponding `ActionExecutor` implementations, ensuring that actions are routed to the correct handler. It also manages dynamic providers for browser sessions and humanoid controllers.

func NewExecutorRegistry

func NewExecutorRegistry(projectRoot string, globalCtx *core.GlobalContext, kg GraphStore) *ExecutorRegistry

NewExecutorRegistry creates and initializes a new registry, populating it with all the specialized executors (Browser, Codebase, Analysis, Humanoid).

func (*ExecutorRegistry) Execute

func (r *ExecutorRegistry) Execute(ctx context.Context, action Action) (*ExecutionResult, error)

Execute finds the appropriate executor for a given action and delegates execution to it. It returns an error if no executor is registered for the action type or if the action is a cognitive one that should be handled by the agent's main loop.

func (*ExecutorRegistry) GetHumanoidProvider

func (r *ExecutorRegistry) GetHumanoidProvider() HumanoidProvider

GetHumanoidProvider returns a thread-safe function that retrieves the current humanoid controller.

func (*ExecutorRegistry) GetSessionProvider

func (r *ExecutorRegistry) GetSessionProvider() SessionProvider

GetSessionProvider returns a thread-safe function that retrieves the current browser session. This allows executors to access the session without race conditions.

func (*ExecutorRegistry) UpdateHumanoidProvider

func (r *ExecutorRegistry) UpdateHumanoidProvider(provider HumanoidProvider)

UpdateHumanoidProvider is a thread-safe method for the Agent to dynamically set the function that provides access to the active humanoid controller.

func (*ExecutorRegistry) UpdateSessionProvider

func (r *ExecutorRegistry) UpdateSessionProvider(provider SessionProvider)

UpdateSessionProvider is a thread-safe method for the Agent to dynamically set the function that provides access to the active browser session.

type FileSystemSecListsLoader

type FileSystemSecListsLoader struct{}

FileSystemSecListsLoader implements SecListsLoader by reading from the local filesystem.

func NewFileSystemSecListsLoader

func NewFileSystemSecListsLoader() *FileSystemSecListsLoader

NewFileSystemSecListsLoader creates a new loader instance.

func (*FileSystemSecListsLoader) Load

func (l *FileSystemSecListsLoader) Load(cfg config.Interface) (*seclistsData, error)

Load reads and parses the necessary SecLists files based on the configuration.

type GraphStore

type GraphStore interface {
	AddNode(ctx context.Context, node schemas.Node) error
	GetNode(ctx context.Context, id string) (schemas.Node, error)
	AddEdge(ctx context.Context, edge schemas.Edge) error
	GetEdge(ctx context.Context, id string) (schemas.Edge, error)
	GetEdges(ctx context.Context, nodeID string) ([]schemas.Edge, error)
	GetNeighbors(ctx context.Context, nodeID string) ([]schemas.Node, error)
	QueryImprovementHistory(ctx context.Context, goalObjective string, limit int) ([]schemas.Node, error)
}

GraphStore defines a generic interface for interacting with a graph database, abstracting the specific implementation (e.g., in-memory, PostgreSQL). This is used by the agent and its components to interact with the knowledge graph.

type HumanoidExecutor

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

HumanoidExecutor is a specialized action executor for handling complex, interactive browser tasks that require human-like simulation, such as intelligent clicks, typing, and drag-and-drop. It delegates these tasks to the `humanoid.Humanoid` controller.

func NewHumanoidExecutor

func NewHumanoidExecutor(provider HumanoidProvider) *HumanoidExecutor

NewHumanoidExecutor creates and initializes a new HumanoidExecutor, registering all of its action handlers.

func (*HumanoidExecutor) Execute

func (e *HumanoidExecutor) Execute(ctx context.Context, action Action) (*ExecutionResult, error)

Execute retrieves the active humanoid controller, finds the correct handler for the given action, and executes it. It is responsible for parsing any resulting errors into a structured format that the agent's mind can use for decision-making.

type HumanoidProvider

type HumanoidProvider func() *humanoid.Humanoid

HumanoidProvider is a function type that acts as a dynamic getter for the active Humanoid controller instance. This allows the executor to be created before the humanoid controller is fully initialized.

type KnowledgeGraphClientAdapter

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

KnowledgeGraphClientAdapter adapts a GraphStore to the schemas.KnowledgeGraphClient interface.

func NewKnowledgeGraphClientAdapter

func NewKnowledgeGraphClientAdapter(store GraphStore) *KnowledgeGraphClientAdapter

NewKnowledgeGraphClientAdapter creates a new adapter.

func (*KnowledgeGraphClientAdapter) AddEdge

func (*KnowledgeGraphClientAdapter) AddNode

func (*KnowledgeGraphClientAdapter) GetEdge

func (*KnowledgeGraphClientAdapter) GetEdges

func (a *KnowledgeGraphClientAdapter) GetEdges(ctx context.Context, nodeID string) ([]schemas.Edge, error)

func (*KnowledgeGraphClientAdapter) GetNeighbors

func (a *KnowledgeGraphClientAdapter) GetNeighbors(ctx context.Context, nodeID string) ([]schemas.Node, error)

func (*KnowledgeGraphClientAdapter) GetNode

func (*KnowledgeGraphClientAdapter) QueryImprovementHistory

func (a *KnowledgeGraphClientAdapter) QueryImprovementHistory(ctx context.Context, goalObjective string, limit int) ([]schemas.Node, error)

type LLMMind

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

LLMMind is the cognitive core of the agent, implementing the `Mind` interface using a Large Language Model (LLM) for decision-making. It orchestrates the agent's behavior by running a continuous OODA (Observe, Orient, Decide, Act) loop. It receives observations from the cognitive bus, reasons about the state of the mission using a knowledge graph, decides on the next action, and posts that action back to the bus for execution.

func NewLLMMind

func NewLLMMind(
	logger *zap.Logger,
	client schemas.LLMClient,
	cfg config.AgentConfig,
	kg GraphStore,
	bus *CognitiveBus,
	ltm LTM,
) *LLMMind

NewLLMMind creates and initializes a new instance of the LLMMind. It sets up all the necessary components for the mind's operation, including the LLM client, knowledge graph, cognitive bus, and long-term memory.

func (*LLMMind) SetMission

func (m *LLMMind) SetMission(mission Mission)

SetMission provides the mind with its primary objective. It records the mission in the knowledge graph and triggers the first decision cycle.

func (*LLMMind) Start

func (m *LLMMind) Start(ctx context.Context) error

Start initiates the mind's main cognitive process, which consists of two primary loops: an observer loop that listens for new information and a decision loop that implements the OODA cycle. This method blocks until the context is cancelled or the mind is stopped.

func (*LLMMind) Stop

func (m *LLMMind) Stop()

Stop gracefully terminates the mind's cognitive loops and background processes. It is safe to call multiple times.

type LTM

type LTM interface {
	Start() // Starts any background processes for the LTM.
	Stop()  // Stops the LTM's background processes.
	// ProcessAndFlagObservation analyzes an observation and returns a map of
	// flags indicating its novelty or significance.
	ProcessAndFlagObservation(ctx context.Context, obs Observation) map[string]bool
}

LTM (Long-Term Memory) defines the interface for a module that provides the agent with memory and learning capabilities. It processes observations to identify patterns and flags novel or interesting events.

func NewLTM

func NewLTM(cfg config.LTMConfig, logger *zap.Logger) LTM

NewLTM creates a new Long-Term Memory module. The background cache cleanup process must be started by calling the Start() method.

type LoginExecutor

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

LoginExecutor is responsible for autonomously handling the login process. It uses heuristics to identify login forms and attempts to authenticate using provided credentials.

func NewLoginExecutor

func NewLoginExecutor(humanoidProvider HumanoidProvider, sessionProvider SessionProvider, kg GraphStore) *LoginExecutor

NewLoginExecutor creates a new LoginExecutor.

func (*LoginExecutor) Execute

func (e *LoginExecutor) Execute(ctx context.Context, action Action) (*ExecutionResult, error)

Execute performs the login action.

type Mind

type Mind interface {
	Start(ctx context.Context) error // Starts the mind's cognitive loop.
	Stop()                           // Gracefully stops the cognitive loop.
	SetMission(mission Mission)      // Assigns a new mission to the mind.
}

Mind represents the cognitive core of the agent. It is responsible for processing observations, reasoning about the current state, and deciding on the next course of action.

type Mission

type Mission struct {
	ID          string                 `json:"id"`          // A unique identifier for this mission.
	ScanID      string                 `json:"scan_id"`     // Correlates the mission to a parent scan operation.
	Objective   string                 `json:"objective"`   // The high-level goal for the agent to achieve.
	TargetURL   string                 `json:"target_url"`  // The primary URL target for the mission.
	Constraints []string               `json:"constraints"` // Any rules or limitations the agent must adhere to.
	Parameters  map[string]interface{} `json:"parameters"`  // Mission-specific parameters.
	StartTime   time.Time              `json:"start_time"`  // The time the mission was initiated.
}

Mission defines the high-level objective and parameters for an agent's operation. It encapsulates the "what" and "where" of the agent's task.

type MissionResult

type MissionResult struct {
	Summary   string
	Findings  []schemas.Finding
	KGUpdates *schemas.KnowledgeGraphUpdate
}

MissionResult encapsulates the final output of a completed mission, including a summary of findings and any knowledge graph updates.

type Observation

type Observation struct {
	ID             string          `json:"id"`               // A unique identifier for this observation.
	MissionID      string          `json:"mission_id"`       // The mission this observation belongs to.
	SourceActionID string          `json:"source_action_id"` // The ID of the action that generated this observation.
	Type           ObservationType `json:"type"`             // The category of the observation.
	Data           interface{}     `json:"data"`             // The raw data payload of the observation.
	Result         ExecutionResult `json:"result"`           // The status and metadata of the action's execution.
	Timestamp      time.Time       `json:"timestamp"`        // The time the observation was made.
}

Observation represents a piece of information that the agent's mind has received. It is the result of an action and forms the "Observe" part of the OODA loop. It contains the raw data and the execution status of the action that produced it.

type ObservationType

type ObservationType string

ObservationType categorizes the different kinds of information the agent can perceive from its environment or internal state.

const (
	ObservedNetworkActivity ObservationType = "NETWORK_ACTIVITY" // An observation of network traffic (e.g., from a HAR file).
	ObservedDOMChange       ObservationType = "DOM_CHANGE"       // An observation of a change in the Document Object Model.
	ObservedConsoleMessage  ObservationType = "CONSOLE_MESSAGE"  // An observation of a browser console message.
	ObservedTaintFlow       ObservationType = "TAINT_FLOW"       // An observation of a data flow from a source to a sink (IAST).
	ObservedCodebaseContext ObservationType = "CODEBASE_CONTEXT" // An observation containing source code and dependency information.
	ObservedEvolutionResult ObservationType = "EVOLUTION_RESULT" // The outcome of a self-improvement attempt.
	ObservedVulnerability   ObservationType = "VULNERABILITY"    // A specific security vulnerability has been identified.
	ObservedSystemState     ObservationType = "SYSTEM_STATE"     // An observation about the agent's own internal state or a system error.
	ObservedAnalysisResult  ObservationType = "ANALYSIS_RESULT"  // A generic wrapper for analysis output (e.g., Headers, JWT, Race Condition results).
	ObservedAuthResult      ObservationType = "AUTH_RESULT"      // The result of an authentication or authorization test (ATO, IDOR, Login).
)

type SecListsLoader

type SecListsLoader interface {
	Load(cfg config.Interface) (*seclistsData, error)
}

SecListsLoader defines the interface for loading SecLists data.

type SelfHealOrchestrator

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

SelfHealOrchestrator is the central coordinator for the entire autofix (self-healing) process. It manages the lifecycle of the watcher, analyzer, and developer components, and orchestrates the flow from panic detection to pull request creation.

func NewSelfHealOrchestrator

func NewSelfHealOrchestrator(
	logger *zap.Logger,
	cfg config.Interface,
	llmClient schemas.LLMClient,
) (*SelfHealOrchestrator, error)

NewSelfHealOrchestrator initializes and wires together all components of the self-healing system. It returns a fully configured orchestrator if the feature is enabled and all components initialize correctly, otherwise it returns nil.

func (*SelfHealOrchestrator) Start

func (o *SelfHealOrchestrator) Start(ctx context.Context)

Start activates the self-healing system by starting the log watcher and the main processing loop. This method is non-blocking.

func (*SelfHealOrchestrator) WaitForShutdown

func (o *SelfHealOrchestrator) WaitForShutdown()

WaitForShutdown blocks until the main control loop of the orchestrator has completed, ensuring a graceful shutdown.

type SessionProvider

type SessionProvider func() schemas.SessionContext

SessionProvider is a function type that acts as a dynamic getter for the currently active browser session. This allows components to be initialized before a session is available and to always access the most current session.

type SignUpExecutor

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

SignUpExecutor is responsible for autonomously handling the sign-up process.

func NewSignUpExecutor

func NewSignUpExecutor(humanoidProvider HumanoidProvider, sessionProvider SessionProvider, cfg config.Interface, loader SecListsLoader) (*SignUpExecutor, error)

NewSignUpExecutor creates a new SignUpExecutor. It accepts a SecListsLoader for dependency injection. If loader is nil, it defaults to FileSystemSecListsLoader.

func (*SignUpExecutor) Execute

func (e *SignUpExecutor) Execute(ctx context.Context, action Action) (*ExecutionResult, error)

Execute performs the sign-up action with a retry mechanism.

Jump to

Keyboard shortcuts

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