diff --git a/README.md b/README.md index 3dcb742..d6d60f5 100644 --- a/README.md +++ b/README.md @@ -41,7 +41,8 @@ secfoo run --skill security-architecture-review --agent claude ``` You'll need an agent CLI already installed and authenticated — Claude -Code, Cursor, Antigravity, Gemini CLI, or Codex CLI (`--agent claude|agent|agy|gemini|codex`). +Code, Cursor, Antigravity, Gemini CLI, or Codex CLI (`--agent claude|agent|agy|gemini|codex`) +— or just a model API key with the built-in `api` agent (below). On a real terminal, that first run prompts for a project name and application ID, then browse every result in the dashboard: @@ -51,6 +52,35 @@ secfoo run --skill sast --skill threat-modeling \ secfoo serve ``` +### No agent CLI? Use an API key + +The built-in `api` agent is a LangGraph workflow that sends the target's +source to OpenAI, Anthropic or Gemini through LiteLLM — no coding-agent +CLI needed, which suits CI. Keys are read from the environment only and +never stored: + +```bash +pip install "secfoo[api]" +export OPENAI_API_KEY=... # or ANTHROPIC_API_KEY / GEMINI_API_KEY +export SECFOO_API_MODEL=openai/gpt-4.1-mini # optional; any LiteLLM model id +secfoo run --skill sast --agent api --target https://github.com/org/repo +``` + +It suits small and medium repositories: the whole target has to fit in one +request, and larger ones are rejected with a message suggesting `--exclude`. + +### Tracking AI spend + +Every run records tokens and cost where the agent reports them (`api`, +`claude`; `gemini` reports tokens only). See it per run in `secfoo run`, +`secfoo list` and the dashboard, or summarised: + +```bash +secfoo cost # by agent +secfoo cost --by skill --since 2026-09-01 +secfoo cost --project checkout +``` + Secfoo also includes a built-in LangGraph agent whose model calls are routed through LiteLLM. Configure the provider key and model in the environment; credentials are never stored in the repository: diff --git a/pyproject.toml b/pyproject.toml index 9b843c4..86614b9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -48,8 +48,12 @@ dependencies = [ ] [project.optional-dependencies] -dev = ["pytest>=8.0", "httpx>=0.27", "ruff>=0.4", "bandit>=1.8", "pip-audit>=2.7"] +dev = ["pytest>=8.0", "httpx>=0.27", "ruff>=0.4", "bandit>=1.8", "pip-audit>=2.7", "langgraph>=0.2"] build = ["pyinstaller>=6.0"] +# The `api` agent (secfoo/agents/api.py): a LangGraph workflow that calls OpenAI/Anthropic/Gemini +# through LiteLLM with an API key instead of driving an installed agent CLI. +# (dev includes langgraph so the real graph runs in tests; litellm is faked.) +api = ["litellm>=1.40", "langgraph>=0.2"] [project.scripts] secfoo = "secfoo.cli:main" diff --git a/src/secfoo/agents/api.py b/src/secfoo/agents/api.py new file mode 100644 index 0000000..595c376 --- /dev/null +++ b/src/secfoo/agents/api.py @@ -0,0 +1,235 @@ +"""Agent that calls a model API directly (OpenAI, Anthropic, Gemini via LiteLLM). + +Unlike the CLI adapters, the model can't open files itself, so the target's +source files are pasted into the prompt ("context stuffing", Tier A). + +The run is a small LangGraph graph: + + collect_files -> assess -> (report complete?) -> END + ^ | no, first attempt + +- request_fix <+ + +`request_fix` asks the model to reformat its own draft into the required +report format without resending the source, so a malformed report costs one +cheap extra call rather than a second full assessment. +""" + +from __future__ import annotations + +import fnmatch +import os +import time +from pathlib import Path +from typing import TypedDict + +from secfoo.agents.base import AgentAdapter, AgentResult, Status, Usage +from secfoo.report.severity import extract_overall_risk_rating +from secfoo.skills.renderer import DEFAULT_EXCLUDE_PATHS + +KEY_VARS = ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY") +DEFAULT_MODEL = "openai/gpt-4.1-mini" +MAX_FILE_BYTES = 200_000 +MAX_TOTAL_CHARS = 2_000_000 +MAX_ATTEMPTS = 2 # one assessment + at most one reformat +NUM_RETRIES = 3 # LiteLLM's own backoff for rate limits / transient errors + +DIR_PATTERNS = [p.rstrip("/") for p in DEFAULT_EXCLUDE_PATHS if p.endswith("/")] +FILE_PATTERNS = [p for p in DEFAULT_EXCLUDE_PATHS if not p.endswith("/")] + +FIX_REQUEST = ( + "## Draft report to reformat\n" + "You already reviewed the target source and wrote the draft below, but it does not " + "follow the required output format above (it has no `**Overall risk rating:**` line). " + "Rewrite it into exactly that format. Keep every finding as-is: do not add, drop, or " + "re-rate findings. Output only the report.\n\n" +) + + +class _State(TypedDict): + prompt: str + workdir: str + model: str + timeout: int + messages: list[dict] + report: str + attempts: int + input_tokens: int + output_tokens: int + cost_usd: float + unpriced: bool + + +def _matches(name: str, patterns: list[str]) -> bool: + return any(fnmatch.fnmatch(name, p) for p in patterns) + + +def collect_files(workdir: Path) -> str: + """Return every readable text file under `workdir` as one labelled string.""" + chunks: list[str] = [] + total = 0 + for root, dirs, files in os.walk(workdir): + dirs[:] = sorted(d for d in dirs if not _matches(d, DIR_PATTERNS)) + for name in sorted(files): + path = Path(root) / name + if _matches(name, FILE_PATTERNS) or path.stat().st_size > MAX_FILE_BYTES: + continue + try: + text = path.read_text(encoding="utf-8") + except (UnicodeDecodeError, OSError): + continue # binary file (image, font, ...) + chunk = f"\n===== FILE: {path.relative_to(workdir).as_posix()} =====\n{text}\n" + total += len(chunk) + if total > MAX_TOTAL_CHARS: + raise ValueError( + f"Target is too large for the api agent (over {MAX_TOTAL_CHARS:,} characters). " + "Use --exclude to narrow it, or use a CLI agent." + ) + chunks.append(chunk) + return "".join(chunks) + + +def build_graph(litellm, StateGraph, START, END): + """The assessment workflow. Takes the libraries as arguments so tests can + run the real graph against a fake LiteLLM.""" + + def collect(state: _State) -> dict: + code = collect_files(Path(state["workdir"])) + content = ( + f"{state['prompt']}\n\n## Source files\nYou cannot open files. " + f"The complete target source is included below.\n{code}" + ) + return {"messages": [{"role": "user", "content": content}]} + + def assess(state: _State) -> dict: + response = litellm.completion( + model=state["model"], + messages=state["messages"], + timeout=state["timeout"], + num_retries=NUM_RETRIES, + ) + usage = _usage(litellm, response) + return { + "report": response.choices[0].message.content or "", + "attempts": state["attempts"] + 1, + "input_tokens": state["input_tokens"] + (usage.input_tokens or 0), + "output_tokens": state["output_tokens"] + (usage.output_tokens or 0), + "cost_usd": state["cost_usd"] + (usage.cost_usd or 0.0), + "unpriced": state["unpriced"] or usage.cost_usd is None, + } + + def request_fix(state: _State) -> dict: + # Fresh, short conversation: the instructions (which carry the output + # contract) plus the draft -- not the source files again. + content = f"{state['prompt']}\n\n{FIX_REQUEST}{state['report']}" + return {"messages": [{"role": "user", "content": content}]} + + def next_step(state: _State) -> str: + if extract_overall_risk_rating(state["report"]) is not None or state["attempts"] >= MAX_ATTEMPTS: + return END + return "request_fix" + + graph = StateGraph(_State) + graph.add_node("collect_files", collect) + graph.add_node("assess", assess) + graph.add_node("request_fix", request_fix) + graph.add_edge(START, "collect_files") + graph.add_edge("collect_files", "assess") + graph.add_conditional_edges("assess", next_step, ["request_fix", END]) + graph.add_edge("request_fix", "assess") + return graph.compile() + + +class ApiAdapter(AgentAdapter): + name = "api" + binary = "API key" # label only: shown in `secfoo agents` + + def is_available(self) -> bool: + return any(os.environ.get(k) for k in KEY_VARS) + + def build_command(self, prompt: str, *, workdir: Path) -> list[str]: + return [] # required by the base class; there is no program to launch + + def run(self, prompt: str, *, workdir: Path, timeout: int | None = None) -> AgentResult: + started = time.monotonic() + _strip_key_whitespace() + if not self.is_available(): + return self._result("binary_not_found", started, stderr=f"No API key set. Set one of: {', '.join(KEY_VARS)}") + try: + import litellm + from langgraph.graph import END, START, StateGraph + except ImportError: + return self._result( + "failed", started, stderr='litellm/langgraph are not installed. Run: pip install "secfoo[api]"' + ) + try: + final = build_graph(litellm, StateGraph, START, END).invoke({ + "prompt": prompt, + "workdir": str(workdir), + "model": os.environ.get("SECFOO_API_MODEL", DEFAULT_MODEL), + "timeout": timeout or self.default_timeout_seconds, + "messages": [], + "report": "", + "attempts": 0, + "input_tokens": 0, + "output_tokens": 0, + "cost_usd": 0.0, + "unpriced": False, + }) + except Exception as exc: # noqa: BLE001 -- any failure becomes a failed run with its message + return self._result("failed", started, stderr=str(exc)) + usage = Usage( + input_tokens=final["input_tokens"], + output_tokens=final["output_tokens"], + cost_usd=None if final["unpriced"] else final["cost_usd"], + ) + report = final["report"] + return self._result("success", started, stdout=report, report=report, usage=usage) + + def _result( + self, + status: Status, + started: float, + *, + stdout: str = "", + stderr: str = "", + report: str = "", + usage: Usage | None = None, + ) -> AgentResult: + usage = usage or Usage() + return AgentResult( + agent=self.name, + exit_code=0 if status == "success" else None, + stdout=stdout, + stderr=stderr, + duration_seconds=time.monotonic() - started, + timed_out=False, + status=status, + raw_report=report, + input_tokens=usage.input_tokens, + output_tokens=usage.output_tokens, + cost_usd=usage.cost_usd, + ) + + +def _strip_key_whitespace() -> None: + """A key pasted with a trailing newline makes httpx reject the auth + header, which LiteLLM reports only as a vague "Connection error".""" + for key in KEY_VARS: + value = os.environ.get(key) + if value and value != value.strip(): + os.environ[key] = value.strip() + + +def _usage(litellm, response) -> Usage: + """Token counts from the response; cost from LiteLLM's price table + (None for a model LiteLLM has no price for).""" + tokens = getattr(response, "usage", None) + try: + cost = litellm.completion_cost(completion_response=response) + except Exception: # noqa: BLE001 -- unknown model pricing shouldn't fail a successful run + cost = None + return Usage( + input_tokens=getattr(tokens, "prompt_tokens", None), + output_tokens=getattr(tokens, "completion_tokens", None), + cost_usd=float(cost) if cost is not None else None, + ) diff --git a/src/secfoo/agents/base.py b/src/secfoo/agents/base.py index 4a6b165..a22b83a 100644 --- a/src/secfoo/agents/base.py +++ b/src/secfoo/agents/base.py @@ -65,6 +65,17 @@ class AgentResult: timed_out: bool status: Status raw_report: str + # AI spend for this run, when the agent reports it. None means unknown + # (the CLI doesn't expose it), not zero. + input_tokens: int | None = None + output_tokens: int | None = None + cost_usd: float | None = None + + +@dataclass(frozen=True) +class Usage: + input_tokens: int | None = None + output_tokens: int | None = None cost_usd: float | None = None @@ -84,6 +95,10 @@ def extract_report(self, stdout: str) -> str: """Pull the report text out of raw stdout. Default: stdout is the report.""" return stdout + def extract_usage(self, stdout: str) -> Usage: + """Pull token counts / cost out of raw stdout. Default: unknown.""" + return Usage() + def run(self, prompt: str, *, workdir: Path, timeout: int | None = None) -> AgentResult: if not self.is_available(): return AgentResult( @@ -118,6 +133,7 @@ def run(self, prompt: str, *, workdir: Path, timeout: int | None = None) -> Agen stdout, stderr = proc.communicate(timeout=effective_timeout) duration = time.monotonic() - started status: Status = "success" if proc.returncode == 0 else "failed" + usage = self.extract_usage(stdout) return AgentResult( agent=self.name, exit_code=proc.returncode, @@ -127,6 +143,9 @@ 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 "", + input_tokens=usage.input_tokens, + output_tokens=usage.output_tokens, + cost_usd=usage.cost_usd, ) except subprocess.TimeoutExpired: _kill_process_tree(proc.pid) diff --git a/src/secfoo/agents/claude.py b/src/secfoo/agents/claude.py index 5da60f8..9a21668 100644 --- a/src/secfoo/agents/claude.py +++ b/src/secfoo/agents/claude.py @@ -3,7 +3,7 @@ import json from pathlib import Path -from secfoo.agents.base import AgentAdapter +from secfoo.agents.base import AgentAdapter, Usage from secfoo.mcp import write_claude_mcp_config from secfoo.settings import load_config @@ -55,3 +55,25 @@ def extract_report(self, stdout: str) -> str: except json.JSONDecodeError: return stdout return payload.get("result", stdout) + + 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, + # not an amount actually billed. + try: + payload = json.loads(stdout) + except json.JSONDecodeError: + return Usage() + if not isinstance(payload, dict): + return Usage() + usage = payload.get("usage") or {} + input_tokens = sum( + usage.get(key) or 0 + for key in ("input_tokens", "cache_creation_input_tokens", "cache_read_input_tokens") + ) + cost = payload.get("total_cost_usd") + return Usage( + input_tokens=input_tokens if usage else None, + output_tokens=usage.get("output_tokens"), + cost_usd=float(cost) if cost is not None else None, + ) diff --git a/src/secfoo/agents/gemini.py b/src/secfoo/agents/gemini.py index d4a0604..f864cbb 100644 --- a/src/secfoo/agents/gemini.py +++ b/src/secfoo/agents/gemini.py @@ -15,7 +15,7 @@ import json from pathlib import Path -from secfoo.agents.base import AgentAdapter +from secfoo.agents.base import AgentAdapter, Usage class GeminiAdapter(AgentAdapter): @@ -39,3 +39,19 @@ def extract_report(self, stdout: str) -> str: except json.JSONDecodeError: return stdout return payload.get("response", payload.get("result", stdout)) + + def extract_usage(self, stdout: str) -> Usage: + # `--output-format json` carries per-model token counts under + # stats.models..tokens, but no cost. + try: + payload = json.loads(stdout) + except json.JSONDecodeError: + return Usage() + models = (payload.get("stats") or {}).get("models") if isinstance(payload, dict) else None + if not isinstance(models, dict) or not models: + return Usage() + tokens = [m.get("tokens") or {} for m in models.values() if isinstance(m, dict)] + return Usage( + input_tokens=sum(t.get("prompt") or 0 for t in tokens), + output_tokens=sum(t.get("candidates") or 0 for t in tokens), + ) diff --git a/src/secfoo/agents/registry.py b/src/secfoo/agents/registry.py index 3543115..79a2517 100644 --- a/src/secfoo/agents/registry.py +++ b/src/secfoo/agents/registry.py @@ -1,6 +1,7 @@ from __future__ import annotations from secfoo.agents.antigravity import AntigravityAdapter +from secfoo.agents.api import ApiAdapter from secfoo.agents.base import AgentAdapter from secfoo.agents.claude import ClaudeAdapter from secfoo.agents.codex import CodexAdapter @@ -13,6 +14,7 @@ CursorAdapter.name: CursorAdapter, AntigravityAdapter.name: AntigravityAdapter, GeminiAdapter.name: GeminiAdapter, + ApiAdapter.name: ApiAdapter, SecFooAdapter.name: SecFooAdapter, CodexAdapter.name: CodexAdapter, } diff --git a/src/secfoo/aibom.py b/src/secfoo/aibom.py index ef3454c..b2de10f 100644 --- a/src/secfoo/aibom.py +++ b/src/secfoo/aibom.py @@ -91,7 +91,7 @@ def _parse_csv(text: str) -> AIBOMSummary: def parse_ai_bom(path: Path) -> AIBOMSummary: - text = path.read_text() + text = path.read_text(encoding="utf-8") suffix = path.suffix.lower() if suffix == ".json": return _parse_json(text) diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index 22b50d1..324f34a 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -21,6 +21,7 @@ from secfoo.attachments import infer_attachment_kind from secfoo.cloud import CloudConfig, CloudError from secfoo.config import CLOUD_CONFIG_PATH, attachment_dir +from secfoo.cost import format_cost, format_tokens from secfoo.runner import _project_display_name, execute_runs from secfoo.settings import CONFIG_PATH, ConfigError, load_config from secfoo.skills.loader import load_all_skills @@ -94,6 +95,7 @@ class AgentId(str, Enum): CURSOR = "agent" ANTIGRAVITY = "agy" GEMINI = "gemini" + API = "api" SECFOO = "secfoo" CODEX = "codex" @@ -290,42 +292,32 @@ def handle_complete(skill_name: str, result_status: str) -> None: table.add_column("Skill") table.add_column("Status") table.add_column("Duration") + table.add_column("Cost", justify="right") table.add_column("Run ID") any_failed = False for outcome in outcomes: style = _STATUS_STYLE.get(outcome.status, "white") duration = f"{outcome.duration_seconds:.1f}s" if outcome.duration_seconds else "-" - table.add_row(outcome.skill_name, f"[{style}]{outcome.status}[/]", duration, outcome.run_uuid) + table.add_row( + outcome.skill_name, + f"[{style}]{outcome.status}[/]", + duration, + format_cost(outcome.cost_usd), + outcome.run_uuid, + ) if outcome.status != "success": any_failed = True console.print(table) + priced = [o.cost_usd for o in outcomes if o.cost_usd is not None] + if priced: + console.print(f"AI spend for this run: [bold]{format_cost(sum(priced))}[/]") console.print("Run [bold]secfoo serve[/] to view full reports in your browser.") if any_failed: raise typer.Exit(code=1) -@app.command() -def cost( - project: Optional[str] = typer.Option(None, "--project", "-p", help="Filter by project name/URL substring."), -) -> None: - """Show recorded AI spend for runs.""" - with RunRepository() as repo: - project_id = None - if project: - matches = [ - p for p in repo.list_projects() - if project.lower() in p.display_name.lower() or project.lower() in p.identifier.lower() - ] - if not matches: - console.print(f"[yellow]No project matches {project!r}.[/]") - return - project_id = matches[0].id - total = repo.total_cost_usd(project_id=project_id) - console.print(f"AI spend: ${total:.4f}") - - @app.command(name="list") def list_runs( project: Optional[str] = typer.Option(None, "--project", "-p", help="Filter by project name/URL substring."), @@ -356,8 +348,8 @@ def list_runs( table.add_column("Project") table.add_column("Skill") table.add_column("Agent") - table.add_column("Cost") table.add_column("Status") + table.add_column("Cost", justify="right") table.add_column("Run ID") for r in runs: @@ -367,8 +359,8 @@ def list_runs( r.project_display_name or "", r.skill_name, r.agent_id, - f"${r.cost_usd:.4f}" if r.cost_usd is not None else "-", f"[{style}]{r.status}[/]", + format_cost(r.cost_usd), r.run_uuid, ) console.print(table) @@ -393,7 +385,7 @@ def show( console.print(f"[bold]{record.skill_name}[/] via {record.agent_id} — status: {record.status}") if record.report_path and Path(record.report_path).exists(): - console.print(Path(record.report_path).read_text()) + console.print(Path(record.report_path).read_text(encoding="utf-8", errors="replace")) else: console.print("[yellow]No report content available for this run.[/]") @@ -428,6 +420,77 @@ def agents() -> None: console.print(table) +class CostGroup(str, Enum): + AGENT = "agent" + SKILL = "skill" + PROJECT = "project" + + +@app.command() +def cost( + by: CostGroup = typer.Option(CostGroup.AGENT, "--by", help="Group spend by agent, skill, or project."), + since: Optional[str] = typer.Option( + None, "--since", help="Only count runs started on or after this date, YYYY-MM-DD.", callback=_validate_date + ), + project: Optional[str] = typer.Option( + None, "--project", "-p", help="Only count one project (name/URL substring)." + ), +) -> None: + """Show AI spend (tokens and cost) across past runs.""" + with RunRepository() as repo: + project_id = None + if project: + needle = project.lower() + matches = [ + p for p in repo.list_projects() + if needle in p.display_name.lower() or needle in p.identifier.lower() + ] + if not matches: + console.print(f"[yellow]No project matches {project!r}.[/]") + return + if len(matches) > 1: + names = ", ".join(p.display_name for p in matches) + err_console.print(f"[red]{project!r} matches several projects ({names}) -- be more specific.[/]") + raise typer.Exit(code=1) + project_id = matches[0].id + rows = repo.cost_summary(group_by=by.value, since=since, project_id=project_id) + + if not rows: + console.print("No runs found.") + return + + table = Table(title=f"AI spend by {by.value}" + (f" since {since}" if since else "")) + table.add_column(by.value.capitalize()) + table.add_column("Runs", justify="right") + table.add_column("Input tokens", justify="right") + table.add_column("Output tokens", justify="right") + table.add_column("Cost", justify="right") + for row in rows: + table.add_row( + row.label, + str(row.runs), + format_tokens(row.input_tokens), + format_tokens(row.output_tokens), + format_cost(row.cost_usd) if row.unpriced_runs < row.runs else "-", + ) + table.add_section() + table.add_row( + "[bold]Total[/]", + str(sum(r.runs for r in rows)), + format_tokens(sum(r.input_tokens for r in rows)), + format_tokens(sum(r.output_tokens for r in rows)), + f"[bold]{format_cost(sum(r.cost_usd for r in rows))}[/]", + ) + console.print(table) + + unpriced = sum(r.unpriced_runs for r in rows) + if unpriced: + console.print( + f"[yellow]{unpriced} run(s) have no cost recorded[/] -- their agent doesn't report it " + "(cursor, agy), or they ran before cost tracking existed." + ) + + @assessment_app.command(name="create") def assessment_create( project: Optional[str] = typer.Option( @@ -1132,7 +1195,7 @@ def config_init( err_console.print(f"[yellow]{CONFIG_PATH} already exists.[/] Use --force to overwrite it.") raise typer.Exit(code=1) CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True) - CONFIG_PATH.write_text(CONFIG_EXAMPLE_PATH.read_text()) + CONFIG_PATH.write_text(CONFIG_EXAMPLE_PATH.read_text(encoding="utf-8"), encoding="utf-8") console.print(f"Wrote {CONFIG_PATH}. Edit it, then run [bold]secfoo mcp list[/] to confirm.") diff --git a/src/secfoo/cloud.py b/src/secfoo/cloud.py index 4f2e446..804432a 100644 --- a/src/secfoo/cloud.py +++ b/src/secfoo/cloud.py @@ -59,7 +59,7 @@ def load_cloud_config(path: Path | None = None) -> CloudConfig | None: if not path.exists(): return None try: - data = tomllib.loads(path.read_text()) + data = tomllib.loads(path.read_text(encoding="utf-8")) except tomllib.TOMLDecodeError as exc: raise CloudError(f"{path}: invalid TOML: {exc}") from exc api_key = data.get("api_key") @@ -73,7 +73,8 @@ def save_cloud_config(config: CloudConfig, path: Path | None = None) -> None: path.parent.mkdir(parents=True, exist_ok=True) path.write_text( f'api_key = "{_toml_escape(config.api_key)}"\n' - f'portal_url = "{_toml_escape(config.portal_url)}"\n' + f'portal_url = "{_toml_escape(config.portal_url)}"\n', + encoding="utf-8", ) path.chmod(0o600) @@ -145,6 +146,8 @@ def push_run( "started_at": run.started_at, "finished_at": run.finished_at, "duration_seconds": run.duration_seconds, + "input_tokens": run.input_tokens, + "output_tokens": run.output_tokens, "cost_usd": run.cost_usd, "confluence_urls": run.confluence_urls, }, @@ -187,7 +190,7 @@ def sync_run(repo: RunRepository, run_uuid: str, config: CloudConfig) -> None: report_markdown = "" if run.report_path and Path(run.report_path).is_file(): - report_markdown = Path(run.report_path).read_text() + report_markdown = Path(run.report_path).read_text(encoding="utf-8", errors="replace") assessment = repo.get_assessment(run.assessment_id) if run.assessment_id else None diff --git a/src/secfoo/config.example.toml b/src/secfoo/config.example.toml index 752d7a2..2092c97 100644 --- a/src/secfoo/config.example.toml +++ b/src/secfoo/config.example.toml @@ -5,6 +5,8 @@ [defaults] # Used whenever --agent / --depth / --timeout aren't passed on the command # line. CLI flags always win over these. +agent = "claude" # claude | agent (Cursor) | agy (Antigravity) | gemini | api (API key, no CLI) +agent = "claude" # claude | agent (Cursor) | agy (Antigravity) | gemini | secfoo agent = "claude" # claude | agent (Cursor) | agy (Antigravity) | gemini | secfoo | codex depth = "quick" # quick | standard # timeout = 1800 # seconds; omit to use each agent's own default diff --git a/src/secfoo/cost.py b/src/secfoo/cost.py new file mode 100644 index 0000000..12a6807 --- /dev/null +++ b/src/secfoo/cost.py @@ -0,0 +1,21 @@ +"""Display helpers for per-run AI spend, shared by the CLI and dashboard. + +None means the agent didn't report the value (Cursor and Antigravity print +plain text only), so it renders as "-" rather than a misleading $0.00. +""" + +from __future__ import annotations + + +def format_cost(value: float | None) -> str: + if value is None: + return "-" + if 0 < value < 0.01: + return "<$0.01" + return f"${value:,.2f}" + + +def format_tokens(value: int | None) -> str: + if value is None: + return "-" + return f"{value:,}" diff --git a/src/secfoo/mcp.py b/src/secfoo/mcp.py index b22adba..105e160 100644 --- a/src/secfoo/mcp.py +++ b/src/secfoo/mcp.py @@ -67,7 +67,7 @@ def write_claude_mcp_config(servers: list[MCPServerConfig]) -> Path | None: return None payload = {"mcpServers": {s.name: _server_to_standard_shape(s) for s in servers}} STORE_DIR.mkdir(parents=True, exist_ok=True) - CLAUDE_MCP_CONFIG_PATH.write_text(json.dumps(payload, indent=2)) + CLAUDE_MCP_CONFIG_PATH.write_text(json.dumps(payload, indent=2), encoding="utf-8") return CLAUDE_MCP_CONFIG_PATH @@ -123,7 +123,7 @@ def sync_cursor(servers: list[MCPServerConfig]) -> list[SyncResult]: existing: dict = {} if CURSOR_MCP_CONFIG_PATH.exists(): try: - existing = json.loads(CURSOR_MCP_CONFIG_PATH.read_text()).get("mcpServers", {}) + existing = json.loads(CURSOR_MCP_CONFIG_PATH.read_text(encoding="utf-8")).get("mcpServers", {}) except json.JSONDecodeError as exc: return [SyncResult("*", False, f"{CURSOR_MCP_CONFIG_PATH} is not valid JSON: {exc}")] @@ -138,7 +138,7 @@ def sync_cursor(servers: list[MCPServerConfig]) -> list[SyncResult]: results.append(SyncResult(server.name, True, f"added to {CURSOR_MCP_CONFIG_PATH}")) if newly_added: - CURSOR_MCP_CONFIG_PATH.write_text(json.dumps({"mcpServers": existing}, indent=2)) + CURSOR_MCP_CONFIG_PATH.write_text(json.dumps({"mcpServers": existing}, indent=2), encoding="utf-8") for name in newly_added: proc = subprocess.run(["agent", "mcp", "enable", name], capture_output=True, text=True, timeout=30) if proc.returncode != 0: diff --git a/src/secfoo/runner.py b/src/secfoo/runner.py index 3729243..6b34786 100644 --- a/src/secfoo/runner.py +++ b/src/secfoo/runner.py @@ -49,6 +49,9 @@ class RunOutcome: exit_code: int | None duration_seconds: float | None report_path: str | None + cost_usd: float | None = None + input_tokens: int | None = None + output_tokens: int | None = None def _project_display_name(resolved: ResolvedTarget) -> str: @@ -227,6 +230,8 @@ def _run_single_skill( medium_count=severity.medium, low_count=severity.low, info_count=severity.info, + input_tokens=result.input_tokens, + output_tokens=result.output_tokens, cost_usd=result.cost_usd, ) @@ -252,6 +257,9 @@ def _run_single_skill( exit_code=result.exit_code, duration_seconds=result.duration_seconds, report_path=str(report_path), + cost_usd=result.cost_usd, + input_tokens=result.input_tokens, + output_tokens=result.output_tokens, ) finally: repo.close() diff --git a/src/secfoo/settings.py b/src/secfoo/settings.py index 68d5051..bf1b997 100644 --- a/src/secfoo/settings.py +++ b/src/secfoo/settings.py @@ -82,7 +82,7 @@ def load_config(path: Path | None = None) -> SecfooConfig: return SecfooConfig(defaults=Defaults(), mcp_servers=[]) try: - data = tomllib.loads(path.read_text()) + data = tomllib.loads(path.read_text(encoding="utf-8")) except tomllib.TOMLDecodeError as exc: raise ConfigError(f"{path}: invalid TOML: {exc}") from exc diff --git a/src/secfoo/skills/loader.py b/src/secfoo/skills/loader.py index 611a220..579d391 100644 --- a/src/secfoo/skills/loader.py +++ b/src/secfoo/skills/loader.py @@ -53,7 +53,7 @@ def _parse_frontmatter(text: str, *, source: Path) -> tuple[dict[str, str], str] def _load_file(path: Path) -> Skill: - fields, body = _parse_frontmatter(path.read_text(), source=path) + fields, body = _parse_frontmatter(path.read_text(encoding="utf-8"), source=path) try: return Skill( id=fields["id"], diff --git a/src/secfoo/storage/models.py b/src/secfoo/storage/models.py index 747eeea..f2dfab2 100644 --- a/src/secfoo/storage/models.py +++ b/src/secfoo/storage/models.py @@ -37,6 +37,9 @@ class RunRecord: low_count: int = 0 info_count: int = 0 cloud_synced_at: str | None = None + input_tokens: int | None = None + output_tokens: int | None = None + cost_usd: float | None = None project_display_name: str | None = None cost_usd: float | None = None @@ -155,3 +158,13 @@ class SastFindingRecord: description: str | None = None recommendation: str | None = None project_display_name: str | None = None + + +@dataclass(frozen=True) +class CostRow: + label: str + runs: int + input_tokens: int + output_tokens: int + cost_usd: float + unpriced_runs: int diff --git a/src/secfoo/storage/repository.py b/src/secfoo/storage/repository.py index afcec39..075b6fd 100644 --- a/src/secfoo/storage/repository.py +++ b/src/secfoo/storage/repository.py @@ -39,6 +39,7 @@ def use_db_path(path: Path): from secfoo.storage.models import ( AssessmentRecord, AttachmentRecord, + CostRow, ExceptionRecord, OsvLookupRecord, PostBuildFindingRecord, @@ -68,6 +69,8 @@ def use_db_path(path: Path): # existed on an upgraded local store (re-synced harmlessly by `secfoo # cloud sync`, since ingestion is idempotent on the server side). "cloud_synced_at": "ALTER TABLE runs ADD COLUMN cloud_synced_at TEXT", + "input_tokens": "ALTER TABLE runs ADD COLUMN input_tokens INTEGER", + "output_tokens": "ALTER TABLE runs ADD COLUMN output_tokens INTEGER", "cost_usd": "ALTER TABLE runs ADD COLUMN cost_usd REAL", } @@ -102,10 +105,10 @@ def __init__(self, db_path: Path | None = None) -> None: # rollback-journal's writer lock. Requires local disk, not # NFS/EFS-backed storage, for the portal host. self._conn.execute("PRAGMA journal_mode = WAL") - self._conn.executescript(SCHEMA_PATH.read_text()) + self._conn.executescript(SCHEMA_PATH.read_text(encoding="utf-8")) self._conn.commit() self._migrate() - self._conn.executescript(SCHEMA_INDEXES_PATH.read_text()) + self._conn.executescript(SCHEMA_INDEXES_PATH.read_text(encoding="utf-8")) self._conn.commit() def _migrate(self) -> None: @@ -248,19 +251,23 @@ def create_completed_run( medium_count: int = 0, low_count: int = 0, info_count: int = 0, - cost_usd: float | None = None, assessment_id: int | None = None, + input_tokens: int | None = None, + output_tokens: int | None = None, + cost_usd: float | None = None, ) -> None: """Insert a run that already completed in another process.""" self._conn.execute( "INSERT INTO runs (run_uuid, project_id, skill_id, skill_name, agent_id, confluence_urls, " "status, exit_code, started_at, finished_at, duration_seconds, report_path, " - "critical_count, high_count, medium_count, low_count, info_count, cost_usd, assessment_id) " - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "critical_count, high_count, medium_count, low_count, info_count, assessment_id, " + "input_tokens, output_tokens, cost_usd) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ( run_uuid, project_id, skill_id, skill_name, agent_id, json.dumps(confluence_urls), status, exit_code, started_at, finished_at, duration_seconds, report_path, - critical_count, high_count, medium_count, low_count, info_count, cost_usd, assessment_id, + critical_count, high_count, medium_count, low_count, info_count, assessment_id, + input_tokens, output_tokens, cost_usd, ), ) self._conn.commit() @@ -280,12 +287,15 @@ def complete_run( medium_count: int = 0, low_count: int = 0, info_count: int = 0, + input_tokens: int | None = None, + output_tokens: int | None = None, cost_usd: float | None = None, ) -> None: self._conn.execute( "UPDATE runs SET status = ?, exit_code = ?, finished_at = ?, duration_seconds = ?, " "report_path = ?, prompt_path = ?, stderr_excerpt = ?, critical_count = ?, high_count = ?, " - "medium_count = ?, low_count = ?, info_count = ?, cost_usd = ? WHERE run_uuid = ?", + "medium_count = ?, low_count = ?, info_count = ?, input_tokens = ?, output_tokens = ?, " + "cost_usd = ? WHERE run_uuid = ?", ( status, exit_code, @@ -299,6 +309,8 @@ def complete_run( medium_count, low_count, info_count, + input_tokens, + output_tokens, cost_usd, run_uuid, ), @@ -397,6 +409,33 @@ def severity_totals(self, *, project_id: int | None = None) -> SeverityCounts: row = self._conn.execute(query, params).fetchone() return SeverityCounts(critical=row["c"], high=row["h"], medium=row["m"], low=row["l"], info=row["i"]) + def cost_summary(self, *, group_by: str, project_id: int | None = None, since: str | None = None) -> list[CostRow]: + """AI spend grouped by agent, skill, or project. Runs whose agent + doesn't report cost are counted in `unpriced_runs`, not as $0.""" + group_sql = { + "agent": "runs.agent_id", + "skill": "runs.skill_name", + "project": "projects.display_name", + }[group_by] + query = ( + f"SELECT {group_sql} AS label, COUNT(*) AS runs, " + "COALESCE(SUM(runs.input_tokens),0) AS input_tokens, " + "COALESCE(SUM(runs.output_tokens),0) AS output_tokens, " + "COALESCE(SUM(runs.cost_usd),0) AS cost_usd, " + "SUM(CASE WHEN runs.cost_usd IS NULL THEN 1 ELSE 0 END) AS unpriced_runs " + "FROM runs JOIN projects ON projects.id = runs.project_id " + "WHERE runs.status NOT IN ('pending','running')" + ) + params: list[object] = [] + if project_id is not None: + query += " AND runs.project_id = ?" + params.append(project_id) + if since is not None: + query += " AND runs.started_at >= ?" + params.append(since) + query += f" GROUP BY {group_sql} ORDER BY cost_usd DESC, runs DESC" + return [CostRow(**dict(row)) for row in self._conn.execute(query, params).fetchall()] + def assessment_severity_totals(self, assessment_id: int) -> SeverityCounts: row = self._conn.execute( "SELECT COALESCE(SUM(critical_count),0) c, COALESCE(SUM(high_count),0) h, " @@ -531,7 +570,7 @@ def _responsible_ai_badges(self, assessment_id: int, status: str) -> tuple[str | path = Path(row["report_path"]) if not path.exists(): return None, None - rating = extract_overall_risk_rating(path.read_text()) + rating = extract_overall_risk_rating(path.read_text(encoding="utf-8", errors="replace")) if rating is None: return None, None risk = "high-risk" if rating == "high" else "moderate" diff --git a/src/secfoo/storage/schema.sql b/src/secfoo/storage/schema.sql index e21ca23..f6f431c 100644 --- a/src/secfoo/storage/schema.sql +++ b/src/secfoo/storage/schema.sql @@ -63,10 +63,14 @@ CREATE TABLE IF NOT EXISTS runs ( medium_count INTEGER NOT NULL DEFAULT 0, low_count INTEGER NOT NULL DEFAULT 0, info_count INTEGER NOT NULL DEFAULT 0, + -- AI spend reported by the agent (see AgentAdapter.extract_usage). + -- NULL means the agent doesn't report it, not zero. + input_tokens INTEGER, + output_tokens INTEGER, + cost_usd REAL, -- Set once `secfoo cloud` has pushed this run to the enterprise -- portal. NULL means never synced (offline, or no `cloud login` yet). - cloud_synced_at TEXT, - cost_usd REAL + cloud_synced_at TEXT ); -- Files manually uploaded to an assessment (AI-BOM inventories, or other diff --git a/src/secfoo/web/dashboard_common.py b/src/secfoo/web/dashboard_common.py index 7a136ff..3bcef06 100644 --- a/src/secfoo/web/dashboard_common.py +++ b/src/secfoo/web/dashboard_common.py @@ -26,7 +26,9 @@ def read_report(path: str | None) -> str: file = Path(path) if not file.is_file(): return "" - return file.read_text() + # errors="replace": reports written by older versions on Windows used the + # locale code page, not UTF-8 -- show them with placeholders, never crash. + return file.read_text(encoding="utf-8", errors="replace") def append_boundary_changed_projects( diff --git a/src/secfoo/web/routes/activities.py b/src/secfoo/web/routes/activities.py index 010e3e3..d5e81f3 100644 --- a/src/secfoo/web/routes/activities.py +++ b/src/secfoo/web/routes/activities.py @@ -75,7 +75,7 @@ def _attach_architecture_signals(projects: list[dict]) -> bool: report_path = project.get("latest_success_report_path") if not report_path or not Path(report_path).is_file(): continue - text = Path(report_path).read_text() + text = Path(report_path).read_text(encoding="utf-8", errors="replace") project["diagram_source"] = extract_mermaid_diagram(text) project["design_verdict"] = extract_design_verdict(text) project["boundary_count"] = count_trust_boundaries(text) diff --git a/src/secfoo/web/routes/assessments.py b/src/secfoo/web/routes/assessments.py index 423909f..30b5703 100644 --- a/src/secfoo/web/routes/assessments.py +++ b/src/secfoo/web/routes/assessments.py @@ -65,11 +65,11 @@ def _run_third_party_risk_assessment(assessment_id: int, project_id: int) -> Non wrote_any = False for attachment in attachments: extracted_path = _extracted_text_path(Path(attachment.file_path)) - text = extracted_path.read_text() if extracted_path.exists() else "" + text = extracted_path.read_text(encoding="utf-8", errors="replace") if extracted_path.exists() else "" if not text.strip(): continue out_path = tmp_dir / f"{Path(attachment.original_name).stem}.txt" - out_path.write_text(f"Source document: {attachment.original_name}\n\n{text}") + out_path.write_text(f"Source document: {attachment.original_name}\n\n{text}", encoding="utf-8") wrote_any = True if not wrote_any: @@ -336,7 +336,7 @@ def assessment_upload(assessment_id: int, file: UploadFile): # (rather than re-extracted on every subsequent upload/trigger) # -- a vendor doc's content doesn't change after upload. text = docext.extract_text(dest) - _extracted_text_path(dest).write_text(text) + _extracted_text_path(dest).write_text(text, encoding="utf-8") if assessment.assessment_type == "third_party": trigger_third_party_review = True diff --git a/src/secfoo/web/routes/overview.py b/src/secfoo/web/routes/overview.py index c30f6fa..db943fa 100644 --- a/src/secfoo/web/routes/overview.py +++ b/src/secfoo/web/routes/overview.py @@ -19,8 +19,8 @@ def overview(request: Request): third_party_count = repo.count_assessments(assessment_type="third_party") responsible_ai_count = repo.count_assessments_with_responsible_ai_risk() models_count, tools_count = repo.ai_bom_counts_total() - total_cost_usd = repo.total_cost_usd() top_findings = build_top_findings(repo) + cost_by_agent = repo.cost_summary(group_by="agent") # Coverage is "projects that have had this activity run", so the # denominator is the project count -- see RunRepository.skill_coverage. @@ -48,7 +48,14 @@ def overview(request: Request): "responsible_ai_count": responsible_ai_count, "models_count": models_count, "tools_count": tools_count, - "total_cost_usd": total_cost_usd, "top_findings": top_findings, + "cost_by_agent": cost_by_agent, + # None (rendered "-") until at least one run has a known cost, + # so runs that predate tracking don't read as free. + "total_cost": ( + sum(row.cost_usd for row in cost_by_agent) + if any(row.unpriced_runs < row.runs for row in cost_by_agent) + else None + ), }, ) diff --git a/src/secfoo/web/routes/runs.py b/src/secfoo/web/routes/runs.py index f54d5c7..96b7eaf 100644 --- a/src/secfoo/web/routes/runs.py +++ b/src/secfoo/web/routes/runs.py @@ -21,7 +21,7 @@ def run_detail(request: Request, run_uuid: str): report_html = "" if record.report_path and Path(record.report_path).exists(): - text = Path(record.report_path).read_text() + text = Path(record.report_path).read_text(encoding="utf-8", errors="replace") if text.strip(): report_html = render_report_html(text) diff --git a/src/secfoo/web/templates/assessments/detail.html b/src/secfoo/web/templates/assessments/detail.html index 2685d61..0740e69 100644 --- a/src/secfoo/web/templates/assessments/detail.html +++ b/src/secfoo/web/templates/assessments/detail.html @@ -55,7 +55,7 @@

Attached runs

{% if runs %}
- + {% for run in runs %} @@ -63,6 +63,7 @@

Attached runs

+ {% endfor %} diff --git a/src/secfoo/web/templates/overview.html b/src/secfoo/web/templates/overview.html index 08787ef..4134c57 100644 --- a/src/secfoo/web/templates/overview.html +++ b/src/secfoo/web/templates/overview.html @@ -26,8 +26,8 @@

AI Security & Assessment Hub

Responsible AI coverage
- ${{ "%.4f" | format(total_cost_usd) }} - Recorded AI spend + {{ total_cost | fmt_cost }} + AI spend
@@ -96,6 +96,29 @@

Responsible AI risk mix

Open Responsible AI view + +
+

AI spend by agent

+ {% if cost_by_agent %} +
StartedSkillAgentStatus
StartedSkillAgentStatusCost
{{ run.skill_name }} {{ run.agent_id }} {{ run.status }}{{ run.cost_usd | fmt_cost }}
+ + + {% for row in cost_by_agent %} + + + + {% set priced = row.unpriced_runs < row.runs %} + + + + {% endfor %} + +
AgentRunsTokensCost
{{ row.label }}{{ row.runs }}{{ ((row.input_tokens + row.output_tokens) | fmt_tokens) if (priced or row.input_tokens or row.output_tokens) else '-' }}{{ (row.cost_usd | fmt_cost) if priced else '-' }}
+

"-" means no cost was recorded: the agent doesn't report it (cursor, agy), or the runs predate cost tracking.

+ {% else %} +

No runs yet.

+ {% endif %} +

Recent assessments

diff --git a/src/secfoo/web/templates/project.html b/src/secfoo/web/templates/project.html index b24136f..939addc 100644 --- a/src/secfoo/web/templates/project.html +++ b/src/secfoo/web/templates/project.html @@ -42,7 +42,7 @@

Runs

{{ run.agent_id }} {{ run.status }} {{ run.duration_seconds | fmt_duration }} - {{ ('$%.4f' % run.cost_usd) if run.cost_usd is not none else '-' }} + {{ run.cost_usd | fmt_cost }} {% endfor %} diff --git a/src/secfoo/web/templates/run_detail.html b/src/secfoo/web/templates/run_detail.html index e7bdc15..ba3b155 100644 --- a/src/secfoo/web/templates/run_detail.html +++ b/src/secfoo/web/templates/run_detail.html @@ -10,7 +10,8 @@

{{ run.skill_name }}

Agent
{{ run.agent_id }}
Started
{{ run.started_at | fmt_time }}
Duration
{{ run.duration_seconds | fmt_duration }}
-
AI cost
{{ ('$%.4f' % run.cost_usd) if run.cost_usd is not none else '-' }}
+
AI cost
{{ run.cost_usd | fmt_cost }}
+
Tokens (in / out)
{{ run.input_tokens | fmt_tokens }} / {{ run.output_tokens | fmt_tokens }}
Exit code
{{ run.exit_code if run.exit_code is not none else '-' }}
diff --git a/src/secfoo/web/templating.py b/src/secfoo/web/templating.py index 1e187d8..9cf9e29 100644 --- a/src/secfoo/web/templating.py +++ b/src/secfoo/web/templating.py @@ -4,6 +4,7 @@ from fastapi.templating import Jinja2Templates +from secfoo.cost import format_cost, format_tokens from secfoo.cvss import CvssError, parse_vector from secfoo.cvss import rating as cvss_rating from secfoo.report.architecture import classify_design_verdict @@ -219,6 +220,8 @@ def severity_rows(critical: int, high: int, medium: int, low: int, info: int) -> templates.env.filters["status_badge"] = status_badge_class templates.env.filters["fmt_time"] = format_timestamp templates.env.filters["fmt_duration"] = format_duration +templates.env.filters["fmt_cost"] = format_cost +templates.env.filters["fmt_tokens"] = format_tokens templates.env.filters["severity_badge"] = severity_badge_class templates.env.filters["cvss_badge"] = cvss_badge_class templates.env.filters["cvss_rating_label"] = cvss_rating_label diff --git a/tests/test_agents/test_api.py b/tests/test_agents/test_api.py new file mode 100644 index 0000000..c587ed8 --- /dev/null +++ b/tests/test_agents/test_api.py @@ -0,0 +1,180 @@ +from __future__ import annotations + +import sys +import types + +import pytest + +from secfoo.agents import api +from secfoo.agents.api import ApiAdapter, collect_files + + +@pytest.fixture +def no_keys(monkeypatch): + for key in api.KEY_VARS: + monkeypatch.delenv(key, raising=False) + + +GOOD_REPORT = "# SAST Report\n\n## Summary\nAll good.\n**Overall risk rating:** Low." + + +def _response(content, prompt_tokens=1200, completion_tokens=300): + return types.SimpleNamespace( + choices=[types.SimpleNamespace(message=types.SimpleNamespace(content=content))], + usage=types.SimpleNamespace(prompt_tokens=prompt_tokens, completion_tokens=completion_tokens), + ) + + +def _fake_litellm(monkeypatch, *, completion=None, cost=0.0123): + module = types.SimpleNamespace() + module.calls = [] + + def _completion(**kwargs): + module.calls.append(kwargs) + if completion is not None: + return completion(**kwargs) + return _response(GOOD_REPORT) + + def _completion_cost(completion_response): + if isinstance(cost, Exception): + raise cost + return cost + + module.completion = _completion + module.completion_cost = _completion_cost + monkeypatch.setitem(sys.modules, "litellm", module) + return module + + +def test_collect_files_labels_files_and_skips_excluded_paths(tmp_path): + (tmp_path / "app.py").write_text("print('hi')", encoding="utf-8") + (tmp_path / "node_modules").mkdir() + (tmp_path / "node_modules" / "dep.js").write_text("junk", encoding="utf-8") + (tmp_path / "bundle.min.js").write_text("junk", encoding="utf-8") + (tmp_path / "logo.png").write_bytes(b"\x89PNG\r\n\x1a\n\xff\xfe") + + text = collect_files(tmp_path) + + assert "===== FILE: app.py =====" in text + assert "print('hi')" in text + assert "dep.js" not in text + assert "bundle.min.js" not in text + assert "logo.png" not in text + + +def test_collect_files_rejects_a_target_over_the_size_limit(tmp_path, monkeypatch): + monkeypatch.setattr(api, "MAX_TOTAL_CHARS", 50) + (tmp_path / "big.py").write_text("x" * 100, encoding="utf-8") + with pytest.raises(ValueError, match="too large"): + collect_files(tmp_path) + + +def test_is_available_depends_on_an_api_key(no_keys, monkeypatch): + assert ApiAdapter().is_available() is False + monkeypatch.setenv("OPENAI_API_KEY", "sk-test") + assert ApiAdapter().is_available() is True + + +def test_run_without_a_key_explains_what_to_set(no_keys, tmp_path): + result = ApiAdapter().run("prompt", workdir=tmp_path) + assert result.status == "binary_not_found" + assert "OPENAI_API_KEY" in result.stderr + + +def test_run_success_returns_report_and_usage(tmp_path, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "sk-test") + monkeypatch.setenv("SECFOO_API_MODEL", "openai/test-model") + (tmp_path / "app.py").write_text("print('hi')", encoding="utf-8") + fake = _fake_litellm(monkeypatch) + + result = ApiAdapter().run("Review this.", workdir=tmp_path) + + assert result.status == "success" + assert result.raw_report == GOOD_REPORT + assert result.input_tokens == 1200 + assert result.output_tokens == 300 + assert result.cost_usd == pytest.approx(0.0123) + assert len(fake.calls) == 1 # a complete report needs no reformat + call = fake.calls[0] + assert call["model"] == "openai/test-model" + assert call["num_retries"] == api.NUM_RETRIES + content = call["messages"][0]["content"] + assert content.startswith("Review this.") + assert "===== FILE: app.py =====" in content + + +def test_run_success_with_unpriced_model_keeps_tokens_and_leaves_cost_unknown(tmp_path, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "sk-test") + _fake_litellm(monkeypatch, cost=RuntimeError("no price for model")) + + result = ApiAdapter().run("prompt", workdir=tmp_path) + + assert result.status == "success" + assert result.input_tokens == 1200 + assert result.cost_usd is None + + +def test_run_api_error_becomes_a_failed_run(tmp_path, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "sk-test") + + def _boom(**kwargs): + raise RuntimeError("Incorrect API key provided") + + _fake_litellm(monkeypatch, completion=_boom) + + result = ApiAdapter().run("prompt", workdir=tmp_path) + + assert result.status == "failed" + assert "Incorrect API key" in result.stderr + assert result.raw_report == "" + assert result.cost_usd is None + + +def test_run_strips_a_trailing_newline_from_the_key(tmp_path, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "sk-test\n") + _fake_litellm(monkeypatch) + + result = ApiAdapter().run("prompt", workdir=tmp_path) + + assert result.status == "success" + assert api.os.environ["OPENAI_API_KEY"] == "sk-test" + + +def test_run_without_litellm_installed_says_how_to_install_it(tmp_path, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "sk-test") + monkeypatch.setitem(sys.modules, "litellm", None) # makes `import litellm` raise ImportError + + result = ApiAdapter().run("prompt", workdir=tmp_path) + + assert result.status == "failed" + assert "secfoo[api]" in result.stderr + + +def test_incomplete_report_is_reformatted_once_without_resending_source(tmp_path, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "sk-test") + (tmp_path / "app.py").write_text("print('hi')", encoding="utf-8") + replies = iter([_response("### [HIGH] SQL injection in app.py"), _response(GOOD_REPORT, 400, 100)]) + fake = _fake_litellm(monkeypatch, completion=lambda **kwargs: next(replies)) + + result = ApiAdapter().run("Review this.", workdir=tmp_path) + + assert result.status == "success" + assert result.raw_report == GOOD_REPORT + assert len(fake.calls) == 2 + fix_request = fake.calls[1]["messages"][0]["content"] + assert "SQL injection in app.py" in fix_request # the draft is passed back + assert "===== FILE: app.py =====" not in fix_request # the source is not + assert result.input_tokens == 1600 # usage and cost add up across both calls + assert result.output_tokens == 400 + assert result.cost_usd == pytest.approx(0.0246) + + +def test_reformat_is_attempted_only_once(tmp_path, monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "sk-test") + fake = _fake_litellm(monkeypatch, completion=lambda **kwargs: _response("no rating here")) + + result = ApiAdapter().run("prompt", workdir=tmp_path) + + assert result.status == "success" + assert result.raw_report == "no rating here" + assert len(fake.calls) == api.MAX_ATTEMPTS diff --git a/tests/test_agents/test_claude.py b/tests/test_agents/test_claude.py index 635dbbe..92aaee0 100644 --- a/tests/test_agents/test_claude.py +++ b/tests/test_agents/test_claude.py @@ -70,3 +70,36 @@ def test_run_success_extracts_report_from_json(fake_popen, tmp_path, monkeypatch result = adapter.run("review this", workdir=tmp_path) assert result.status == "success" assert result.raw_report == "# Threat Report" + + +def test_extract_usage_reads_cost_and_sums_cached_input_tokens(): + stdout = json.dumps({ + "result": "report", + "total_cost_usd": 0.4512, + "usage": { + "input_tokens": 100, + "cache_creation_input_tokens": 2000, + "cache_read_input_tokens": 30000, + "output_tokens": 4000, + }, + }) + usage = ClaudeAdapter().extract_usage(stdout) + assert usage.input_tokens == 32100 + assert usage.output_tokens == 4000 + assert usage.cost_usd == 0.4512 + + +def test_extract_usage_unknown_when_stdout_is_not_json(): + usage = ClaudeAdapter().extract_usage("plain text") + assert usage.cost_usd is None + assert usage.input_tokens is None + + +def test_run_records_usage_from_json_output(tmp_path, monkeypatch, fake_popen): + monkeypatch.setattr("secfoo.agents.claude.load_config", lambda: _empty_config()) + stdout = json.dumps({"result": "report", "total_cost_usd": 1.5, "usage": {"input_tokens": 10, "output_tokens": 5}}) + fake_popen(returncode=0, stdout=stdout) + result = ClaudeAdapter().run("prompt", workdir=tmp_path) + assert result.cost_usd == 1.5 + assert result.input_tokens == 10 + assert result.output_tokens == 5 diff --git a/tests/test_agents/test_gemini.py b/tests/test_agents/test_gemini.py index b8aa4ed..12b2223 100644 --- a/tests/test_agents/test_gemini.py +++ b/tests/test_agents/test_gemini.py @@ -27,3 +27,24 @@ def test_extract_report_result_key_fallback(): def test_extract_report_non_json_passthrough(): adapter = GeminiAdapter() assert adapter.extract_report("plain text") == "plain text" + + +def test_extract_usage_sums_tokens_across_models_without_cost(): + stdout = json.dumps({ + "response": "report", + "stats": { + "models": { + "gemini-pro": {"tokens": {"prompt": 1000, "candidates": 200}}, + "gemini-flash": {"tokens": {"prompt": 50, "candidates": 5}}, + } + }, + }) + usage = GeminiAdapter().extract_usage(stdout) + assert usage.input_tokens == 1050 + assert usage.output_tokens == 205 + assert usage.cost_usd is None + + +def test_extract_usage_unknown_without_stats(): + assert GeminiAdapter().extract_usage(json.dumps({"response": "r"})).input_tokens is None + assert GeminiAdapter().extract_usage("not json").input_tokens is None diff --git a/tests/test_cli.py b/tests/test_cli.py index b7deceb..d8d5e7c 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -8,7 +8,7 @@ from secfoo.runner import RunOutcome from secfoo.settings import Defaults, MCPServerConfig, SecfooConfig from secfoo.skills.loader import load_all_skills -from secfoo.storage.models import ProjectRecord +from secfoo.storage.models import CostRow, ProjectRecord runner = CliRunner() @@ -247,13 +247,17 @@ def total_cost_usd(self, *, project_id=None): self.requested_project_id = project_id return self._total + def cost_summary(self, *, group_by, project_id=None, since=None): + self.requested_project_id = project_id + return [CostRow(label="secfoo", runs=1, input_tokens=100, output_tokens=10, cost_usd=self._total, unpriced_runs=0)] + def test_cost_command_prints_total_spend(monkeypatch): fake = _FakeRepoWithCost(total=1.2345) monkeypatch.setattr("secfoo.cli.RunRepository", lambda *a, **kw: fake) result = runner.invoke(app, ["cost"]) assert result.exit_code == 0 - assert "$1.2345" in result.stdout + assert "$1.23" in result.stdout assert fake.requested_project_id is None @@ -266,7 +270,7 @@ def test_cost_command_filters_by_matching_project(monkeypatch): monkeypatch.setattr("secfoo.cli.RunRepository", lambda *a, **kw: fake) result = runner.invoke(app, ["cost", "--project", "acme"]) assert result.exit_code == 0 - assert "$0.5000" in result.stdout + assert "$0.50" in result.stdout assert fake.requested_project_id == 7 diff --git a/tests/test_cloud.py b/tests/test_cloud.py index b50eb6e..609e878 100644 --- a/tests/test_cloud.py +++ b/tests/test_cloud.py @@ -302,3 +302,24 @@ def test_sync_run_does_not_mark_synced_on_push_failure(tmp_path, fake_urlopen): assert repo.get_run(run_uuid).cloud_synced_at is None repo.close() + + +def test_sync_run_includes_ai_usage_and_cost(tmp_path, fake_urlopen): + calls = fake_urlopen(response={"server_run_id": "u1", "status": "recorded"}) + repo = RunRepository(db_path=tmp_path / "db.sqlite") + project_id = repo.upsert_project("https://github.com/acme/app", "acme/app", "github") + run_uuid = repo.create_run( + project_id=project_id, skill_id="sast", skill_name="SAST", agent_id="api", confluence_urls=[], + ) + repo.complete_run( + run_uuid, status="success", exit_code=0, duration_seconds=1.0, report_path=None, + prompt_path=None, stderr_excerpt=None, input_tokens=1000, output_tokens=200, cost_usd=0.25, + ) + + cloud.sync_run(repo, run_uuid, cloud.CloudConfig(api_key="k", portal_url="https://portal.example.com")) + + run = json.loads(calls[0].data.decode("utf-8"))["run"] + assert run["input_tokens"] == 1000 + assert run["output_tokens"] == 200 + assert run["cost_usd"] == 0.25 + repo.close() diff --git a/tests/test_cost.py b/tests/test_cost.py new file mode 100644 index 0000000..696041e --- /dev/null +++ b/tests/test_cost.py @@ -0,0 +1,213 @@ +from __future__ import annotations + +import sqlite3 + +import pytest +from fastapi.testclient import TestClient +from typer.testing import CliRunner + +from secfoo.cli import app +from secfoo.cost import format_cost, format_tokens +from secfoo.runner import RunOutcome +from secfoo.storage.repository import RunRepository +from secfoo.web.app import create_app + +runner = CliRunner() + + +@pytest.fixture +def db(tmp_path, monkeypatch): + monkeypatch.setattr("secfoo.storage.repository.DB_PATH", tmp_path / "db.sqlite") + monkeypatch.setattr("secfoo.storage.repository.ensure_store_dirs", lambda: None) + return tmp_path + + +def _seed(*, agent_id: str, skill: str = "SAST", project: str = "org/repo", cost=None, tokens=None, status="success"): + repo = RunRepository() + project_id = repo.upsert_project(f"https://github.com/{project}", project, "github") + run_uuid = repo.create_run( + project_id=project_id, + skill_id=skill.lower(), + skill_name=skill, + agent_id=agent_id, + confluence_urls=[], + ) + repo.complete_run( + run_uuid, + status=status, + exit_code=0, + duration_seconds=1.0, + report_path=None, + prompt_path=None, + stderr_excerpt=None, + input_tokens=tokens[0] if tokens else None, + output_tokens=tokens[1] if tokens else None, + cost_usd=cost, + ) + repo.close() + return run_uuid + + +def test_format_cost_and_tokens(): + assert format_cost(None) == "-" + assert format_cost(0.0) == "$0.00" + assert format_cost(0.004) == "<$0.01" + assert format_cost(1234.5) == "$1,234.50" + assert format_tokens(None) == "-" + assert format_tokens(1234567) == "1,234,567" + + +def test_complete_run_stores_usage(db): + run_uuid = _seed(agent_id="api", cost=0.25, tokens=(1000, 200)) + with RunRepository() as repo: + run = repo.get_run(run_uuid) + assert run.cost_usd == 0.25 + assert run.input_tokens == 1000 + assert run.output_tokens == 200 + + +def test_cost_summary_groups_and_counts_unpriced_runs(db): + _seed(agent_id="api", cost=0.25, tokens=(1000, 200)) + _seed(agent_id="api", skill="Threat Modeling", cost=0.75, tokens=(3000, 400)) + _seed(agent_id="agent") # cursor: no usage reported + _seed(agent_id="api", status="running", cost=9.0) # in flight: excluded + + with RunRepository() as repo: + rows = {r.label: r for r in repo.cost_summary(group_by="agent")} + + assert rows["api"].runs == 2 + assert rows["api"].cost_usd == pytest.approx(1.0) + assert rows["api"].input_tokens == 4000 + assert rows["api"].unpriced_runs == 0 + assert rows["agent"].cost_usd == 0 + assert rows["agent"].unpriced_runs == 1 + + +def test_cost_summary_since_filters_old_runs(db): + _seed(agent_id="api", cost=0.5) + with RunRepository() as repo: + assert repo.cost_summary(group_by="skill", since="2999-01-01") == [] + assert len(repo.cost_summary(group_by="skill", since="2000-01-01")) == 1 + + +def test_existing_db_without_cost_columns_migrates_cleanly(tmp_path): + db_path = tmp_path / "old.db" + conn = sqlite3.connect(db_path) + conn.execute( + "CREATE TABLE runs (id INTEGER PRIMARY KEY AUTOINCREMENT, run_uuid TEXT NOT NULL UNIQUE, " + "project_id INTEGER NOT NULL, skill_id TEXT NOT NULL, skill_name TEXT NOT NULL, agent_id TEXT NOT NULL, " + "confluence_urls TEXT NOT NULL DEFAULT '[]', status TEXT NOT NULL, exit_code INTEGER, " + "started_at TEXT NOT NULL, finished_at TEXT, duration_seconds REAL, report_path TEXT, " + "prompt_path TEXT, stderr_excerpt TEXT)" + ) + conn.commit() + conn.close() + + repo = RunRepository(db_path=db_path) + columns = {row["name"] for row in repo._conn.execute("PRAGMA table_info(runs)").fetchall()} + repo.close() + assert {"input_tokens", "output_tokens", "cost_usd"} <= columns + + +def test_cost_command_shows_totals_and_unpriced_note(db): + _seed(agent_id="api", cost=0.25, tokens=(1000, 200)) + _seed(agent_id="agent") + + result = runner.invoke(app, ["cost"]) + + assert result.exit_code == 0 + assert "api" in result.stdout + assert "$0.25" in result.stdout + assert "1 run(s) have no cost recorded" in result.stdout + + +def test_cost_command_rejects_bad_since_date(db): + result = runner.invoke(app, ["cost", "--since", "last week"]) + assert result.exit_code != 0 + + +def test_cost_command_empty_store(db): + result = runner.invoke(app, ["cost", "--by", "project"]) + assert result.exit_code == 0 + assert "No runs found" in result.stdout + + +def test_run_command_prints_cost_per_skill_and_total(monkeypatch): + outcomes = [ + RunOutcome( + run_uuid=f"u{i}", + skill_id="sast", + skill_name=f"Skill {i}", + agent_id="api", + status="success", + exit_code=0, + duration_seconds=1.0, + report_path=None, + cost_usd=cost, + ) + for i, cost in enumerate([0.5, 1.25]) + ] + monkeypatch.setattr("secfoo.cli.execute_runs", lambda **kwargs: outcomes) + + result = runner.invoke(app, ["run", "--skill", "sast", "--agent", "api"]) + + assert result.exit_code == 0 + assert "$1.25" in result.stdout + assert "AI spend for this run: $1.75" in result.stdout + + +def test_dashboard_shows_run_cost_and_overview_spend(db): + run_uuid = _seed(agent_id="api", cost=0.25, tokens=(1000, 200)) + client = TestClient(create_app()) + + run_page = client.get(f"/runs/{run_uuid}") + assert run_page.status_code == 200 + assert "AI cost" in run_page.text + assert "$0.25" in run_page.text + assert "1,000 / 200" in run_page.text + + overview = client.get("/") + assert overview.status_code == 200 + assert "AI spend by agent" in overview.text + assert "$0.25" in overview.text + + +def test_overview_spend_is_unknown_not_zero_when_no_run_has_a_cost(db): + _seed(agent_id="agent") + overview = TestClient(create_app()).get("/") + assert "$0.00" not in overview.text + assert "AI spend" in overview.text + + +def test_create_completed_run_keeps_usage_for_portal_ingestion(tmp_path): + repo = RunRepository(db_path=tmp_path / "db.sqlite") + project_id = repo.upsert_project("id-1", "P1", "local") + repo.create_completed_run( + run_uuid="remote-1", project_id=project_id, skill_id="sast", skill_name="SAST", agent_id="api", + confluence_urls=[], status="success", exit_code=0, started_at="2026-09-21T00:00:00+00:00", + finished_at=None, duration_seconds=1.0, report_path=None, + input_tokens=1000, output_tokens=200, cost_usd=0.25, + ) + run = repo.get_run("remote-1") + repo.close() + assert (run.input_tokens, run.output_tokens, run.cost_usd) == (1000, 200, 0.25) + + +def test_cost_command_filters_by_project(db): + _seed(agent_id="api", project="acme/checkout", cost=0.25) + _seed(agent_id="api", project="acme/billing", cost=5.0) + + result = runner.invoke(app, ["cost", "--project", "checkout"]) + + assert result.exit_code == 0 + assert "$0.25" in result.stdout + assert "$5.00" not in result.stdout + + +def test_cost_command_rejects_ambiguous_or_unknown_project(db): + _seed(agent_id="api", project="acme/checkout", cost=0.25) + _seed(agent_id="api", project="acme/billing", cost=5.0) + + assert runner.invoke(app, ["cost", "--project", "acme"]).exit_code == 1 + unknown = runner.invoke(app, ["cost", "--project", "nope"]) + assert "No project matches" in unknown.stdout