Implementation:0xSteph Pentest ai run agent loop
| Knowledge Sources | |
|---|---|
| Domains | Security_Testing, LLM_Agents |
| Last Updated | 2026-10-23 12:00 GMT |
Overview
Concrete autonomous LLM reasoning loop that drives a penetration test by iteratively observing engagement state, proposing the next action, dispatching to a handler, and recording results with multiple safety nets.
Description
run_agent_loop is the core function of the autonomous agent mode. It replaces fixed-pipeline orchestration with an LLM-driven loop where the model decides each action based on engagement state.
The loop cycle:
- Observe: `memory.summary_for_llm()` produces a compact state snapshot
- Propose: `agent.decide_next_action(state)` returns an Action
- Dispatch: Action name maps to a registered handler in `_HANDLERS`
- Record: Handler returns an Observation that updates WorkingMemory
- Check: Termination conditions (finish, coverage, max_iter, cost_limit, LLM unavailable)
Safety nets ensure zero-finding runs are avoided:
- Early-finish detection: Finish below iteration floor with 0 findings → deterministic fallback
- Non-cooperative detection: N consecutive bad LLM responses → deterministic fallback
- Unproductive detection: Clean exit with 0 findings → deterministic fallback
- Cost limit: CostTracker.over_budget() stops spending immediately
- LLM unavailable: Falls through to deterministic mode if fallback_to_deterministic is True
Scope is exposed to handlers via contextvar for the duration of the run.
Usage
Import this when you need to:
- Run an engagement in autonomous agent mode (`--agent-mode`)
- Drive a penetration test with LLM-driven action selection
- Implement a custom LLM agent that follows the LLMAgent Protocol
Code Reference
Source Location
- Repository: pentest-ai
- File: engine/agent_loop.py
Signature
ExitReason = Literal[
"finished", "max_iterations", "coverage", "cost_limit",
"llm_unavailable", "deterministic", "llm_non_cooperative",
"llm_finished_too_early", "llm_unproductive",
]
@dataclass
class Action:
name: str
args: dict[str, Any] = field(default_factory=dict)
rationale: str = ""
@dataclass
class Observation:
action_name: str
success: bool
findings_added: int = 0
endpoints_added: int = 0
auth_added: int = 0
raw: dict[str, Any] = field(default_factory=dict)
error: str = ""
normalized: NormalizedResult | None = None
class LLMAgent(Protocol):
async def decide_next_action(self, state: dict[str, Any]) -> Action: ...
async def run_agent_loop(
agent: LLMAgent,
memory: WorkingMemory,
config: LoopConfig | None = None,
) -> WorkingMemory:
"""Drive the engagement to completion via the LLM agent."""
Import
from engine.agent_loop import run_agent_loop, Action, Observation, LLMAgent, LoopConfig, register_handler, ExitReason
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| agent | LLMAgent | Yes | Anything implementing decide_next_action(state) -> Action |
| memory | WorkingMemory | Yes | Per-engagement state object |
| config | None | No | Termination + safety knobs (default: LoopConfig()) |
Outputs
| Name | Type | Description |
|---|---|---|
| returns | WorkingMemory | Same memory object with state updated; exit_reason set |
Usage Examples
Running the Agent Loop
from engine.agent_loop import run_agent_loop, LoopConfig
from engine.working_memory import make_working_memory
from engine.scope import build_enforcer
# 1. Initialize working memory and config
memory = make_working_memory("eng-123", "https://app.example.com")
config = LoopConfig(
max_iterations=50,
coverage_threshold=0.8,
scope=build_enforcer("https://app.example.com"),
)
# 2. Run the loop with an LLMAgent implementation
memory = await run_agent_loop(my_llm_agent, memory, config)
print(f"Exit reason: {memory.exit_reason}")
print(f"Findings: {len(memory.findings)}")