项目文件夹

文件
Gelei Deng ab5fbb4d90 feat: ship the durable multi-model autonomous PentestGPT runtime (#493)
* first refactor

* feat: dockerized tool with persistent Claude+Codex login + multi-model benchmark

Run the autonomous CTF/pentest tool in Docker with a one-time, persistent login for
BOTH Claude Code and Codex, and add a multi-model benchmark harness.

Backend (multi-model):
- Add `--backend {claude,codex}` to the CTF pipeline. CodexBackend (pentestgpt/core/
  backend.py) wraps unified_agent's Codex backend and translates its events into
  AgentMessages, so the same pipeline runs on Claude (opus/sonnet) or Codex
  (gpt-5.5/gpt-5.4-mini). Wired through config.backend, pipeline stage construction,
  and the CLI (+ PENTESTGPT_CODEX_EFFORT; greppable [CODEX_USAGE] under PENTESTGPT_BENCH=1).

Docker tool (tool-only image; the benchmark stays OUTSIDE the image):
- Extend Dockerfile: Codex CLI (@openai/codex) + openai_codex SDK + unified_agent/
  pentestgpt_agent/pentestgpt_legacy packages + gobuster/dirb + socat. Add .dockerignore
  (keeps creds/benchmark/workspace out of the build context).
- Persistent dual login (the hard part) — asymmetric by token model:
  * Claude: `setup-token` -> token stored in the pentestgpt-claude volume; entrypoint
    exports CLAUDE_CODE_OAUTH_TOKEN (setup-token does not write .credentials.json; macOS
    host creds live in the Keychain and can't be copied).
  * Codex: the container does its OWN `codex login` (NOT seeding -- ChatGPT refresh tokens
    are single-use, so a shared/copied login 401s on first refresh). The 127.0.0.1:1455
    OAuth callback is forwarded into the container via a socat hop (-p 1455:8455).
  * scripts/docker-login.sh is idempotent: checks logins live, logs in only the missing one(s).
- docker-compose codex-config volume (+ pinned names); entrypoint token-export + non-blocking
  preflight; scripts/docker-auth-status.sh; Make targets (docker-build/login/auth-status/
  run/shell/down/nuke).
- Verified end-to-end: one `make docker-login` -> a fresh container reports claude+codex
  logged in with live round-trips; the CTF pipeline (Codex) captured a flag against an
  isolated fixture and the pentest pipeline ran cleanly; persists across recreation, no re-login.

Benchmark (multi-model, host-side):
- benchmark/pilot/ harness (run_pilot.py + report.py): builds each xbow challenge, discovers
  the loopback port, runs the pipeline across the 4 model combos, judges by the baked
  FLAG{sha256(UPPER-dir)}, and renders REPORT.md (infra failures excluded from solve rates).
  Includes the partial pilot's results (results.jsonl + REPORT.md).

Docs: docs/docker-dev-plan.md (full plan + implementation status); CLAUDE.md and README
docker quickstart; benchmark/pilot/README.md; design-doc roadmap (docs/redesign).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* fix: fail controller on backend error messages

* fix: allow listing sessions without target

* docs: add docker xbow benchmark report

* fix: infer concrete backend constructor type

* docs: refresh docker benchmark documentation

* feat(benchmark): add pure single-agent baseline + pipeline comparison

Add a "pure single agent" benchmark variant -- one bare `claude -p` /
`codex exec` call per target (no pipeline) -- to quantify what the 3-stage
PentestGPT pipeline buys over an un-orchestrated agent on the xbow targets.

- pentestgpt/prompts/stages.py: ctf_single_agent_{system,task}_prompt -- the
  pipeline's shared fragments collapsed into ONE turn, so prompt content is
  held constant and the only variable is the multi-stage decomposition.
- benchmark/pilot/run_docker_bench.py: docker-network runner
  (--variant single|pipeline). Brings the target up, discovers the container's
  internal IP+network (skips DB side-cars/ports), docker-runs the tool image on
  that network, and scores the ground-truth flag against the agent's *assistant
  text* only (parity with the pipeline's raw streaming). Reads stdout in chunks
  to handle >64KB JSON lines. Resumable; --dry-run supported.
- benchmark/pilot/report_comparison.py -> DOCKER_COMPARISON.md: head-to-head
  pipeline-vs-single per model on the common non-infra set.
- tests/unit/test_single_agent_prompt.py: prompt-builder coverage.
- docs: README, CLAUDE.md, benchmark README, DOCKER_REPORT updated.

Recorded result (10 medium/hard targets x 4 models, container-to-container,
same baseline image digest 0c4c0f3e..., commit dca0019 image):

  Model               Pipeline   Single
  Claude Opus           5/10      7/10   (single +2)
  Claude Sonnet         6/10      4/10   (pipeline +2)
  Codex gpt-5.5         7/10      7/10   (tie)
  Codex gpt-5.4-mini    3/10      4/10   (single +1)
  TOTAL                21/40     22/40

Single agent matches the pipeline on solve rate (55% vs 52%) while using
~40% fewer Codex tokens (13.0M vs 21.8M) and solving faster. The pipeline
only clearly helps Claude Sonnet (which times out solo); Opus is better solo.
Full per-challenge grid in DOCKER_COMPARISON.md; raw records in
docker_single_results.jsonl.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* feat(benchmark): add pentestgpt_agent docker harness

* bench: refresh pentestgpt_agent smoke result

* fix(benchmark): make repeat rows variant-aware

* fix(agent): fall back for semantic executor labels

* fix(agent): tolerate executor prose evidence

* fix(benchmark): score accepted framework findings

* bench: append partial framework repeat results

* bench: complete framework repeat sweep

* bench: expose framework executor concurrency

* bench: add extended parallel framework sweep

* checkpoint: preserve working agent and benchmark state

* feat: harden durable agent loop and xbow qualification

* fix: reserve an exploit result turn

* docs: record clean xbow qualification

* build: consume unified-agent from the git wrapper repo

Repoint pentestgpt_agent_new's unified-agent dependency from the local
editable path (../../UnifiedAgentPoC, now renamed and gone) to the pinned
git source PentestGPT-Project/UnifedAgentWrapper@d05d21f. Regenerate uv.lock
and update test_dependency.py to assert the external package is installed
from that VCS URL (not the repo-root vendored copy) at version 0.2.0.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: make pentestgpt_agent_new the sole framework

Remove the retired ledger-based pentestgpt_agent package (instructor/executor/
judge) and its orphaned unit + smoke tests. The nested pentestgpt_agent_new
project (Supervisor/Executor over a durable SQLite loop, consuming unified-agent
from the git wrapper) is now the single maintained framework.

Repoint the top-level tooling to it:
- pyproject: drop the pentestgpt-agent console script and pentestgpt_agent from
  the wheel packages.
- Makefile: lint/format target parent code only; typecheck/check/ci now run the
  nested framework's own gate (ruff, format, mypy, pytest) via test-agent-new /
  check-agent-new, so `make check` finally covers it; `make run` delegates to the
  pentestgpt-agent-new CLI.
- Dockerfile: stop copying the removed package (kept the build working); note the
  framework is not baked into the image yet.
- docker container-health test: import the substrate packages that actually ship.
- CLAUDE.md / AGENT.md: describe the new framework, the git-sourced wrapper, and
  the deprioritized benchmark/Docker rewire.

The XBOW `--variant framework` path and docker-bench Makefile targets still point
at the old in-image framework and are left as a pending rewire (benchmarks
deprioritized); the naive `--variant single` path is unaffected.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* refactor: rename pentestgpt_agent_new -> pentestgpt_agent

The framework reclaims the clean name now that the old ledger-based package is
gone. Rename the nested project folder, its src package, the distribution
(pentestgpt-agent-new -> pentestgpt-agent) and CLI, and every import/reference in
the package, the umbrella Makefile, the Dockerfile, the docker health test, and
CLAUDE.md / AGENT.md. Regenerate uv.lock. The audit CLI stays pentestgpt-agent-audit;
the git-sourced unified-agent dependency is unchanged. `make check` is green
(108 nested tests). The two historical *_REPORT.md files keep the old name as
dated records.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* chore: extract benchmark harness to sibling xbow-benchmark repo

Move PentestGPT/benchmark/ out to ../xbow-benchmark (its own repo) to keep this
project clean. The harness was decoupled from the framework code (it scores
container output, never imports pentestgpt_agent/unified_agent), so only
operational ties remain and they now live in the sibling repo.

- Remove benchmark/ and the 4 harness unit tests (relocated + repointed there).
- Strip the docker-bench-*/bench-* targets and their config vars from the
  Makefile; keep the tool-image lifecycle (docker-build/login/run/...) and add a
  help pointer to `make -C ../xbow-benchmark help`.

The sibling repo mounts this checkout read-only (--source-root ../PentestGPT) and
runs the pentestgpt:latest image built here.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat: harden autonomous framework and runtime integration

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 16:49:08 +08:00

265 行
8.6 KiB
Python

import json
import sys
from types import SimpleNamespace as NS
import pytest
from openai_codex import Sandbox
from unified_agent.backends.codex import (
CodexBackend,
_TurnState,
build_config_overrides,
build_thread_kwargs,
build_turn_kwargs,
normalize_notification,
)
from unified_agent.events import (
AssistantText,
CommandRun,
FileChanged,
RawEvent,
Reasoning,
SessionStarted,
TextDelta,
ToolCall,
ToolResult,
TurnCompleted,
)
from unified_agent.types import RunOptions, SandboxPolicy, ToolServerSpec
def opts(tmp_path, **kw) -> RunOptions:
return RunOptions(workspace=tmp_path, **kw)
TOOL_SERVER = ToolServerSpec(
server_name="unified",
command=[sys.executable, "-m", "unified_agent.tool_server", "tests.fixture_registry:REG"],
env={"PYTHONPATH": "/re po"}, # space exercises TOML string quoting
)
# --- config / thread option mapping ----------------------------------------
def test_config_overrides_define_the_mcp_server_inline():
overrides = build_config_overrides(TOOL_SERVER)
joined = "\n".join(overrides)
assert f"mcp_servers.unified.command={json.dumps(sys.executable)}" in overrides
args_line = next(o for o in overrides if ".args=" in o)
assert json.loads(args_line.split("=", 1)[1]) == [
"-m",
"unified_agent.tool_server",
"tests.fixture_registry:REG",
]
env_line = next(o for o in overrides if ".env=" in o)
assert env_line == 'mcp_servers.unified.env={ "PYTHONPATH" = "/re po" }'
assert "mcp_servers.unified.startup_timeout_sec=30" in joined
assert "mcp_servers.unified.tool_timeout_sec=120" in joined
assert "mcp_servers.unified.required=true" in joined
assert 'mcp_servers.unified.default_tools_approval_mode="auto"' in joined
@pytest.mark.parametrize(
"policy,expected",
[
(SandboxPolicy.READ_ONLY, Sandbox.read_only),
(SandboxPolicy.WORKSPACE_WRITE, Sandbox.workspace_write),
(SandboxPolicy.FULL_ACCESS, Sandbox.full_access),
],
)
def test_thread_kwargs_sandbox_mapping(tmp_path, policy, expected):
kw = build_thread_kwargs(opts(tmp_path, sandbox=policy))
assert kw["sandbox"] is expected
assert kw["cwd"] == str(tmp_path)
def test_thread_kwargs_passthroughs(tmp_path):
kw = build_thread_kwargs(opts(tmp_path, model="gpt-5.5", instructions="be terse"))
assert kw["model"] == "gpt-5.5"
assert kw["developer_instructions"] == "be terse"
kw2 = build_thread_kwargs(opts(tmp_path))
assert "model" not in kw2 and "developer_instructions" not in kw2
def test_turn_kwargs_effort_mapping(tmp_path):
from openai_codex.generated.v2_all import ReasoningEffort
kw = build_turn_kwargs(opts(tmp_path, effort="xhigh"))
assert kw["effort"] is ReasoningEffort.xhigh
assert build_turn_kwargs(opts(tmp_path)) == {"output_schema": None}
def test_turn_kwargs_invalid_effort(tmp_path):
from unified_agent.types import AgentRunError
with pytest.raises(AgentRunError, match="effort"):
build_turn_kwargs(opts(tmp_path, effort="max")) # claude-only level
# --- notification normalization ---------------------------------------------
def fresh_state(tmp_path, **kw) -> _TurnState:
return _TurnState(opts=opts(tmp_path, **kw))
def norm(method, payload, state):
return list(normalize_notification(method, payload, state))
def test_thread_started_announces_session_once(tmp_path):
state = fresh_state(tmp_path)
events = norm("thread/started", NS(thread=NS(id="thr-1")), state)
assert events == [SessionStarted(session_id="thr-1")]
assert norm("thread/started", NS(thread=NS(id="thr-1")), state) == []
def test_agent_message_item(tmp_path):
state = fresh_state(tmp_path)
item = NS(root=NS(type="agentMessage", text="hello there", id="i1"))
events = norm("item/completed", NS(item=item), state)
assert events == [AssistantText(text="hello there")]
assert state.last_agent_text == "hello there"
def test_reasoning_item_prefers_summary(tmp_path):
state = fresh_state(tmp_path)
item = NS(root=NS(type="reasoning", summary=["thought hard"], content=[], id="i2"))
assert norm("item/completed", NS(item=item), state) == [Reasoning(text="thought hard")]
def test_command_execution_item(tmp_path):
state = fresh_state(tmp_path)
item = NS(
root=NS(
type="commandExecution",
command="ls -la",
exit_code=0,
aggregated_output="total 0",
status="completed",
id="i3",
)
)
assert norm("item/completed", NS(item=item), state) == [
CommandRun(command="ls -la", exit_code=0, output="total 0")
]
def test_mcp_tool_call_item(tmp_path):
state = fresh_state(tmp_path)
item = NS(
root=NS(
type="mcpToolCall",
server="unified",
tool="add_numbers",
arguments='{"a": 2, "b": 3}',
result=NS(content=[NS(type="text", text="2 + 3 = 5")], structured_content=None),
error=None,
status="completed",
id="i4",
)
)
call, result = norm("item/completed", NS(item=item), state)
assert call == ToolCall(name="mcp__unified__add_numbers", input={"a": 2, "b": 3}, call_id="i4")
assert isinstance(result, ToolResult)
assert "5" in result.output and result.is_error is False
def test_failed_mcp_tool_call_marks_error(tmp_path):
state = fresh_state(tmp_path)
item = NS(
root=NS(
type="mcpToolCall",
server="unified",
tool="boom",
arguments=None,
result=None,
error=NS(message="exploded"),
status="failed",
id="i5",
)
)
_call, result = norm("item/completed", NS(item=item), state)
assert result.is_error is True
assert "exploded" in result.output
def test_file_change_item(tmp_path):
state = fresh_state(tmp_path)
item = NS(
root=NS(
type="fileChange",
status="completed",
changes=[NS(path="a.txt", kind="add"), NS(path="b.txt", kind="update")],
id="i6",
)
)
assert norm("item/completed", NS(item=item), state) == [
FileChanged(path="a.txt", kind="add"),
FileChanged(path="b.txt", kind="update"),
]
def test_agent_message_delta_gated_by_stream_text(tmp_path):
on = fresh_state(tmp_path, stream_text=True)
off = fresh_state(tmp_path, stream_text=False)
assert norm("item/agentMessage/delta", NS(delta="he"), on) == [TextDelta(text="he")]
assert norm("item/agentMessage/delta", NS(delta="he"), off) == []
def test_token_usage_tracked_then_reported_on_turn_completed(tmp_path):
state = fresh_state(tmp_path)
usage = NS(
total=NS(
input_tokens=100,
cached_input_tokens=40,
output_tokens=9,
reasoning_output_tokens=3,
total_tokens=112,
),
last=None,
model_context_window=None,
)
assert norm("thread/tokenUsage/updated", NS(token_usage=usage, turn_id="t"), state) == []
state.thread_id = "thr-1"
state.last_agent_text = "final answer"
turn = NS(id="t", status="completed", error=None)
[event] = norm("turn/completed", NS(turn=turn, thread_id="thr-1"), state)
assert isinstance(event, TurnCompleted)
assert event.success is True
assert event.final_text == "final answer"
assert event.usage.input_tokens == 100
assert event.usage.cached_input_tokens == 40
assert event.usage.reasoning_output_tokens == 3
assert event.session_id == "thr-1"
assert event.cost_usd is None
def test_turn_failed_with_error_notification(tmp_path):
state = fresh_state(tmp_path)
norm("error", NS(error=NS(message="rate limited"), will_retry=False), state)
turn = NS(id="t", status=NS(value="failed"), error=NS(message="turn died"))
[event] = norm("turn/completed", NS(turn=turn), state)
assert event.success is False
assert "turn died" in event.error and "rate limited" in event.error
def test_structured_output_parsed_from_final_text(tmp_path):
state = fresh_state(tmp_path, output_schema={"type": "object"})
state.last_agent_text = '{"n": 42}'
turn = NS(id="t", status="completed", error=None)
[event] = norm("turn/completed", NS(turn=turn), state)
assert event.structured_output == {"n": 42}
def test_unknown_notification_becomes_raw_event(tmp_path):
state = fresh_state(tmp_path)
[event] = norm("guardianWarning", NS(anything=1), state)
assert isinstance(event, RawEvent)
assert event.kind == "guardianWarning"
def test_backend_name():
assert CodexBackend().name == "codex"