Skip to content

Add API-key agent (LiteLLM) and per-run AI cost tracking - #9

Closed
geet038 wants to merge 3 commits into
mainfrom
feat/api-agent
Closed

geet038 wants to merge 3 commits into
mainfrom
feat/api-agent

Conversation

@geet038

@geet038 geet038 commented Sep 18, 2026

Copy link
Copy Markdown
Contributor

Why

API agent (Initiative 2, Tier A). Every existing agent drives an installed coding-agent CLI (Claude Code, Cursor, Antigravity, Gemini CLI). CI runners and many contributors don't have one installed and logged in, so they can't run an assessment at all. The new api agent needs only an API key.

Cost tracking. Users had no way to see what their AI usage costs. Each run now records tokens and cost where the agent reports them, and spend is visible per run, per agent, per skill and per project.

What changed

--agent api (src/secfoo/agents/api.py)

  • Calls OpenAI, Anthropic or Gemini through LiteLLM. Enabled by any of OPENAI_API_KEY, ANTHROPIC_API_KEY or GEMINI_API_KEY; the model is set with SECFOO_API_MODEL (default openai/gpt-4.1-mini).
  • Tier A "context stuffing": the model can't open files, so the target's files go into one request. Files are skipped if they match DEFAULT_EXCLUDE_PATHS, are binary, or are over 200 KB. Targets over 2M characters fail with a clear message.
  • Overrides run(), since there's no subprocess, and returns the same AgentResult shape. Registered in registry.py and added to the CLI's AgentId enum.
  • Trims whitespace from keys: a trailing newline made httpx reject the auth header, which LiteLLM reports only as "Connection error".
  • LiteLLM is an optional extra, installed with pip install "secfoo[api]". If it's missing, the run fails with an install hint.

Cost tracking

  • AgentResult gains input_tokens, output_tokens and cost_usd, plus an extract_usage() hook on AgentAdapter:
    • api: LiteLLM usage and completion_cost(); cost is None for models LiteLLM can't price.
    • claude: total_cost_usd and usage from --output-format json, with cache tokens counted as input. On a subscription login this is Claude's API-price estimate.
    • gemini: token counts from stats.models.*.tokens; no cost available.
    • agent (Cursor) and agy: they print plain text, so nothing is recorded.
  • runs gains three nullable columns, added through _RUNS_MIGRATIONS so existing databases upgrade in place.
  • RunRepository.cost_summary() groups by agent, skill or project. Runs with no recorded cost are counted as unpriced_runs, not as $0.
  • CLI: a Cost column in run and list, "AI spend for this run: $X", and a new secfoo cost [--by agent|skill|project] [--since YYYY-MM-DD] command.
  • Dashboard: an "AI spend" stat card and an "AI spend by agent" card on the overview, AI cost and tokens on the run page, and a Cost column on the assessment and project run tables.
  • Unknown cost always renders as "-", never "$0.00".

Testing

  • 24 new tests: tests/test_agents/test_api.py (9), tests/test_cost.py (11), and usage parsing in test_claude.py / test_gemini.py (5).
  • Full suite: 656 passed, 6 failed. The same 6 fail on main locally (Windows): 4 architecture-diagram tests need secfoo vendor mermaid, which CI runs first; test_save_cloud_config_sets_restrictive_permissions checks POSIX permissions; test_timeout_status_does_not_raise fails because os.killpg doesn't exist on Windows.
  • Manual run against OWASP NodeGoat with gpt-4.1-mini:
    • 7 of the 8 code-based skills completed, with 57 findings. prompt-review failed because running 7 skills at once hit OpenAI's rate limit.
    • A follow-up SAST run recorded 61,597 input and 3,265 output tokens, costing $0.03.

Known limitations / follow-ups

  • Accuracy: findings from the api agent haven't yet been compared against a claude run or NodeGoat's documented vulnerabilities.
  • Providers: only OpenAI has been tested end to end. Anthropic and Gemini go through the same LiteLLM path.
  • Exclusions: user --exclude paths are listed in the prompt, but collect_files() doesn't skip them yet.
  • Size limit: measured in characters, not tokens per model.
  • Rate limits: concurrent --skill runs can hit provider rate limits. Retry with backoff, or run api skills one after another.
  • Wording: the dashboard's "(not installed)" and "CLI not found on PATH" messages are misleading for the api agent.
  • Cloud sync: cost isn't included in the secfoo cloud sync payload yet.
  • Separate issue: on Windows, unencoded read_text() / write_text() calls need PYTHONUTF8=1.

🤖 Generated with Claude Code

geet038 and others added 3 commits September 18, 2026 23:39
Add an `api` agent that runs skills by calling OpenAI, Anthropic or
Gemini directly through LiteLLM, so an assessment no longer needs a
coding-agent CLI installed. This is Tier A (context stuffing): the
target's source files, minus the default exclusions, binaries and files
over 200 KB, are sent in one request. Targets over 2M characters are
rejected with a clear message. Install with `pip install "secfoo[api]"`.

Record input/output tokens and cost on every run where the agent
reports them (api via LiteLLM, claude via total_cost_usd, gemini tokens
only), and surface spend in `secfoo run`, `secfoo list`, a new
`secfoo cost` command, and the dashboard. Unknown cost renders as "-",
never $0.00. Existing databases gain the new columns automatically.

Co-Authored-By: Claude Opus 5 <[email protected]>
Rebuild the api agent's run as a LangGraph graph (collect_files ->
assess -> report check), with LiteLLM still the only model gateway. If
a report comes back without the `**Overall risk rating:**` line every
output contract requires, the graph asks the model once to reformat its
own draft -- without resending the source, so the retry stays cheap.
Tokens and cost add up across both calls. LiteLLM now retries rate
limits and transient errors itself (num_retries=3); running several
skills at once previously failed on OpenAI's rate limit.

Fold in the useful parts of PR #10:
- tokens and cost in the cloud-sync payload and create_completed_run
- `secfoo cost --project`, a README section, config.example.toml hint
- UTF-8 for every text read/write, not just runner's report writes.
  Report reads use errors="replace" so reports written by older
  versions in the Windows code page still render instead of crashing.
  The suite now gives the same result with or without PYTHONUTF8.

langgraph joins litellm in the `api` extra, and dev (litellm stays
faked in tests, so CI doesn't need it).

Co-Authored-By: Claude Opus 5 <[email protected]>
@geet038

geet038 commented Sep 21, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #11

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant