vxcontrol/pentagi
Self-hosted Go and React pentest platform where a primary LLM agent plans subtasks and delegates to specialist agents in a Kali container.
Overview
PentAGI is a self-hosted web application for running LLM-driven penetration tests. A user opens a flow in the React UI and describes the job in plain language. The Go backend then creates a Docker worker container for that flow, by default from a Kali image, and runs a team of role-specific LLM agents against it. Everything is persisted to PostgreSQL: tasks, subtasks, every message chain, tool call, terminal line and search. The UI follows progress through GraphQL subscriptions.
The backend is plain Go. It uses langchaingo for the LLM and message types, gqlgen for the API and sqlc for database access. Thirteen provider types are supported, from OpenAI, Anthropic, Gemini and Bedrock to Ollama and any OpenAI-compatible endpoint, with per-agent-role model settings. Optional add-ons include pgvector memory, a Graphiti/Neo4j knowledge graph, Langfuse tracing, an OpenTelemetry stack and a separate scraper container for the browser tool.
The design is a planner-executor hierarchy with fixed roles. Code decides who may call whom. The model decides the plan and every command. Isolation engineering is strong. Engagement scope is not enforced anywhere: the prompts declare every action pre-authorised.
Architecture
flowchart TD
UI["React UI"] -->|"GraphQL"| API["Go server (gqlgen)"]
API --> FW["flowWorker"]
FW --> TW["taskWorker"]
TW -->|"GenerateSubtasks / RefineSubtasks"| PLAN["generator / refiner agents"]
TW --> SW["subtaskWorker"]
SW --> PA["primary_agent chain"]
PA -->|"agent tools"| SPEC["pentester, coder, installer, searcher, memorist, adviser"]
SPEC --> TERM["terminal / file tools"]
TERM --> WORKER["Kali worker container"]
SPEC --> SRCH["web_search, browser"]
PA --> DB["PostgreSQL + pgvector"]
PA --> GR["Graphiti (optional)"]
TW --> REP["reporter agent"]
| Component | Path | Role |
|---|---|---|
| Flow controller | backend/pkg/controller/flow.go |
Builds a flow worker, provider and tool executor, runs the input loop |
| Task / subtask workers | backend/pkg/controller/task.go, subtask.go |
Pop subtasks, run the agent chain, refine the plan, write the result |
| Flow provider | backend/pkg/providers/provider.go, handlers.go |
Subtask generation and refinement, agent handlers, task report |
| Agent loop | backend/pkg/providers/performer.go |
performAgentChain: call, run tools, summarise, repeat |
| Tool executors | backend/pkg/tools/tools.go, executor.go, registry.go |
Per-role tool sets, barrier tools, result storage |
| Terminal and files | backend/pkg/tools/terminal.go |
Docker exec and tar copy into the worker container |
| Docker layer | backend/pkg/docker/ |
Worker spec, capabilities, networking, sandbox probe |
| Prompts | backend/pkg/templates/prompts/*.tmpl |
One system and one question template per role |
| Providers | backend/pkg/providers/<vendor>/, pconfig/ |
13 provider types and per-role model options |
How a request flows
- Create. The
createFlowmutation checks theflows.createpermission and requires a provider and an input (schema.resolvers.go). - Build the worker.
buildFlowWorkercreates the tool executor and the flow provider, which picks the title, language and Docker image. It wires the log providers, callsexecutor.Prepareto start the container, launches theworker()goroutine and submits the first input (flow.go). - Plan. Each input becomes a task. The
generatoragent writes the subtask list (GenerateSubtasks, provider.go), capped byTasksNumberLimit = 15. - Execute subtasks.
taskWorker.Runpops one subtask at a time and runs it. After each subtask it asks therefineragent to rewrite the remaining plan (task.go).subtaskWorker.RuncallsPerformAgentChainand maps the result to finished, waiting or failed (subtask.go). - Agent chain.
PerformAgentChainbuilds the primary agent’s handlers for adviser, coder, installer, memorist, pentester and searcher (provider.go). It then entersperformAgentChain. - Loop. Each iteration compacts the chain to fit the window, calls the model with retries, appends the AI message, runs every tool call, appends the results and summarises. A barrier tool (
done,ask, or a specialist’shack_result/code_result) ends the chain. A reply with no tool call goes to thereflectoragent, which pushes the model back to tools. Iterations are capped at 100 for general agents and 20 for limited ones, and three iterations before the cap the reflector is told to wind down (performer.go). - Delegation. A call to
pentesterrenders the pentester prompt and runs a nested chain with its own executor. That executor hasterminal,file, browser, search and memory tools, plus calls to coder, installer, adviser and memorist.hack_resultis its barrier (tools.go). - Report. When the queue empties,
writeResultasks thereporteragent for the task write-up and stores it as a Markdown report message (task.go). A report can also be requested on demand while a task is still running.
Key components
Roles and delegation
The roles are fixed in code. primary_agent orchestrates. generator and refiner plan. pentester, coder, installer, searcher, memorist, adviser and enricher are specialists. reporter, summarizer, reflector and tool_call_fixer are helpers. Each specialist is exposed to its caller as a tool. The handler renders that role’s templates and runs a fresh nested performAgentChain, so a specialist is a scoped sub-conversation with its own tool set rather than a peer agent. There is also an interactive assistant mode, a chat that can optionally call the same agents.
Tools
The registry defines about 40 tool names in barrier, agent, environment, search and memory groups (registry.go). Security tooling is not wrapped. The pentester runs CLI tools through terminal, which uses the Docker exec API inside the worker, with a configurable timeout (TERMINAL_TOOL_TIMEOUT, default 1200 s) and a hard ceiling (terminal.go). web_search walks a per-mode fallback chain over the configured engines. Its exploit mode queries an exploit index first (web_search.go). A repeatingDetector stops the model from issuing the same call over and over.
State and memory
Relational state covers flows, tasks, subtasks, message chains (with token and cost columns), tool calls, terminal logs and agent logs. That makes a flow resumable after a restart (LoadFlowWorker) and fully auditable. Results from selected tools are split into 2,000-character chunks, passed through an anonymising replacer and embedded into pgvector (executor.go). Agents recall them with search_in_memory, search_guide, search_answer and search_code. With Graphiti enabled, agent responses and tool executions are also written to a temporal knowledge graph.
Findings
There is no findings model. Results are the prose that specialists return through hack_result, which the primary agent combines and the reporter agent turns into a Markdown task report. Nothing deduplicates findings, scores severity in a structured way, or re-runs a proof of concept. The raw tool-call and terminal logs are the evidence trail.
Scope and safety controls
- No scope enforcement. There is no target list, scope file or egress filter. The primary, generator and installer prompts open with an “authorization framework” that states every task is pre-authorised, requires no confirmation, and must not include authorisation checks (primary_agent.tmpl). The user’s free-text input is the only definition of the engagement.
- Human in the loop is off by default.
ASK_USERdefaults tofalse(config.go). When it is enabled, the primary agent gets anaskbarrier that parks the flow until the user replies (tools.go). The user can also stop a flow from the UI. - Container hardening is real. Workers drop all capabilities and add back an explicit list.
NET_ADMINis added only withDOCKER_NET_ADMIN, andSYS_ADMIN/SYS_MODULEare never added (worker_spec.go). Containers get a 2,048-PID limit and rotated logs (client.go).DOCKER_ALLOWED_IMAGESandDOCKER_IMAGE_SELECTION_MODE=fixedlimit the image the model may choose. - Docker access for agents is guarded. With
DOCKER_INSIDE, workers get a Docker daemon of their own.decideSandboxdisables that access if no dedicatedDOCKER_INSIDE_HOSTis set, or if the policy probe finds the daemon is PentAGI’s own or accepts host-escape requests (sandbox.go). The probe runs only whenDOCKER_INSIDE_POLICY_TESTSis on. Otherwise it only logs a warning. - Exposure to watch. The backend container mounts the host Docker socket and runs as root. In bridge mode each flow’s worker ports are published on
DOCKER_PUBLIC_IP, which defaults to0.0.0.0. Host network mode gives workers the host’s interfaces.
Extending it
- Prompts. Every role’s system and question template is a Go template in
pkg/templates/prompts/. Users can store their own overrides, andnewUserPrompterlays these over the defaults for each flow. - Providers and models. Add a provider type in
pkg/providers/registry.go, or use thecustomOpenAI-compatible provider with a YAML model config.pconfigmaps each agent role to its own model and options. - External functions. Flows accept user-defined functions with JSON schemas, called over HTTP as extra tools.
- Search backends. Engines live under
pkg/tools/searchers/. Each one becomes available when its key or URL is configured. - Images. The pentest image is configurable. By default the model picks an image per flow (the
image_chooserprompt), unless selection is fixed or restricted by an allowlist.
Running it
- Docker Compose is the primary deployment:
pentagi(backend plus static UI on 8443, bound to127.0.0.1by default),pgvectorandscraper. Separate compose files add Langfuse, Graphiti and an observability stack. An interactive installer (backend/cmd/installer) writes the.env. - At least one LLM provider key is required, plus an embedding endpoint for vector memory. Search engine keys are optional.
- For untrusted workloads, run workers against a separate Docker daemon (
DOCKER_INSIDE_HOSTwith policy tests) and setDOCKER_NETWORK/DOCKER_PUBLIC_IPdeliberately. - The helper binaries
ctester,ftesterandetesterexercise provider configs, individual tool functions and the embedding store.
Strengths and caveats
- Strength: full audit trail. Every chain, tool call, terminal byte and search is in PostgreSQL. A flow can be replayed, inspected in the UI and resumed after a restart.
- Strength: deliberate container isolation. It drops all capabilities and adds back an allowlist, caps PIDs, offers an image allowlist, and tests any nested Docker access at startup before granting it.
- Strength: model flexibility. Thirteen provider types and per-role models let cheap models do summarisation and search while a strong model plans.
- Caveat: scope is the operator’s job. There is no allowlist, and the prompts explicitly suppress authorisation checks. The default deployment has no human approval step.
- Caveat: no structured findings. Output is a Markdown narrative with no dedupe, severity schema, SARIF or PoC validation, so it is weak for CI or triage pipelines.
- Caveat: heavy footprint. A root-run backend with the host Docker socket, PostgreSQL, a scraper and optional graph and observability stacks is a platform deployment, not a CLI.
- Caveat: cost is bounded only by iteration caps. Usage and cost are recorded per chain, but there is no spend budget that stops a flow.
Sources: code at cffed94, verified Q&A.
How it answers the Open-source AI pentest and offensive-security agents questions
Each answer was drafted by a code-reading agent at commit cffed94. Its citations were checked mechanically. Compare with the other open-source ai pentest and offensive-security agents →
How is the agent loop and planning implemented?
answeredThe agent loop is structured as a three-tier hierarchy — flow → task → subtask — running inside a single backend process with Go-style concurrency (goroutines/channels).
Multi-agent, not single-agent. This is a role-based crew, not a single agent. The MsgchainType enum defines 15 agent roles (pkg/database/models.go:197-212): primary_agent orchestrates everything, generator/refiner plan subtasks, and specialist agents (pentester, coder, searcher, installer, memorist, adviser, enricher, reporter, summarizer, tool_call_fixer, reflector) each handle one dimension. An assistant (interactive chat) also exists as a separate role.
Task planning and decomposition. When user input arrives, taskWorker.Run() (pkg/controller/task.go:341-376) pops subtasks from a queue generated by the generator agent (via stc.GenerateSubtasks). After each subtask completes, the refiner agent is called (stc.RefineSubtasks, pkg/controller/task.go:366) to re-plan remaining subtasks. This generator/refiner pair is the planning loop — it creates an initial plan then revises it based on what actually happened.
Turn structure. Each subtask runs as an agent chain through performAgentChain() (pkg/providers/performer.go:58-279). The chain loops: call the LLM → execute tool calls → append results → summarize chain → repeat. The loop has iteration caps (maxGeneralAgentChainIterations=100, maxLimitedAgentChainIterations=20, pkg/providers/performer.go:37-39) and a repeatingDetector that aborts on consecutive identical tool calls. Barrier tools (done, ask) stop the loop early. A reflector agent steps in when the model returns text instead of a tool call.
Stop conditions. Subtasks complete on done/ask barrier calls or when the LLM returns no tool calls (triggering the reflector). Tasks complete when the subtask queue is empty or user input is awaited. The flow finishes by setting FlowStatusFinished after all tasks are done and a report is written.
How are security tools integrated and executed?
answeredSecurity tools are integrated as Docker-executed commands through a unified tool-calling layer, not as wrapper scripts on the host. The tool registry (pkg/tools/registry.go:11-54) defines 35+ tool names grouped into 7 types: Barrier (done, ask), Agent (pentester, coder, installer, searcher, memorist, adviser), Environment (terminal, file), SearchNetwork (browser, all search engines), and SearchVectorDb (search_in_memory, graphiti_search).
Terminal and file access. The terminal tool (pkg/tools/terminal.go) is the core environment interface. Commands execute inside Docker containers via the Docker exec API (ContainerExecCreate, line 228), not a host shell. The SandboxCommand() function wraps commands with a HUP-signal trap so they survive flow stops (pkg/docker/flow_commands.go:21-24). File read/write/edit use Docker's CopyFromContainer/CopyToContainer with tar streams (lines 433-560). All commands have configurable timeouts (default 1200s, max 3 hours, line 82-90).
Search engines. The web_search tool (pkg/tools/web_search.go) is the unified search orchestrator. It selects from 8 backends (Google, DuckDuckGo, Tavily, Firecrawl, Traversaal, Perplexity, Searxng, Sploitus) based on intent mode: links, answer, research, or exploit. Each mode has a fallbackStrategy fallback chain (lines 82-109). Sploitus is a dedicated exploit/offensive-tool search engine (line 105, registry line 268-276). The orchestrator retries retryable errors up to 2 times per engine and walks the chain on failure.
Specialist agents as tools. Agent tools (pentester, coder, installer, etc.) are not direct tool executions but calls to sub-agents. When the primary agent calls pentester, the executor spawns a pentester sub-agent with its own tool set including terminal, browser, web_search, and hack_result barrier — that sub-agent does the actual work and returns a synthesized result.
External functions. The system also supports user-defined external functions (ExternalFunction in pkg/tools/tools.go:63-69) registered via the API, which are called as HTTP APIs with JSON schemas.
How are scope, authorization and dangerous actions controlled?
answeredPentAGI implements safety through Docker sandboxing, capability dropping, and configuration-gated controls rather than target allowlists or scope files.
Docker sandbox isolation. Every flow runs inside a Docker container. The WorkerSpec() function (pkg/docker/worker_spec.go:18-26) creates containers with CapDrop: ["ALL"] and a carefully curated CapAdd allowlist (CHOWN, DAC_OVERRIDE, NET_RAW, SYS_PTRACE, etc.). SYS_ADMIN, SYS_MODULE, SYS_RAWIO, and SYS_BOOT are explicitly forbidden (line 30-31). NET_ADMIN is only added when DOCKER_NET_ADMIN is configured (line 39-41). The default pentest image is vxcontrol/kali-linux (pkg/config/config.go:67), but DOCKER_ALLOWED_IMAGES can restrict which images are usable. The binary also has an LLM_FALLBACK_PROVIDER config option.
Network isolation. Agents operate inside the Docker sandbox; the host Docker network is configurable via DOCKER_NETWORK. The DOCKER_INSIDE_* config options (lines 50-52) point sandbox containers at a separate Docker daemon, preventing agents from accessing the host daemon. DOCKER_INSIDE_POLICY_TESTS (line 60) optionally runs authorization policy tests before granting agent access.
Human-in-the-loop. The ASK_USER config flag (pkg/config/config.go:25) enables the ask barrier tool which pauses the subtask and waits for human input. When enabled, the primary agent's tool set includes AskUserToolName (pkg/tools/tools.go:1061-1065). The flow goes to Waiting status, and the system sends a subscription event; the human's response resumes the subtask.
Rate limiting and stop controls. There is no built-in API rate limiting per se, but server-side context cancellation (context.WithCancel) provides stop capability. The StopFlow tool (registry line 424-430) cancels the executing task context. ErrFlowStateGuard (pkg/tools/flow_manager.go:22) prevents state-conflicting tool calls from being retried with argument fixing. The repeatingDetector in the performer (performer.go:323-348) aborts chains that repeat the same tool call consecutively.
ask barrier (the only human checkpoint) is absent unless the operator enables it.How are findings validated and reported?
answeredThere is no automated finding-validation pipeline with PoC re-execution or second-agent cross-checking. Instead, findings emerge organically from the agent chain outputs and are compiled into markdown reports.
How findings surface. The specialist agents (pentester, coder) execute tests inside the Docker sandbox and report results through barrier tools: hack_result for penetration test findings, code_result for code output, maintenance_result for tool installation outcomes. These are stored as Agentlog entries and Msglog entries with type MsglogTypeReport, attributed by role (initiator/executor, pkg/database/models.go:870-880). The report is a summary produced by the reporter agent.
Report generation. At the end of a task, taskWorker.writeResult() (pkg/controller/task.go:382-422) calls Provider.GetTaskResult() to generate the write-up. The reporter agent produces a markdown report that is stored as MsglogTypeReport. Reports can also be requested on-demand via flowWorker.Report() (pkg/controller/flow.go:964-993), which supports up to 3 retry attempts with 20-second exponential backoff (lines 918-931). The report has a configurable budget (default 30 minutes, line 927).
Deduplication and false positive handling. The codebase does not implement explicit false-positive verification or PoC re-run validation. There is no second-agent cross-checker for findings. Duplicates are handled only at the vector-store retrieval level (MergeAndDeduplicateDocs() in memory.go and guide.go) — this is for memory retrieval, not finding deduplication. Subtask replanning via the refiner agent is the closest the system comes to "re-checking" — if a subtask fails, the refiner adjusts the plan and the new approach may re-examine the same target.
Report format. Reports are markdown (MsglogResultFormatMarkdown), stored in the Msglog table with type MsglogTypeReport. The Terminal/Task/ToolCall logs are all persisted for audit trail, but there is no specific "findings database" table — the engagement output is the prose report plus the raw execution logs.
How is engagement state and knowledge kept across a long run?
answeredEngagement state and knowledge are persisted across three primary stores: PostgreSQL (relational), pgvector (semantic memory), and optionally Graphiti (temporal knowledge graph).
Relational (PostgreSQL). Every action is logged in structured tables: Flow, Task, Subtask with status lifecycle (Created→Running→Waiting→Finished/Failed); Msgchain stores the full LLM conversation chain (messages JSON blob, plus token usage and cost); Toolcall records each tool call with args and result; Termlog captures terminal stdin/stdout/stderr; Agentlog tracks which agent role initiated/executed what. All models are in pkg/database/models.go. The status propagation chain flows upwards: subtask → task → flow (pkg/controller/subtask.go:216-231).
Semantic (pgvector). Tool results from terminal, file, search, and agent tools are automatically stored into the pgvector store via storeToolResult() (pkg/tools/executor.go:597-683). Results are split into chunks (2000-char recursive character splitter, lines 610-618), anonymized using a pattern-based replacer (IPs, domains, credentials), and embedded with the configured Embedder. Agents retrieve past findings through search_in_memory (memory tool), search_guide, search_answer, and search_code tools. Retrieval is by similarity search (cosine, threshold 0.2, limit 3, pkg/tools/memory.go:24-26).
Knowledge graph (Graphiti, optional). Agent responses and tool executions are optionally logged to a Graphiti temporal knowledge graph server over HTTP (pkg/graphiti/). Agent responses are stored via storeAgentResponseToGraphiti() (pkg/providers/performer.go:1011-1089) and tool executions via storeToolExecutionToGraphiti() starting at line 1092. Agents can query Graphiti using the graphiti_search tool with 7 search types (temporal window, entity relationships, diverse results, episode context, successful tools, etc.) — see registry.go:347-357.
Summarization and compaction. The performer chain loop calls compactChainForWindow() (performer.go:139-148) and SummarizeChain() (line 258) to compact long message chains when they exceed context windows. The summarizer is role-specific, driven by pkg/csum/ package.
Resumability. Flows can be loaded from the database on restart via LoadFlowWorker() (pkg/controller/flow.go:339-526), which restores tasks, subtasks, message chains, containers, and assistant workers.
Which models are supported and how are cost and context managed?
answeredPentAGI supports 13 provider types, all documented in the AllProviderTypes constant (pkg/providers/provider/provider.go:68-82): OpenAI, Anthropic, Gemini, Bedrock (AWS), Ollama, Custom (OpenAI-compatible), DeepSeek, GLM, Kimi, Qwen, MiniMax, Mistral, and xAI.
Provider architecture. Each provider has a registry entry in pkg/providers/registry.go:48-165 with a type, default name, Enabled gate (checks for API key env vars), NewConfig (creates default pconfig), New (constructor), and BuildConfig (from persisted data). OpenAI-compatible providers (DeepSeek, GLM, Kimi, Qwen, MiniMax, Mistral, xAI, Custom) use the shared openaicompat door module (pkg/providers/openaicompat/). Custom endpoints with LLM_SERVER_URL + LLM_SERVER_KEY allow connecting to any OpenAI-compatible backend. Federated (token-based) auth is supported for Anthropic (pkg/providers/routing.go:54-63).
Per-role model configuration. The pconfig package (pkg/providers/pconfig/config.go) provides per-agent-role model selection. flowProvider.Model(optAgentType) returns the model for a given role (primary_agent, pentester, coder, etc.). Each provider's models.yml ships predefined model-to-capability mappings (e.g., gpt-4 for primary agent, gpt-3.5-turbo for cheaper roles). The catalog system (bundledCatalogs in pkg/providers/catalog.go) lets operators see which shipped models are actually served by the configured endpoint.
Local models. Ollama fully supports local models via OLLAMA_SERVER_URL (pkg/config/config.go). Bedrock also supports locally hosted models via a custom server URL, and Custom endpoints work with any OpenAI-compatible local server (vLLM, LocalAI, etc.).
Cost and context management. Token usage (input, output, cache reads/writes) is tracked per Msgchain row (pkg/database/models.go:979-997) with cost fields (UsageCostIn, UsageCostOut). Chain summarization (compactChainForWindow in pkg/providers/performer.go:139-148) compacts conversation history when it exceeds context windows. The pkg/csum/ package handles chain summarization for LLM context management. pkg/providers/provider/limits.go likely holds per-model context window limits. Streaming supports real-time token output to the UI via subscription callbacks (streamCb in performer.go:516-548). There is no hard token budget per run; instead, iteration caps (100 for general agents, 20 for limited agents) bound total cost.