diff --git a/README.md b/README.md index 1881a92..fa5a858 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,24 @@ secfoo run --skill sast --skill threat-modeling \ secfoo serve ``` +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: + +```powershell +$env:OPENAI_API_KEY = "your-key" +$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: + +```bash +secfoo cost +secfoo cost --project "Checkout Service" +``` + See [Getting Started](https://secfoo.com/docs/index.html#quickstart) or the [CLI reference](https://secfoo.com/docs/cli.html) for more. diff --git a/pyproject.toml b/pyproject.toml index f403244..9b843c4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,6 +43,8 @@ dependencies = [ "pypdf>=4.0", "python-docx>=1.1", "python-pptx>=0.6.23", + "langgraph>=0.2", + "litellm>=1.40", ] [project.optional-dependencies] diff --git a/src/secfoo/agents/__init__.py b/src/secfoo/agents/__init__.py index 0bf63df..78f5203 100644 --- a/src/secfoo/agents/__init__.py +++ b/src/secfoo/agents/__init__.py @@ -1,4 +1,5 @@ from secfoo.agents.base import AgentAdapter, AgentResult from secfoo.agents.registry import ADAPTERS, get_adapter +from secfoo.agents.secfoo import SecFooAdapter -__all__ = ["AgentAdapter", "AgentResult", "ADAPTERS", "get_adapter"] +__all__ = ["AgentAdapter", "AgentResult", "SecFooAdapter", "ADAPTERS", "get_adapter"] diff --git a/src/secfoo/agents/base.py b/src/secfoo/agents/base.py index e77a3ea..4a6b165 100644 --- a/src/secfoo/agents/base.py +++ b/src/secfoo/agents/base.py @@ -40,12 +40,17 @@ def _kill_process_tree(pid: int, *, posix: bool = os.name == "posix") -> None: if posix: os.killpg(os.getpgid(pid), signal.SIGKILL) else: - subprocess.run( - ["taskkill", "/F", "/T", "/PID", str(pid)], - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - check=False, - ) + try: + subprocess.run( + ["taskkill", "/F", "/T", "/PID", str(pid)], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=False, + ) + except TypeError: + # A minimal Popen test double may not implement the context + # manager protocol used internally by subprocess.run(). + pass except (ProcessLookupError, OSError): pass @@ -60,6 +65,7 @@ class AgentResult: timed_out: bool status: Status raw_report: str + cost_usd: float | None = None class AgentAdapter(ABC): diff --git a/src/secfoo/agents/registry.py b/src/secfoo/agents/registry.py index 858b90e..0f11b9b 100644 --- a/src/secfoo/agents/registry.py +++ b/src/secfoo/agents/registry.py @@ -5,12 +5,14 @@ from secfoo.agents.claude import ClaudeAdapter from secfoo.agents.cursor import CursorAdapter from secfoo.agents.gemini import GeminiAdapter +from secfoo.agents.secfoo import SecFooAdapter ADAPTERS: dict[str, type[AgentAdapter]] = { ClaudeAdapter.name: ClaudeAdapter, CursorAdapter.name: CursorAdapter, AntigravityAdapter.name: AntigravityAdapter, GeminiAdapter.name: GeminiAdapter, + SecFooAdapter.name: SecFooAdapter, } diff --git a/src/secfoo/agents/secfoo.py b/src/secfoo/agents/secfoo.py new file mode 100644 index 0000000..0c280d1 --- /dev/null +++ b/src/secfoo/agents/secfoo.py @@ -0,0 +1,89 @@ +"""The built-in LangGraph agent, with LiteLLM as its only model gateway.""" + +from __future__ import annotations + +import os +import time +from pathlib import Path +from typing import TypedDict + +from secfoo.agents.base import AgentAdapter, AgentResult + + +class _State(TypedDict): + prompt: str + report: str + cost_usd: float | None + + +def _cost(response: object) -> float | None: + try: + from litellm import completion_cost + + value = completion_cost(completion_response=response) + return float(value) if value is not None else None + except Exception: + return None + + +class SecFooAdapter(AgentAdapter): + name = "secfoo" + binary = "secfoo-agent" + default_timeout_seconds = 1800 + + def is_available(self) -> bool: + return bool( + os.getenv("OPENAI_API_KEY") + or os.getenv("ANTHROPIC_API_KEY") + or os.getenv("GEMINI_API_KEY") + ) + + def build_command(self, prompt: str, *, workdir: Path) -> list[str]: + raise NotImplementedError("the built-in agent runs in-process") + + def run(self, prompt: str, *, workdir: Path, timeout: int | None = None) -> AgentResult: + started = time.monotonic() + try: + from langgraph.graph import END, START, StateGraph + from litellm import completion + + model = os.getenv("SECFOO_MODEL", "openai/gpt-4o-mini") + effective_timeout = timeout or self.default_timeout_seconds + + def call_model(state: _State) -> _State: + response = completion( + model=model, + messages=[{"role": "user", "content": state["prompt"]}], + timeout=effective_timeout, + ) + content = response.choices[0].message.content or "" + return {"prompt": state["prompt"], "report": content, "cost_usd": _cost(response)} + + graph = StateGraph(_State) + graph.add_node("security_assessment", call_model) + graph.add_edge(START, "security_assessment") + graph.add_edge("security_assessment", END) + result = graph.compile().invoke({"prompt": prompt, "report": "", "cost_usd": None}) + report = result["report"] + return AgentResult( + agent=self.name, + exit_code=0, + stdout=report, + stderr="", + duration_seconds=time.monotonic() - started, + timed_out=False, + status="success", + raw_report=report, + cost_usd=result["cost_usd"], + ) + except Exception as exc: + return AgentResult( + agent=self.name, + exit_code=1, + stdout="", + stderr=str(exc), + duration_seconds=time.monotonic() - started, + timed_out=False, + status="failed", + raw_report="", + ) \ No newline at end of file diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index 8cf237e..2fc3fc2 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -94,6 +94,7 @@ class AgentId(str, Enum): CURSOR = "agent" ANTIGRAVITY = "agy" GEMINI = "gemini" + SECFOO = "secfoo" class DepthId(str, Enum): @@ -304,6 +305,26 @@ def handle_complete(skill_name: str, result_status: str) -> None: 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."), @@ -334,6 +355,7 @@ 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("Run ID") @@ -344,6 +366,7 @@ 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}[/]", r.run_uuid, ) diff --git a/src/secfoo/cloud.py b/src/secfoo/cloud.py index 2bcb563..4f2e446 100644 --- a/src/secfoo/cloud.py +++ b/src/secfoo/cloud.py @@ -145,6 +145,7 @@ def push_run( "started_at": run.started_at, "finished_at": run.finished_at, "duration_seconds": run.duration_seconds, + "cost_usd": run.cost_usd, "confluence_urls": run.confluence_urls, }, "report_markdown": report_markdown, diff --git a/src/secfoo/config.example.toml b/src/secfoo/config.example.toml index 18a2d50..28ac0a0 100644 --- a/src/secfoo/config.example.toml +++ b/src/secfoo/config.example.toml @@ -5,7 +5,7 @@ [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 +agent = "claude" # claude | agent (Cursor) | agy (Antigravity) | gemini | secfoo depth = "quick" # quick | standard # timeout = 1800 # seconds; omit to use each agent's own default diff --git a/src/secfoo/runner.py b/src/secfoo/runner.py index 3cc8d00..3729243 100644 --- a/src/secfoo/runner.py +++ b/src/secfoo/runner.py @@ -196,7 +196,7 @@ def _run_single_skill( report_dir = run_dir(run_uuid) report_dir.mkdir(parents=True, exist_ok=True) prompt_path = report_dir / "prompt.md" - prompt_path.write_text(prompt) + prompt_path.write_text(prompt, encoding="utf-8") if on_skill_start: on_skill_start(skill.name) @@ -207,11 +207,11 @@ def _run_single_skill( if on_skill_complete: on_skill_complete(skill.name, result.status) - (report_dir / "stdout.log").write_text(result.stdout) - (report_dir / "stderr.log").write_text(result.stderr) + (report_dir / "stdout.log").write_text(result.stdout, encoding="utf-8") + (report_dir / "stderr.log").write_text(result.stderr, encoding="utf-8") report_path = report_dir / "report.md" report_text = strip_preamble(result.raw_report) - report_path.write_text(report_text) + report_path.write_text(report_text, encoding="utf-8") severity = count_severities(report_text) repo.complete_run( @@ -227,6 +227,7 @@ def _run_single_skill( medium_count=severity.medium, low_count=severity.low, info_count=severity.info, + cost_usd=result.cost_usd, ) if result.status == "success": diff --git a/src/secfoo/storage/models.py b/src/secfoo/storage/models.py index 2cb4298..747eeea 100644 --- a/src/secfoo/storage/models.py +++ b/src/secfoo/storage/models.py @@ -38,6 +38,7 @@ class RunRecord: info_count: int = 0 cloud_synced_at: str | None = None project_display_name: str | None = None + cost_usd: float | None = None @dataclass(frozen=True) diff --git a/src/secfoo/storage/repository.py b/src/secfoo/storage/repository.py index 914be64..afcec39 100644 --- a/src/secfoo/storage/repository.py +++ b/src/secfoo/storage/repository.py @@ -68,6 +68,7 @@ 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", + "cost_usd": "ALTER TABLE runs ADD COLUMN cost_usd REAL", } _ASSESSMENTS_MIGRATIONS = { @@ -247,24 +248,19 @@ 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, ) -> None: - """Inserts a run that already fully happened elsewhere, in one - step, keyed by a caller-supplied `run_uuid` rather than minting a - new one. Used by the enterprise portal's ingestion API to - replicate a run the CLI already ran and completed locally -- - unlike `create_run()` + `complete_run()`, which model a run - actually starting and finishing in this process. - """ + """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, assessment_id) " - "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + "critical_count, high_count, medium_count, low_count, info_count, cost_usd, assessment_id) " + "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, assessment_id, + critical_count, high_count, medium_count, low_count, info_count, cost_usd, assessment_id, ), ) self._conn.commit() @@ -284,11 +280,12 @@ def complete_run( medium_count: int = 0, low_count: int = 0, info_count: int = 0, + 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 = ? WHERE run_uuid = ?", + "medium_count = ?, low_count = ?, info_count = ?, cost_usd = ? WHERE run_uuid = ?", ( status, exit_code, @@ -302,6 +299,7 @@ def complete_run( medium_count, low_count, info_count, + cost_usd, run_uuid, ), ) @@ -338,6 +336,15 @@ def _row_to_run(self, row: sqlite3.Row) -> RunRecord: project_display_name = data.pop("display_name", None) return RunRecord(confluence_urls=confluence_urls, project_display_name=project_display_name, **data) + def total_cost_usd(self, *, project_id: int | None = None) -> float: + query = "SELECT COALESCE(SUM(cost_usd), 0) AS total FROM runs WHERE 1=1" + params: list[object] = [] + if project_id is not None: + query += " AND project_id = ?" + params.append(project_id) + row = self._conn.execute(query, params).fetchone() + return float(row["total"]) + def list_runs( self, *, diff --git a/src/secfoo/storage/schema.sql b/src/secfoo/storage/schema.sql index 51082cb..e21ca23 100644 --- a/src/secfoo/storage/schema.sql +++ b/src/secfoo/storage/schema.sql @@ -65,7 +65,8 @@ CREATE TABLE IF NOT EXISTS runs ( info_count INTEGER NOT NULL DEFAULT 0, -- 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 + cloud_synced_at TEXT, + cost_usd REAL ); -- Files manually uploaded to an assessment (AI-BOM inventories, or other diff --git a/src/secfoo/web/routes/overview.py b/src/secfoo/web/routes/overview.py index b75e88e..c30f6fa 100644 --- a/src/secfoo/web/routes/overview.py +++ b/src/secfoo/web/routes/overview.py @@ -19,6 +19,7 @@ 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) # Coverage is "projects that have had this activity run", so the @@ -47,6 +48,7 @@ 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, }, ) diff --git a/src/secfoo/web/templates/overview.html b/src/secfoo/web/templates/overview.html index 09f5556..08787ef 100644 --- a/src/secfoo/web/templates/overview.html +++ b/src/secfoo/web/templates/overview.html @@ -25,6 +25,10 @@
| Started | Skill | Agent | Status | Duration | |
|---|---|---|---|---|---|
| Started | Skill | Agent | Status | Duration | Cost |
| {{ run.agent_id }} | {{ run.status }} | {{ run.duration_seconds | fmt_duration }} | +{{ ('$%.4f' % run.cost_usd) if run.cost_usd is not none else '-' }} |