Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Environment:AISecurityLab Hackagent Asyncio

From Leeroopedia
Knowledge Sources
Domains Infrastructure, Security_Testing, Concurrency
Last Updated 2026-10-29 00:00 GMT

Overview

Python 3.10+ runtime with the asyncio event loop, providing the concurrent execution foundation for all HackAgent campaign operations.

Description

This environment provides the standard CPython runtime with the asyncio standard library as the concurrency backbone for HackAgent. Every campaign operation — preflight checks, attack execution, judge panel evaluation, guardrail classification, result tracking, and panel audits — is built on async/await coroutines. The runner uses asyncio.gather for concurrent judge votes, asyncio.Semaphore for shared concurrency limits across attacks/targets/judges, asyncio.to_thread for blocking store I/O, and asyncio.wait_for for per-attack timeouts.

A synchronous entry point (run_campaign) is provided via run_coroutine_blocking, which uses asyncio.run directly when no loop is running, or spawns a dedicated bridge thread with its own event loop when called from inside an already-running loop (e.g., Jupyter notebooks).

The runtime requires Python >= 3.10 and the core dependencies listed in pyproject.toml. No GPU or special hardware is needed — HackAgent drives external LLM backends over HTTP.

Usage

Use this environment for any HackAgent campaign execution — running run_campaign or arun_campaign, calling preflight, Panel.aevaluate, GuardedModel.acomplete, IterativeAttack.run, RunTracker.record, or aaudit_configured_panel. It is the mandatory prerequisite for every async implementation in the orchestrator, evaluation, models, and attacks packages.

System Requirements

Category Requirement Notes
OS Linux / macOS / Windows Cross-platform; Windows excludes some dev-only extras (vllm, fastapi, transformers)
Hardware Any CPU No GPU required; LLM backends are remote over HTTP
Disk 100 MB + run outputs Calibration datasets cache to ~/.cache/hackagent/calibration/
Runtime Python >= 3.10 pyproject.toml: requires-python = ">=3.10"
Network HTTP access to LLM endpoints Target models, judges, and attack role models are reached over HTTP

Dependencies

System Packages

  • Python 3.10+ (CPython)
  • git (for clone/development)
  • ollama (optional — only for local Ollama-backed examples)

Python Packages

  • httpx >= 0.27.0
  • pydantic[email] >= 2.0
  • litellm >= 1.69.2
  • openai >= 1.0.0
  • rich >= 14.0.0
  • click >= 8.1.0
  • pyyaml >= 6.0.0
  • python-dateutil >= 2.8.0

Optional extras (install with pip install hackagent[tui|web|browser|rag|vision|hf]):

  • textual >= 1.0.0 (TUI interface)
  • flask >= 3.1.3 (web dashboard)
  • playwright >= 1.40 (browser model)
  • faiss-cpu >= 1.13.2, numpy >= 1.26 (RAG/embedding)
  • Pillow >= 10.0.0 (vision)
  • datasets >= 2.14.0 (HuggingFace dataset provider)

Credentials

The following environment variables may be set (all optional for local mode):

  • HACKAGENT_API_KEY: HackAgent cloud API key. When set, runs persist to the remote backend; without it, runs use local SQLite.
  • HACKAGENT_BASE_URL: Remote API base URL (default: https://api.hackagent.dev).
  • HACKAGENT_DB_PATH: Local SQLite database path (default: ~/.local/share/hackagent/hackagent.db).
  • OLLAMA_BASE_URL / OLLAMA_API_BASE / OLLAMA_HOST: Ollama endpoint override (default: http://localhost:11434).

Campaign-specific credentials (e.g., OPENAI_API_KEY, provider tokens) are injected via the campaign YAML's api_key_env field, which names the environment variable to read at runtime.

Quick Install

# Core install (asyncio is part of the Python stdlib)
pip install hackagent

# With optional extras
pip install hackagent[tui,web,rag,hf]

# Development install
pip install -e ".[dev]"

Code Evidence

Async runtime usage in runner.py:37 (import and core loop):

import asyncio
from collections.abc import Awaitable, Callable, Iterable, Mapping

Shared semaphores for concurrency control from runner.py:389-401:

@dataclass(frozen=True)
class _Limits:
    attack: asyncio.Semaphore
    target: asyncio.Semaphore
    judge: asyncio.Semaphore

    @classmethod
    def from_counts(cls, *, attack: int, target: int, judge: int) -> "_Limits":
        return cls(
            asyncio.Semaphore(attack),
            asyncio.Semaphore(target),
            asyncio.Semaphore(judge),
        )

Sync-to-async bridge from async_utils.py:12-29:

def run_coroutine_blocking(coro_factory: Callable[[], Awaitable[T]]) -> T:
    try:
        asyncio.get_running_loop()
    except RuntimeError:
        return asyncio.run(coro_factory())

    from concurrent.futures import ThreadPoolExecutor
    with ThreadPoolExecutor(max_workers=1) as pool:
        return pool.submit(lambda: asyncio.run(coro_factory())).result()

Concurrent judge evaluation from panel.py:230-241:

async def aevaluate(self, sample: Sample) -> Verdict:
    async def ask(judge: Any) -> JudgeVote:
        try:
            return await judge.avote(sample)
        except Exception as exc:
            return JudgeVote(judge=_judge_name(judge), error=f"Judge failed: {exc}")
    votes = await asyncio.gather(*(ask(judge) for judge in self.judges))
    return self._combine(list(votes))

Python version requirement from pyproject.toml:9:

requires-python = ">=3.10"

Common Errors

Error Message Cause Solution
RuntimeError: asyncio.run() cannot be called from a running event loop Calling run_campaign inside an async context without the bridge Use await arun_campaign() directly, or run_coroutine_blocking which handles nesting
Preflight failed: <model> (target): no answer within <N>s Target model endpoint unreachable or too slow Check endpoint URL, network, and connection.timeout in campaign YAML
ImportError: No module named 'textual' TUI extra not installed pip install hackagent[tui]
ValueError: Remote storage requires 'base_url' and 'api_key_env' Remote storage configured without credentials Set HACKAGENT_API_KEY or configure storage.api_key_env in campaign YAML
semaphore or gather not yielding (hang) Concurrency limits too restrictive (all default to 1) Increase execution.concurrency.{attack,target,judge} in campaign YAML

Compatibility Notes

  • Jupyter Notebooks: run_campaign detects a running event loop and spawns a bridge thread, so synchronous calls work inside notebooks. Prefer await arun_campaign() for cleaner stack traces.
  • Windows:' Core package installs and runs. Dev-only extras (vllm, fastapi[standard], transformers) are excluded on Windows via sys_platform != 'win32 markers in pyproject.toml.
  • Ollama: Local Ollama must be running (ollama serve) and have required models pulled. The CLI hackagent examples ollama auto-preflights and pulls missing models.
  • Python 3.13: Supported per classifiers, but some optional dependencies may lag behind on the newest version.

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment