Skip to content
Merged
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
51 changes: 36 additions & 15 deletions docs/REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -834,6 +834,11 @@ secfoo serve

# AI spend across past runs
secfoo cost --by skill --since 2026-09-01
secfoo cost --by model

# Discover models available for installed agents
secfoo models
secfoo models --agent claude --refresh
```

### CI gates and machine-readable output
Expand Down Expand Up @@ -977,6 +982,8 @@ wiring each agent CLI separately.

```bash
secfoo config init # writes a starter ~/.secfoo/config.toml
secfoo config set agents.claude.model claude-sonnet-4-6
secfoo config get agents.claude.model
```

```toml
Expand All @@ -995,6 +1002,12 @@ max_cost_usd = 2.00
[agents.claude]
model = "claude-sonnet-4-6"

[skills.secret-scanning]
model = "claude-haiku-4-5"

[agents.claude.skills.threat-modeling]
model = "claude-opus-4-6"

[agents.api]
# Refuse to send a prompt larger than this (see --max-input-tokens).
max_input_tokens = 150000
Expand All @@ -1017,21 +1030,29 @@ CLI flags always override `[defaults]`. See
[`src/secfoo/config.example.toml`](../src/secfoo/config.example.toml) for the
full reference, including remote HTTP/SSE servers.

`secfoo run --model <model-id>` overrides `[agents.<agent-id>].model` for
that invocation without changing any CLI global settings. Use the registered
agent ID (`agent` for Cursor, `agy` for Antigravity). Model IDs must be
non-empty strings. Claude, Codex, Gemini, Copilot and Cursor receive `--model`;
Droid and OpenCode receive `-m`. Antigravity and Devin currently warn and ignore model
selection because no supported model flag is established for these adapters.
The `api` agent uses the selected model ahead of `SECFOO_API_MODEL`, then its
existing built-in default. With no selection, CLI commands remain unchanged.

Each run stores the **requested** model (`runs.model`), not a provider-verified
model identity. It is NULL when no model was selected (including older runs).
A setting ignored by an unsupported adapter remains a requested label; its
warning explains that the CLI default was used. Run records do not infer the
CLI's global default or resolve provider aliases. Use model IDs supported by
your installed CLI version; an invalid ID is reported by that CLI.
`secfoo run --model <model-id>` overrides configured defaults for that
invocation without changing any CLI global settings. Precedence is:

1. `--model <model-id>`
2. `[agents.<agent-id>.skills.<skill-id>].model`
3. `[skills.<skill-id>].model`
4. `[agents.<agent-id>].model`
5. The agent CLI's own default (or `SECFOO_API_MODEL` / `openai/gpt-4.1-mini` for `api`)

Use `secfoo models [--agent ID] [--refresh] [--json]` to list available models
(cached in `~/.secfoo/models.json` for 24 hours). When live discovery is
available, `secfoo run` validates the requested model up front and suggests
the three closest IDs on mismatch (pass `--model-unchecked` to bypass; curated-only
lists warn rather than blocking). Use the registered agent ID (`agent` for
Cursor, `agy` for Antigravity). Model IDs must be non-empty strings. Claude,
Codex, Gemini, Copilot and Cursor receive `--model`; Droid and OpenCode receive
`-m`. Antigravity (`agy`) and Devin (`devin`) do not support model selection and
fail fast on an explicit `--model`.

Each run stores the **requested** model (`runs.model`), shown in `secfoo list`,
`secfoo show`, `secfoo run --json`, `secfoo cost --by model`, and the dashboard.
It is NULL when no model was selected (including older runs). Run records do not
infer the CLI's global default or resolve provider aliases.

How MCP servers reach each agent varies by what its CLI actually supports:

Expand Down
30 changes: 17 additions & 13 deletions docs/agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,24 @@ The table describes the argv secfoo builds, not a command to paste verbatim.
`PROMPT` is the rendered review prompt, `WORKDIR` the target directory, and
brackets indicate optional arguments. All CLI processes run in `WORKDIR`.

| `--agent` | Setup and command |
| --- | --- |
| `claude` | Install via `npm install -g @anthropic-ai/claude-code` or `curl -fsSL https://claude.ai/install.sh \| bash` ([docs](https://docs.anthropic.com/en/docs/claude-code/setup)). Authenticate with `claude auth login`. For non-interactive use, set `ANTHROPIC_API_KEY`, or with a Claude subscription run `claude setup-token` once and set the token it prints as `CLAUDE_CODE_OAUTH_TOKEN` (verified `2.1.329 (Claude Code)` on 2026-11-21, macOS Darwin arm64). `claude [--model MODEL] -p --output-format json --allowedTools TOOLS --permission-mode default --setting-sources user --strict-mcp-config --no-session-persistence [--mcp-config PATH]` (prompt on stdin). `TOOLS` starts with `Read,Grep,Glob,Bash(git log:*),Bash(git diff:*)` and includes configured MCP servers when present. The tool grant is read-only, not an OS sandbox. |
| `agent` (Cursor) | Install via `curl https://cursor.com/install -fsS \| bash` ([docs](https://cursor.com/docs/cli/overview)). Authenticate with `agent login` or set `CURSOR_API_KEY` for non-interactive use (login and `CURSOR_API_KEY` confirmed in `agent --help` for `2026.08.11-e8db854` on 2026-11-21, macOS arm64; install command from the official docs). `agent [--model MODEL] -p PROMPT` |
| `agy` (Antigravity) | Install the `agy` CLI from the Antigravity distribution ([docs](https://antigravity.google)), then run `agy install` to add it to `PATH`. The CLI has no login subcommand: sign in through Antigravity before headless runs (checked against `agy --help` for `1.5.3` on 2026-11-21, macOS arm64). `agy --print PROMPT --print-timeout Ns` (`N` is the effective timeout in seconds). Headless mode denies tool calls requiring approval. |
| `gemini` | Install via `npm install -g @google/gemini-cli` ([docs](https://github.com/google-gemini/gemini-cli)). Authenticate interactively with `gemini` or set `GEMINI_API_KEY` for non-interactive use (verified `0.38.1` on 2026-11-21, macOS Darwin arm64). `gemini [--model MODEL] -p PROMPT --output-format json --skip-trust`. No `--yolo` write auto-approval is passed. |
| `codex` | Install via `npm install -g @openai/codex` ([docs](https://github.com/openai/codex)). Authenticate with `codex login` or set `OPENAI_API_KEY` for non-interactive use (verified `codex-cli 0.159.0` on 2026-11-21, macOS Darwin arm64). `codex exec [--model MODEL] --sandbox read-only [-c windows.sandbox="unelevated"] --skip-git-repo-check --ephemeral --color never --cd WORKDIR -` (prompt on stdin; `-c` is Windows-only). |
| `copilot` | Install via `npm install -g @github/copilot` ([docs](https://docs.github.com/en/copilot/how-tos/use-copilot-agents/use-copilot-cli)). Authenticate by running `copilot` and using its `/login` command, or set `GH_TOKEN` / `GITHUB_TOKEN` (a fine-grained token with the Copilot Requests permission) for non-interactive use (verified against the real CLI 1.0.117 on 2026-11-29, Windows: `gh auth login` plus `GH_TOKEN` from `gh auth token` worked; see the matrix below). `copilot [--model MODEL] --output-format json --allow-all-tools --usage-output-file PATH` (prompt on stdin). Token counts come from the usage file; premium requests / AI credits are not USD, so `cost_usd` stays unknown. Tools, including writes, are auto-approved: read-only behavior relies on review instructions, not a sandbox. |
| `droid` | Install via `curl -fsSL https://app.factory.ai/cli \| sh` ([docs](https://docs.factory.ai/cli/getting-started/overview)). Set `FACTORY_API_KEY` for non-interactive use or run `droid` to sign in interactively (checked against official docs on 2026-11-21, not on an installed CLI). `droid exec [-m MODEL] --output-format json --cwd WORKDIR -- PROMPT`. Droid defaults to read-only; a full authenticated secfoo run was not verified in the adapter. |
| `devin` | Install via `brew install --cask devin-cli` ([docs](https://docs.devin.ai)). Authenticate beforehand with `devin auth login`; credential reuse for headless runs is unverified (install and login checked against official docs on 2026-11-21, not on an installed CLI). `devin -p PROMPT --respect-workspace-trust false --permission-mode auto`. The combined command and an authenticated end-to-end run are unverified; `auto` is documented by the CLI as approving read-only tools. |
| `api` | No agent binary is invoked. `litellm` and `langgraph` are installed with secfoo; if importing them fails, reinstall secfoo the way you installed it (`pipx reinstall secfoo` or `pip install --force-reinstall secfoo`). Set `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, or `GEMINI_API_KEY`. Source files are included in the API prompt. Model selection uses the configured model, then `SECFOO_API_MODEL`, then `openai/gpt-4.1-mini`. MCP servers from `[[mcp_servers]]` (and `secfoo-memory`) are connected by secfoo itself. Only their read-only tools are offered to the model (`readOnlyHint: true`, or the server's `tools = [...]` list), with at most 20 tool calls per run (`[agents.api].tool_call_budget`, `0` turns tools off). The tool phase also stops once the input tokens sent reach 4× the first call's. Each call, the number of rounds and the total input tokens are logged to `stderr.log`. |
| `--agent` | Setup and command | Models |
| --- | --- | --- |
| `--agent` | Setup and command | Models |
| `claude` | Install via `npm install -g @anthropic-ai/claude-code` or `curl -fsSL https://claude.ai/install.sh \| bash` ([docs](https://docs.anthropic.com/en/docs/claude-code/setup)). Authenticate with `claude auth login`. For non-interactive use, set `ANTHROPIC_API_KEY`, or with a Claude subscription run `claude setup-token` once and set the token it prints as `CLAUDE_CODE_OAUTH_TOKEN` (verified `2.1.329 (Claude Code)` on 2026-11-21, macOS Darwin arm64). `claude [--model MODEL] -p --output-format json --allowedTools TOOLS --permission-mode default --setting-sources user --strict-mcp-config --no-session-persistence [--mcp-config PATH]` (prompt on stdin). `TOOLS` starts with `Read,Grep,Glob,Bash(git log:*),Bash(git diff:*)` and includes configured MCP servers when present. The tool grant is read-only, not an OS sandbox. | `secfoo models --agent claude`. Examples: `claude-sonnet-4-6`, `sonnet`. Live via `ANTHROPIC_API_KEY` (Anthropic models API), else curated. |
| `agent` (Cursor) | Install via `curl https://cursor.com/install -fsS \| bash` ([docs](https://cursor.com/docs/cli/overview)). Authenticate with `agent login` or set `CURSOR_API_KEY` for non-interactive use (login and `CURSOR_API_KEY` confirmed in `agent --help` for `2026.08.11-e8db854` on 2026-11-21, macOS arm64; install command from the official docs). `agent [--model MODEL] -p PROMPT` | `secfoo models --agent agent`. Examples: `auto`, `claude-4.5-sonnet`. Live via CLI if supported, else curated. |
| `agy` (Antigravity) | Install the `agy` CLI from the Antigravity distribution ([docs](https://antigravity.google)), then run `agy install` to add it to `PATH`. The CLI has no login subcommand: sign in through Antigravity before headless runs (checked against `agy --help` for `1.5.3` on 2026-11-21, macOS arm64). `agy --print PROMPT --print-timeout Ns` (`N` is the effective timeout in seconds). Headless mode denies tool calls requiring approval. | Not supported (`--model` fails fast). |
| `gemini` | Install via `npm install -g @google/gemini-cli` ([docs](https://github.com/google-gemini/gemini-cli)). Authenticate interactively with `gemini` or set `GEMINI_API_KEY` for non-interactive use (verified `0.38.1` on 2026-11-21, macOS Darwin arm64). `gemini [--model MODEL] -p PROMPT --output-format json --skip-trust`. No `--yolo` write auto-approval is passed. | `secfoo models --agent gemini`. Examples: `gemini-2.5-pro`, `gemini-2.5-flash`. Live via `GEMINI_API_KEY`, else curated. |
| `codex` | Install via `npm install -g @openai/codex` ([docs](https://github.com/openai/codex)). Authenticate with `codex login` or set `OPENAI_API_KEY` for non-interactive use (verified `codex-cli 0.159.0` on 2026-11-21, macOS Darwin arm64). `codex exec [--model MODEL] --sandbox read-only [-c windows.sandbox="unelevated"] --skip-git-repo-check --ephemeral --color never --cd WORKDIR -` (prompt on stdin; `-c` is Windows-only). | `secfoo models --agent codex`. Examples: `gpt-5.4`, `o4-mini`. Live via `OPENAI_API_KEY` (or CLI), else curated. |
| `copilot` | Install via `npm install -g @github/copilot` ([docs](https://docs.github.com/en/copilot/how-tos/use-copilot-agents/use-copilot-cli)). Authenticate by running `copilot` and using its `/login` command, or set `GH_TOKEN` / `GITHUB_TOKEN` (a fine-grained token with the Copilot Requests permission) for non-interactive use (verified against the real CLI 1.0.117 on 2026-11-29, Windows: `gh auth login` plus `GH_TOKEN` from `gh auth token` worked; see the matrix below). `copilot [--model MODEL] --output-format json --allow-all-tools --usage-output-file PATH` (prompt on stdin). Token counts come from the usage file; premium requests / AI credits are not USD, so `cost_usd` stays unknown. Tools, including writes, are auto-approved: read-only behavior relies on review instructions, not a sandbox. | `secfoo models --agent copilot`. Examples: `claude-sonnet-4.5`, `gpt-5`. Curated (live via CLI if supported). |
| `droid` | Install via `curl -fsSL https://app.factory.ai/cli \| sh` ([docs](https://docs.factory.ai/cli/getting-started/overview)). Set `FACTORY_API_KEY` for non-interactive use or run `droid` to sign in interactively (checked against official docs on 2026-11-21, not on an installed CLI). `droid exec [-m MODEL] --output-format json --cwd WORKDIR -- PROMPT`. Droid defaults to read-only; a full authenticated secfoo run was not verified in the adapter. | `secfoo models --agent droid`. Examples: `claude-sonnet-4-5-20250929`, `gpt-5`. Curated (live via CLI if supported). |
| `devin` | Install via `brew install --cask devin-cli` ([docs](https://docs.devin.ai)). Authenticate beforehand with `devin auth login`; credential reuse for headless runs is unverified (install and login checked against official docs on 2026-11-21, not on an installed CLI). `devin -p PROMPT --respect-workspace-trust false --permission-mode auto`. The combined command and an authenticated end-to-end run are unverified; `auto` is documented by the CLI as approving read-only tools. | Not supported (`--model` fails fast). |
| `opencode` | Install via `npm install -g opencode-ai` or `curl -fsSL https://opencode.ai/install \| bash`. Non-interactive `opencode run --pure --format json --dir WORKDIR [-m MODEL]` (prompt on stdin). Read-only permissions set via `OPENCODE_CONFIG_CONTENT` / `OPENCODE_PERMISSION`. | `secfoo models --agent opencode`. Examples: `anthropic/claude-sonnet-4-5`, `openai/gpt-5`. Live via `opencode models`, else curated. |
| `api` | No agent binary is invoked. `litellm` and `langgraph` are installed with secfoo; if importing them fails, reinstall secfoo the way you installed it (`pipx reinstall secfoo` or `pip install --force-reinstall secfoo`). Set `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, or `GEMINI_API_KEY`. Source files are included in the API prompt. Model selection uses the configured model, then `SECFOO_API_MODEL`, then `openai/gpt-4.1-mini`. MCP servers from `[[mcp_servers]]` (and `secfoo-memory`) are connected by secfoo itself. Only their read-only tools are offered to the model (`readOnlyHint: true`, or the server's `tools = [...]` list), with at most 20 tool calls per run (`[agents.api].tool_call_budget`, `0` turns tools off). The tool phase also stops once the input tokens sent reach 4× the first call's. Each call, the number of rounds and the total input tokens are logged to `stderr.log`. | `secfoo models --agent api`. Examples: `openai/gpt-4.1-mini`, `anthropic/claude-sonnet-4-5`. Live from LiteLLM filtered by env API keys. |

`agy` and `devin` do not support adapter model selection; secfoo warns and
ignores a requested model. Other CLI model flags are shown above.
`agy` and `devin` do not support adapter model selection; passing an explicit
`--model` (or agent-scoped config) errors before the run. Other CLI model flags
are shown above; run `secfoo models` to inspect available models and whether
validation is live or curated.

## Real-CLI verification matrix (issue #116)

Expand Down
43 changes: 43 additions & 0 deletions src/secfoo/agents/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
from typing import TypedDict

from secfoo.agents.base import AgentAdapter, AgentResult, Status, Usage
from secfoo.agents.models import ModelInfo
from secfoo.report.markdown import MalformedReportError
from secfoo.report.severity import extract_overall_risk_rating
from secfoo.settings import ConfigError, MCPServerConfig
Expand Down Expand Up @@ -546,6 +547,48 @@ def build_command(self, prompt: str, *, workdir: Path) -> list[str]:
supports_model = True
supports_max_input_tokens = True

def list_models(self) -> list[ModelInfo]:
"""Filter LiteLLM's model_cost map by the provider API keys currently set."""
active_providers: set[str] = set()
if (os.environ.get("OPENAI_API_KEY") or "").strip():
active_providers.add("openai")
if (os.environ.get("ANTHROPIC_API_KEY") or "").strip():
active_providers.add("anthropic")
if (os.environ.get("GEMINI_API_KEY") or "").strip():
active_providers.add("gemini")
if not active_providers:
return []

os.environ.setdefault("LITELLM_LOCAL_MODEL_COST_MAP", "True")
try:
import litellm
except ImportError:
return []

model_cost = getattr(litellm, "model_cost", None)
if not isinstance(model_cost, dict):
return []

seen: set[str] = set()
items: list[ModelInfo] = []
for raw_id, meta in model_cost.items():
if not isinstance(raw_id, str) or not isinstance(meta, dict):
continue
provider = meta.get("litellm_provider")
if provider not in active_providers:
continue
mode = meta.get("mode")
if mode is not None and mode != "chat":
continue
if raw_id.startswith("ft:") or raw_id == "sample_spec":
continue
model_id = raw_id if "/" in raw_id else f"{provider}/{raw_id}"
if model_id in seen:
continue
seen.add(model_id)
items.append(ModelInfo(id=model_id, display_name=model_id, source="litellm"))
return sorted(items, key=lambda m: m.id)

def run(self, prompt: str, *, workdir: Path, timeout: int | None = None, prev_commit: str | None = None) -> AgentResult: # Memory Bank: prev_commit triggers incremental diff scan.
started = time.monotonic()
_strip_key_whitespace()
Expand Down
20 changes: 17 additions & 3 deletions src/secfoo/agents/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,15 @@
from pathlib import Path
from typing import ClassVar, Literal

from secfoo.agents.model_info import ModelInfo

Status = Literal["success", "failed", "timeout", "binary_not_found", "not_configured"]


class UnsupportedModelError(ValueError):
"""Raised when a model is configured for an agent that cannot select models."""


def _kill_process_tree(pid: int, *, posix: bool = os.name == "posix") -> None:
"""Kill `pid` and its descendants after a timeout.

Expand Down Expand Up @@ -100,15 +106,23 @@ class AgentAdapter(ABC):
model: str | None = None
model_flag: ClassVar[str | None] = None
supports_model: ClassVar[bool] = False
curated_models: ClassVar[tuple[ModelInfo, ...]] = ()

@classmethod
def accepts_model(cls) -> bool:
return bool(cls.model_flag or cls.supports_model)

def configure_model(self, model: str | None) -> None:
if model is not None and (not isinstance(model, str) or not model.strip()):
raise ValueError("model must be a non-empty string")
if model is not None and not (self.model_flag or self.supports_model):
warnings.warn(f"Agent {self.name!r} does not support model selection; ignoring model", stacklevel=2)
model = None
if model is not None and not self.accepts_model():
raise UnsupportedModelError(f"Agent {self.name!r} does not support model selection")
self.model = model

def list_models(self) -> list[ModelInfo]:
"""Return available models for this adapter (CLI -> provider API -> curated)."""
return list(self.curated_models)

# Pre-flight cap on prompt size (#32). Only an adapter that builds the
# full prompt itself (the api agent) can measure it before sending; CLI
# agents read the target's files on their own, out of secfoo's sight.
Expand Down
Loading
Loading