Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,37 @@ dashboard (like SAST's Open/Closed Findings register), look at
templates as the reference shape — most skills don't need this and are
fine with the generic activity page (`activities/detail.html`).

## Adding or changing an agent adapter

Agent adapters live under `src/secfoo/agents/*.py`. Each one subclasses
`AgentAdapter` (`src/secfoo/agents/base.py`), which owns the shared
subprocess/timeout/process-tree-kill contract, so a new adapter only
needs to supply:

- `name` / `binary` class vars, and `default_timeout_seconds` if the
1800s default doesn't fit
- `build_command(prompt, *, workdir)` — the argv to invoke the CLI
non-interactively
- `extract_report(stdout)` — optional, only for a CLI that wraps its
answer in a JSON envelope rather than printing the report directly
- `extract_cost(stdout)` — optional, only if the CLI itself reports a USD
spend figure (e.g. Claude Code's `total_cost_usd` in `--output-format
json`; see `ClaudeAdapter`). Leave it unset if the CLI doesn't report
cost — don't estimate from token counts, since there's no pricing table
in this repo to keep current. `secfoo cost` shows `-` for runs whose
adapter doesn't provide this.

Then register the class in `ADAPTERS` in
`src/secfoo/agents/registry.py`. `secfoo agents`, `--agent`, and the web
run form are all driven from that dict, so there's nothing else to wire
up.

The built-in `secfoo` agent (`src/secfoo/agents/secfoo.py`) is the one
exception: it overrides `run()` directly instead of `build_command()`,
since it runs in-process via LangGraph/LiteLLM rather than shelling out
to an external CLI — use it as the reference if your adapter also needs
to skip the subprocess path.

## Pull requests

- Keep PRs focused — one behavior change per PR is easier to review
Expand Down
11 changes: 9 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,11 @@ $env:SECFOO_MODEL = "openai/gpt-4o-mini"
secfoo run --skill security-architecture-review --agent secfoo
```

LiteLLM-reported spend is stored per run and can be reviewed from the
dashboard or queried from the CLI:
Spend is stored per run and can be reviewed from the dashboard or queried
from the CLI, for any agent whose CLI reports its own cost -- currently
the built-in `secfoo` agent (via LiteLLM) and `claude` (via Claude Code's
own `total_cost_usd`); Cursor, Antigravity, and Gemini CLI don't report a
spend figure yet, so those runs show `-`:

```bash
secfoo cost
Expand Down Expand Up @@ -133,6 +136,10 @@ the [CLI reference](https://secfoo.com/docs/cli.html) for more.
record every rescan.
- **Concurrent by default**: multiple `--skill` flags run at the same
time, not one after another.
- **Bring your own agent**: Claude Code, Cursor, Antigravity, or Gemini
CLI — pick whichever you already use and trust. Want to wire up a
different CLI, or your own LangGraph/LiteLLM pipeline? See
[Adding or changing an agent adapter](CONTRIBUTING.md#adding-or-changing-an-agent-adapter).
- **Bring your own agent**: Claude Code, Cursor, Antigravity, Gemini
CLI, or Codex CLI — pick whichever you already use and trust.
- **Open source CLI**: MIT licensed.
Expand Down
4 changes: 4 additions & 0 deletions src/secfoo/agents/antigravity.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ class AntigravityAdapter(AgentAdapter):
binary = "agy"
default_timeout_seconds = 1800

# No extract_cost() override: `agy --print` has no JSON output mode (see
# module docstring), so there's no reported spend figure to parse.
# secfoo cost will show `-` for runs through this adapter.

def build_command(self, prompt: str, *, workdir: Path) -> list[str]:
effective_timeout = getattr(self, "_effective_timeout", self.default_timeout_seconds)
return [self.binary, "--print", prompt, "--print-timeout", f"{effective_timeout}s"]
Expand Down
7 changes: 7 additions & 0 deletions src/secfoo/agents/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,12 @@ def extract_report(self, stdout: str) -> str:
"""Pull the report text out of raw stdout. Default: stdout is the report."""
return stdout

def extract_cost(self, stdout: str) -> float | None:
"""Pull a CLI-reported USD spend figure out of raw stdout, if the CLI
reports one. Default: no cost data available. Only override this
with a value the CLI itself reports -- never a token-count estimate,
since we have no reliable, current pricing table to convert with."""
return None
def extract_usage(self, stdout: str) -> Usage:
"""Pull token counts / cost out of raw stdout. Default: unknown."""
return Usage()
Expand Down Expand Up @@ -143,6 +149,7 @@ def run(self, prompt: str, *, workdir: Path, timeout: int | None = None) -> Agen
timed_out=False,
status=status,
raw_report=self.extract_report(stdout) if status == "success" else "",
cost_usd=self.extract_cost(stdout) if status == "success" else None,
input_tokens=usage.input_tokens,
output_tokens=usage.output_tokens,
cost_usd=usage.cost_usd,
Expand Down
10 changes: 10 additions & 0 deletions src/secfoo/agents/claude.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,16 @@ def extract_report(self, stdout: str) -> str:
return stdout
return payload.get("result", stdout)

def extract_cost(self, stdout: str) -> float | None:
# `--output-format json` includes `total_cost_usd`, Claude Code's own
# accounting of the spend for this invocation -- a real reported
# figure, not something we derive.
try:
payload = json.loads(stdout)
except json.JSONDecodeError:
return None
value = payload.get("total_cost_usd")
return float(value) if isinstance(value, (int, float)) else None
def extract_usage(self, stdout: str) -> Usage:
# `--output-format json` reports total_cost_usd plus a usage block.
# On a subscription login the cost is claude's API-price estimate,
Expand Down
4 changes: 4 additions & 0 deletions src/secfoo/agents/cursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,7 @@ class CursorAdapter(AgentAdapter):

def build_command(self, prompt: str, *, workdir: Path) -> list[str]:
return [self.binary, "-p", prompt]

# No extract_cost() override: `agent -p` prints plain text, not a JSON
# envelope with a reported spend figure, so there's nothing to parse
# cost out of. secfoo cost will show `-` for runs through this adapter.
6 changes: 6 additions & 0 deletions src/secfoo/agents/gemini.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ def extract_report(self, stdout: str) -> str:
return stdout
return payload.get("response", payload.get("result", stdout))

# No extract_cost() override: Gemini CLI's JSON output doesn't report a
# USD spend figure (unlike Claude Code's total_cost_usd), and deriving
# one from token counts would need a pricing table we have no reliable
# way to keep current -- see AgentAdapter.extract_cost()'s docstring for
# why that tradeoff isn't worth it. secfoo cost will show `-` for runs
# through this adapter until Gemini CLI reports cost itself.
def extract_usage(self, stdout: str) -> Usage:
# `--output-format json` carries per-model token counts under
# stats.models.<model>.tokens, but no cost.
Expand Down
9 changes: 9 additions & 0 deletions tests/test_agents/test_antigravity.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,12 @@ def test_no_dangerously_skip_permissions_flag(tmp_path):
adapter = AntigravityAdapter()
cmd = adapter.build_command("hi", workdir=tmp_path)
assert "--dangerously-skip-permissions" not in cmd


def test_run_success_leaves_cost_usd_none(fake_popen, tmp_path):
"""`agy --print` has no JSON output mode, so no reported spend figure to
parse -- cost_usd must stay None rather than a guessed/estimated value."""
fake_popen(returncode=0, stdout="# Report", stderr="")
adapter = AntigravityAdapter()
result = adapter.run("hi", workdir=tmp_path)
assert result.cost_usd is None
26 changes: 26 additions & 0 deletions tests/test_agents/test_claude.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,32 @@ def test_run_success_extracts_report_from_json(fake_popen, tmp_path, monkeypatch
assert result.raw_report == "# Threat Report"


def test_extract_cost_parses_total_cost_usd():
adapter = ClaudeAdapter()
stdout = json.dumps({"result": "ok", "total_cost_usd": 0.0412})
assert adapter.extract_cost(stdout) == 0.0412


def test_extract_cost_returns_none_when_field_missing():
adapter = ClaudeAdapter()
assert adapter.extract_cost(json.dumps({"result": "ok"})) is None


def test_extract_cost_returns_none_on_non_json():
adapter = ClaudeAdapter()
assert adapter.extract_cost("not json") is None


def test_run_success_sets_cost_usd_from_json(fake_popen, tmp_path, monkeypatch):
monkeypatch.setattr("secfoo.agents.claude.load_config", lambda: _empty_config())
fake_popen(
returncode=0,
stdout=json.dumps({"result": "# Threat Report", "total_cost_usd": 0.0412}),
stderr="",
)
adapter = ClaudeAdapter()
result = adapter.run("review this", workdir=tmp_path)
assert result.cost_usd == 0.0412
def test_extract_usage_reads_cost_and_sums_cached_input_tokens():
stdout = json.dumps({
"result": "report",
Expand Down
9 changes: 9 additions & 0 deletions tests/test_agents/test_cursor.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,12 @@ def test_timeout_status_does_not_raise(fake_popen, tmp_path):
assert result.timed_out is True
assert result.exit_code is None
assert result.raw_report == ""


def test_run_success_leaves_cost_usd_none(fake_popen, tmp_path):
"""`agent -p` prints plain text, no reported spend figure to parse --
cost_usd must stay None rather than a guessed/estimated value."""
fake_popen(returncode=0, stdout="plain text report", stderr="")
adapter = CursorAdapter()
result = adapter.run("hi", workdir=tmp_path)
assert result.cost_usd is None
7 changes: 7 additions & 0 deletions tests/test_agents/test_gemini.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,13 @@ def test_extract_report_non_json_passthrough():
assert adapter.extract_report("plain text") == "plain text"


def test_run_success_leaves_cost_usd_none(fake_popen, tmp_path):
"""Gemini CLI's JSON output has no reported spend figure -- cost_usd
must stay None rather than a guessed/estimated value."""
fake_popen(returncode=0, stdout=json.dumps({"response": "R"}), stderr="")
adapter = GeminiAdapter()
result = adapter.run("hi", workdir=tmp_path)
assert result.cost_usd is None
def test_extract_usage_sums_tokens_across_models_without_cost():
stdout = json.dumps({
"response": "report",
Expand Down
Loading