From cff8b1a6856a332446f749516e3936aec89bca91 Mon Sep 17 00:00:00 2001 From: SriRamKunamsetty Date: Sun, 29 Nov 2026 07:42:15 +0530 Subject: [PATCH 1/4] feat(models): add secfoo models discovery, validation, per-skill defaults, and model spend/UI (#111) --- docs/REFERENCE.md | 51 ++- docs/agents.md | 29 +- src/secfoo/agents/api.py | 43 ++ src/secfoo/agents/base.py | 20 +- src/secfoo/agents/claude.py | 20 + src/secfoo/agents/codex.py | 24 + src/secfoo/agents/copilot.py | 19 + src/secfoo/agents/cursor.py | 20 + src/secfoo/agents/droid.py | 18 + src/secfoo/agents/gemini.py | 12 + src/secfoo/agents/models.py | 314 +++++++++++++ src/secfoo/agents/opencode.py | 18 + src/secfoo/cli.py | 200 ++++++++- src/secfoo/runner.py | 5 +- src/secfoo/settings.py | 163 +++++++ src/secfoo/storage/repository.py | 3 +- src/secfoo/web/routes/overview.py | 6 +- .../web/templates/assessments/detail.html | 3 +- src/secfoo/web/templates/overview.html | 38 +- src/secfoo/web/templates/project.html | 3 +- src/secfoo/web/templates/run_detail.html | 3 +- tests/test_agents/test_models.py | 423 +++++++++++++++++- 22 files changed, 1367 insertions(+), 68 deletions(-) create mode 100644 src/secfoo/agents/models.py diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index b303ac4..cb018b3 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -788,6 +788,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 @@ -930,6 +935,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 @@ -948,6 +955,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 @@ -965,21 +978,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 ` overrides `[agents.].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 ` overrides configured defaults for that +invocation without changing any CLI global settings. Precedence is: + +1. `--model ` +2. `[agents..skills.].model` +3. `[skills.].model` +4. `[agents.].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: diff --git a/docs/agents.md b/docs/agents.md index 7dfc0fc..42527dd 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -8,20 +8,23 @@ 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 (checked against official docs on 2026-11-21). `copilot [--model MODEL] --output-format json --allow-all-tools` (prompt on stdin). 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`. | +| `--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 (checked against official docs on 2026-11-21). `copilot [--model MODEL] --output-format json --allow-all-tools` (prompt on stdin). 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`. | `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. ## Troubleshooting diff --git a/src/secfoo/agents/api.py b/src/secfoo/agents/api.py index 52c9333..56605ac 100644 --- a/src/secfoo/agents/api.py +++ b/src/secfoo/agents/api.py @@ -26,6 +26,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.skills.renderer import DEFAULT_EXCLUDE_PATHS @@ -314,6 +315,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() diff --git a/src/secfoo/agents/base.py b/src/secfoo/agents/base.py index 6b29fbf..48593b4 100644 --- a/src/secfoo/agents/base.py +++ b/src/secfoo/agents/base.py @@ -19,9 +19,15 @@ from pathlib import Path from typing import ClassVar, Literal +from secfoo.agents.models 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. @@ -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. diff --git a/src/secfoo/agents/claude.py b/src/secfoo/agents/claude.py index f1325e0..9be30f7 100644 --- a/src/secfoo/agents/claude.py +++ b/src/secfoo/agents/claude.py @@ -30,6 +30,7 @@ from pathlib import Path from secfoo.agents.base import AgentAdapter, Usage +from secfoo.agents.models import ModelInfo, fetch_anthropic_models from secfoo.mcp import effective_servers, write_claude_mcp_config from secfoo.settings import load_config @@ -58,6 +59,25 @@ class ClaudeAdapter(AgentAdapter): # `claude` is a `.cmd` shim and cmd.exe cuts the argument at its first # newline (the same failure PR #23 fixed for Codex and Copilot). prompt_via_stdin = True + curated_models = ( + ModelInfo(id="claude-sonnet-4-6", display_name="Claude Sonnet 4.6", source="curated", verified_at="2026-11-29"), + ModelInfo(id="claude-opus-4-6", display_name="Claude Opus 4.6", source="curated", verified_at="2026-11-29"), + ModelInfo(id="claude-haiku-4-5", display_name="Claude Haiku 4.5", source="curated", verified_at="2026-11-29"), + ModelInfo(id="sonnet", display_name="Sonnet (CLI alias)", source="curated", verified_at="2026-11-29"), + ModelInfo(id="opus", display_name="Opus (CLI alias)", source="curated", verified_at="2026-11-29"), + ModelInfo(id="haiku", display_name="Haiku (CLI alias)", source="curated", verified_at="2026-11-29"), + ) + + def list_models(self) -> list[ModelInfo]: + live = fetch_anthropic_models() + if live: + aliases = [ + ModelInfo(id=a, display_name=f"{a.capitalize()} (CLI alias)", source="provider") + for a in ("sonnet", "opus", "haiku") + if all(m.id != a for m in live) + ] + return live + aliases + return list(self.curated_models) def build_command(self, prompt: str, *, workdir: Path) -> list[str]: # MCP servers from ~/.secfoo/config.toml are injected here, scoped diff --git a/src/secfoo/agents/codex.py b/src/secfoo/agents/codex.py index f8bed34..b229352 100644 --- a/src/secfoo/agents/codex.py +++ b/src/secfoo/agents/codex.py @@ -31,6 +31,12 @@ from pathlib import Path from secfoo.agents.base import AgentAdapter, Usage +from secfoo.agents.models import ( + ModelInfo, + fetch_openai_models, + parse_plain_model_lines, + run_cli_models_command, +) # "tokens used" on its own line, then the total (thousands separators allowed). _TOKENS_USED_RE = re.compile(r"^\s*tokens used\s*\n\s*([\d,]+)\s*$", re.MULTILINE | re.IGNORECASE) @@ -48,6 +54,24 @@ class CodexAdapter(AgentAdapter): # on Windows, where `codex` is a `.cmd` shim and cmd.exe truncates the # argument at its first newline. prompt_via_stdin = True + curated_models = ( + ModelInfo(id="gpt-5.4", display_name="GPT-5.4", source="curated", verified_at="2026-11-29"), + ModelInfo(id="gpt-5.3-codex", display_name="GPT-5.3 Codex", source="curated", verified_at="2026-11-29"), + ModelInfo(id="gpt-5.2-codex", display_name="GPT-5.2 Codex", source="curated", verified_at="2026-11-29"), + ModelInfo(id="o3", display_name="o3", source="curated", verified_at="2026-11-29"), + ModelInfo(id="o4-mini", display_name="o4-mini", source="curated", verified_at="2026-11-29"), + ) + + def list_models(self) -> list[ModelInfo]: + stdout = run_cli_models_command(self.binary, ["models"]) + if stdout: + parsed = parse_plain_model_lines(stdout, source="cli") + if parsed: + return parsed + live = fetch_openai_models() + if live: + return live + return list(self.curated_models) def detect_failure(self, stdout: str, stderr: str) -> str | None: # If Codex's sandbox still refuses its commands, `codex exec` exits 0 diff --git a/src/secfoo/agents/copilot.py b/src/secfoo/agents/copilot.py index 31b36dc..e21f4a8 100644 --- a/src/secfoo/agents/copilot.py +++ b/src/secfoo/agents/copilot.py @@ -76,6 +76,11 @@ from pathlib import Path from secfoo.agents.base import AgentAdapter +from secfoo.agents.models import ( + ModelInfo, + parse_plain_model_lines, + run_cli_models_command, +) class CopilotAdapter(AgentAdapter): @@ -88,6 +93,20 @@ class CopilotAdapter(AgentAdapter): # (reproduced Sep 2026, CLI 1.0.89). With stdin piped and no `-p`, the # CLI still runs one non-interactive turn and exits. prompt_via_stdin = True + curated_models = ( + ModelInfo(id="claude-sonnet-4.5", display_name="Claude Sonnet 4.5", source="curated", verified_at="2026-11-29"), + ModelInfo(id="gpt-5", display_name="GPT-5", source="curated", verified_at="2026-11-29"), + ModelInfo(id="gpt-4.1", display_name="GPT-4.1", source="curated", verified_at="2026-11-29"), + ModelInfo(id="o4-mini", display_name="o4-mini", source="curated", verified_at="2026-11-29"), + ) + + def list_models(self) -> list[ModelInfo]: + stdout = run_cli_models_command(self.binary, ["models"]) + if stdout: + parsed = parse_plain_model_lines(stdout, source="cli") + if parsed: + return parsed + return list(self.curated_models) def build_command(self, prompt: str, *, workdir: Path) -> list[str]: return [self.binary, *self.model_arguments(), "--output-format", "json", "--allow-all-tools"] diff --git a/src/secfoo/agents/cursor.py b/src/secfoo/agents/cursor.py index fdccb83..28f80d6 100644 --- a/src/secfoo/agents/cursor.py +++ b/src/secfoo/agents/cursor.py @@ -15,6 +15,11 @@ from pathlib import Path from secfoo.agents.base import AgentAdapter +from secfoo.agents.models import ( + ModelInfo, + parse_plain_model_lines, + run_cli_models_command, +) class CursorAdapter(AgentAdapter): @@ -22,6 +27,21 @@ class CursorAdapter(AgentAdapter): binary = "agent" default_timeout_seconds = 900 model_flag = "--model" + curated_models = ( + ModelInfo(id="auto", display_name="Auto", source="curated", verified_at="2026-11-29"), + ModelInfo(id="claude-4.5-sonnet", display_name="Claude 4.5 Sonnet", source="curated", verified_at="2026-11-29"), + ModelInfo(id="gpt-5", display_name="GPT-5", source="curated", verified_at="2026-11-29"), + ModelInfo(id="gemini-2.5-pro", display_name="Gemini 2.5 Pro", source="curated", verified_at="2026-11-29"), + ) + + def list_models(self) -> list[ModelInfo]: + for args in (["models"], ["--list-models"]): + stdout = run_cli_models_command(self.binary, args) + if stdout: + parsed = parse_plain_model_lines(stdout, source="cli") + if parsed: + return parsed + return list(self.curated_models) def build_command(self, prompt: str, *, workdir: Path) -> list[str]: return [self.binary, *self.model_arguments(), "-p", prompt] diff --git a/src/secfoo/agents/droid.py b/src/secfoo/agents/droid.py index 772a237..f27f633 100644 --- a/src/secfoo/agents/droid.py +++ b/src/secfoo/agents/droid.py @@ -46,6 +46,11 @@ from pathlib import Path from secfoo.agents.base import AgentAdapter, Usage +from secfoo.agents.models import ( + ModelInfo, + parse_plain_model_lines, + run_cli_models_command, +) class DroidAdapter(AgentAdapter): @@ -53,6 +58,19 @@ class DroidAdapter(AgentAdapter): binary = "droid" default_timeout_seconds = 1800 model_flag = "-m" + curated_models = ( + ModelInfo(id="claude-sonnet-4-5-20250929", display_name="Claude Sonnet 4.5", source="curated", verified_at="2026-11-29"), + ModelInfo(id="gpt-5", display_name="GPT-5", source="curated", verified_at="2026-11-29"), + ModelInfo(id="gemini-2.5-pro", display_name="Gemini 2.5 Pro", source="curated", verified_at="2026-11-29"), + ) + + def list_models(self) -> list[ModelInfo]: + stdout = run_cli_models_command(self.binary, ["models"]) + if stdout: + parsed = parse_plain_model_lines(stdout, source="cli") + if parsed: + return parsed + return list(self.curated_models) def build_command(self, prompt: str, *, workdir: Path) -> list[str]: return [ diff --git a/src/secfoo/agents/gemini.py b/src/secfoo/agents/gemini.py index 877f089..bf4ffba 100644 --- a/src/secfoo/agents/gemini.py +++ b/src/secfoo/agents/gemini.py @@ -16,6 +16,7 @@ from pathlib import Path from secfoo.agents.base import AgentAdapter, Usage +from secfoo.agents.models import ModelInfo, fetch_gemini_models class GeminiAdapter(AgentAdapter): @@ -23,6 +24,17 @@ class GeminiAdapter(AgentAdapter): binary = "gemini" default_timeout_seconds = 1800 model_flag = "--model" + curated_models = ( + ModelInfo(id="gemini-2.5-pro", display_name="Gemini 2.5 Pro", source="curated", verified_at="2026-11-29"), + ModelInfo(id="gemini-2.5-flash", display_name="Gemini 2.5 Flash", source="curated", verified_at="2026-11-29"), + ModelInfo(id="gemini-2.5-flash-lite", display_name="Gemini 2.5 Flash-Lite", source="curated", verified_at="2026-11-29"), + ) + + def list_models(self) -> list[ModelInfo]: + live = fetch_gemini_models() + if live: + return live + return list(self.curated_models) def build_command(self, prompt: str, *, workdir: Path) -> list[str]: # Deliberately no --yolo: a read-only review never needs diff --git a/src/secfoo/agents/models.py b/src/secfoo/agents/models.py new file mode 100644 index 0000000..8cc6c8e --- /dev/null +++ b/src/secfoo/agents/models.py @@ -0,0 +1,314 @@ +"""Model discovery, 24h caching, and pre-run validation across agent adapters.""" + +from __future__ import annotations + +import difflib +import hashlib +import json +import os +import shutil +import subprocess # nosec B404 -- fixed argv, no shell +import urllib.error +import urllib.request +from collections.abc import Iterable +from dataclasses import asdict, dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import TYPE_CHECKING + +from secfoo import config as config_module + +if TYPE_CHECKING: + from secfoo.agents.base import AgentAdapter + +CACHE_TTL_SECONDS = 24 * 60 * 60 +_HTTP_TIMEOUT_SECONDS = 5 +_CLI_TIMEOUT_SECONDS = 10 + +_PROVIDER_KEY_VARS = ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY") + + +@dataclass(frozen=True) +class ModelInfo: + """One model choice exposed by an agent adapter.""" + + id: str + display_name: str = "" + source: str = "curated" # "cli" | "provider" | "litellm" | "curated" + verified_at: str | None = None + + @property + def is_live(self) -> bool: + return self.source != "curated" + + +def models_cache_path() -> Path: + return config_module.STORE_DIR / "models.json" + + +def _env_fingerprint(adapter: AgentAdapter) -> str: + """Hashes which provider keys are set and where the CLI binary resolves, + without ever persisting secret values or full paths to the cache file.""" + active_keys = sorted(k for k in _PROVIDER_KEY_VARS if os.environ.get(k)) + binary_path = shutil.which(adapter.binary) if adapter.name != "api" else "api" + raw = json.dumps({"keys": active_keys, "binary": binary_path or ""}, sort_keys=True) + return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:16] + + +def _read_cache() -> dict: + path = models_cache_path() + if not path.is_file(): + return {} + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return {} + return data if isinstance(data, dict) else {} + + +def _write_cache(data: dict) -> None: + path = models_cache_path() + path.parent.mkdir(parents=True, exist_ok=True) + config_module.write_private_text(path, json.dumps(data, indent=2)) + + +def _is_fresh(entry: dict, *, fingerprint: str, now: datetime) -> bool: + if entry.get("fingerprint") != fingerprint: + return False + fetched_raw = entry.get("fetched_at") + if not isinstance(fetched_raw, str): + return False + try: + fetched = datetime.fromisoformat(fetched_raw) + except ValueError: + return False + if fetched.tzinfo is None: + fetched = fetched.replace(tzinfo=timezone.utc) + return (now - fetched).total_seconds() < CACHE_TTL_SECONDS + + +def discover_models(adapter: AgentAdapter, *, refresh: bool = False) -> list[ModelInfo]: + """Return models for `adapter`, reading/updating ~/.secfoo/models.json (24h TTL).""" + now = datetime.now(timezone.utc) + fingerprint = _env_fingerprint(adapter) + cache = _read_cache() + + if not refresh: + entry = cache.get(adapter.name) + if isinstance(entry, dict) and _is_fresh(entry, fingerprint=fingerprint, now=now): + raw_models = entry.get("models") + if isinstance(raw_models, list): + try: + return [ModelInfo(**m) for m in raw_models if isinstance(m, dict) and isinstance(m.get("id"), str)] + except TypeError: + pass + + models = adapter.list_models() + cache[adapter.name] = { + "fetched_at": now.isoformat(), + "fingerprint": fingerprint, + "models": [asdict(m) for m in models], + } + try: + _write_cache(cache) + except OSError: + pass + return models + + +def _http_get_json(url: str, headers: dict[str, str]) -> dict | None: + if not url.startswith("https://"): + return None + req = urllib.request.Request(url, headers={**headers, "User-Agent": "secfoo"}) + try: + with urllib.request.urlopen(req, timeout=_HTTP_TIMEOUT_SECONDS) as resp: # nosec B310 -- hardcoded https:// endpoints only + data = json.loads(resp.read().decode("utf-8")) + return data if isinstance(data, dict) else None + except (OSError, urllib.error.URLError, json.JSONDecodeError, ValueError): + return None + + +def fetch_openai_models() -> list[ModelInfo] | None: + key = (os.environ.get("OPENAI_API_KEY") or "").strip() + if not key: + return None + payload = _http_get_json( + "https://api.openai.com/v1/models", + {"Authorization": f"Bearer {key}"}, + ) + if not payload or not isinstance(payload.get("data"), list): + return None + items: list[ModelInfo] = [] + for entry in payload["data"]: + if not isinstance(entry, dict): + continue + model_id = entry.get("id") + if isinstance(model_id, str) and model_id.strip(): + items.append(ModelInfo(id=model_id.strip(), display_name=model_id.strip(), source="provider")) + return sorted(items, key=lambda m: m.id) if items else None + + +def fetch_anthropic_models() -> list[ModelInfo] | None: + key = (os.environ.get("ANTHROPIC_API_KEY") or "").strip() + if not key: + return None + payload = _http_get_json( + "https://api.anthropic.com/v1/models", + {"x-api-key": key, "anthropic-version": "2023-06-01"}, + ) + if not payload or not isinstance(payload.get("data"), list): + return None + items: list[ModelInfo] = [] + for entry in payload["data"]: + if not isinstance(entry, dict): + continue + model_id = entry.get("id") + if isinstance(model_id, str) and model_id.strip(): + display = entry.get("display_name") + name = display.strip() if isinstance(display, str) and display.strip() else model_id.strip() + items.append(ModelInfo(id=model_id.strip(), display_name=name, source="provider")) + return sorted(items, key=lambda m: m.id) if items else None + + +def fetch_gemini_models() -> list[ModelInfo] | None: + key = (os.environ.get("GEMINI_API_KEY") or "").strip() + if not key: + return None + payload = _http_get_json( + "https://generativelanguage.googleapis.com/v1beta/models", + {"x-goog-api-key": key}, + ) + if not payload or not isinstance(payload.get("models"), list): + return None + items: list[ModelInfo] = [] + for entry in payload["models"]: + if not isinstance(entry, dict): + continue + methods = entry.get("supportedGenerationMethods") + if isinstance(methods, list) and "generateContent" not in methods: + continue + raw_name = entry.get("name") + if not isinstance(raw_name, str) or not raw_name.strip(): + continue + model_id = raw_name.strip().removeprefix("models/") + display = entry.get("displayName") + name = display.strip() if isinstance(display, str) and display.strip() else model_id + items.append(ModelInfo(id=model_id, display_name=name, source="provider")) + return sorted(items, key=lambda m: m.id) if items else None + + +def run_cli_models_command(binary: str, args: list[str]) -> str | None: + """Run a CLI subcommand to list models; return stdout on 0-exit else None.""" + exe = shutil.which(binary) + if not exe: + return None + try: + proc = subprocess.run( # nosec B603 -- resolved binary with fixed args, no shell + [exe, *args], + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=_CLI_TIMEOUT_SECONDS, + check=False, + ) + except (OSError, subprocess.SubprocessError): + return None + if proc.returncode != 0 or not (proc.stdout or "").strip(): + return None + return proc.stdout + + +def parse_plain_model_lines(stdout: str, *, source: str = "cli") -> list[ModelInfo]: + """Parse line-oriented CLI output (e.g. `opencode models`) into ModelInfo rows.""" + seen: set[str] = set() + models: list[ModelInfo] = [] + for raw in stdout.splitlines(): + line = raw.strip() + if not line or line.startswith("#"): + continue + token = line.split()[0].strip(",;") + if not token or token.lower() in {"id", "model", "models", "name", "available"}: + continue + if set(token) <= {"-", "=", "_"}: + continue + if token not in seen: + seen.add(token) + models.append(ModelInfo(id=token, display_name=token, source=source)) + return models + + +def closest_model_ids(requested: str, models: Iterable[ModelInfo], *, n: int = 3) -> list[str]: + """Top `n` closest model IDs via difflib, filling from remaining IDs if needed.""" + ids = [m.id for m in models] + if not ids: + return [] + matches = difflib.get_close_matches(requested, ids, n=n, cutoff=0.3) + if len(matches) < n: + # Case-insensitive substring or low-cutoff fallback so suggestions stay helpful. + scored = difflib.get_close_matches(requested, ids, n=n, cutoff=0.0) + for candidate in scored: + if candidate not in matches: + matches.append(candidate) + if len(matches) >= n: + break + return matches[:n] + + +@dataclass(frozen=True) +class ModelValidation: + ok: bool + message: str | None = None + is_warning: bool = False + suggestions: tuple[str, ...] = () + + +def validate_model_selection( + agent_id: str, + model: str, + *, + models: list[ModelInfo], + supports_model: bool, +) -> ModelValidation: + """Validate `model` against discovered `models`. + + - Unsupported agent (`supports_model=False`) -> hard error. + - Empty list -> ok (nothing to validate against). + - Known match -> ok. + - Unknown against live list -> hard error with up to 3 difflib suggestions. + - Unknown against curated-only list -> warning only (never blocks). + """ + if not supports_model: + return ModelValidation( + ok=False, + message=f"Agent {agent_id!r} does not support model selection (--model cannot be used).", + ) + if not models: + return ModelValidation(ok=True) + + known = {m.id for m in models} + if model in known: + return ModelValidation(ok=True) + # LiteLLM accepts both "openai/gpt-4.1-mini" and bare "gpt-4.1-mini". + if agent_id == "api" and any(f"{prefix}/{model}" in known for prefix in ("openai", "anthropic", "gemini")): + return ModelValidation(ok=True) + + suggestions = tuple(closest_model_ids(model, models, n=3)) + has_live = any(m.is_live for m in models) + hint = f" Did you mean: {', '.join(suggestions)}?" if suggestions else "" + cmd = f"Run `secfoo models --agent {agent_id}` to list available models." + if not has_live: + return ModelValidation( + ok=True, + is_warning=True, + suggestions=suggestions, + message=( + f"Model {model!r} is not in {agent_id}'s curated model list.{hint} " + f"(Curated list only -- proceeding anyway. {cmd})" + ), + ) + return ModelValidation( + ok=False, + suggestions=suggestions, + message=f"Unknown model {model!r} for agent {agent_id!r}.{hint} {cmd}", + ) diff --git a/src/secfoo/agents/opencode.py b/src/secfoo/agents/opencode.py index 8adc1ba..9896f03 100644 --- a/src/secfoo/agents/opencode.py +++ b/src/secfoo/agents/opencode.py @@ -12,6 +12,11 @@ from typing import ClassVar from secfoo.agents.base import AgentAdapter, Usage +from secfoo.agents.models import ( + ModelInfo, + parse_plain_model_lines, + run_cli_models_command, +) def _events(stdout: str): @@ -29,6 +34,19 @@ class OpenCodeAdapter(AgentAdapter): binary = "opencode" prompt_via_stdin = True model_flag = "-m" + curated_models = ( + ModelInfo(id="anthropic/claude-sonnet-4-5", display_name="Claude Sonnet 4.5", source="curated", verified_at="2026-11-29"), + ModelInfo(id="openai/gpt-5", display_name="GPT-5", source="curated", verified_at="2026-11-29"), + ModelInfo(id="google/gemini-2.5-pro", display_name="Gemini 2.5 Pro", source="curated", verified_at="2026-11-29"), + ) + + def list_models(self) -> list[ModelInfo]: + stdout = run_cli_models_command(self.binary, ["models"]) + if stdout: + parsed = parse_plain_model_lines(stdout, source="cli") + if parsed: + return parsed + return list(self.curated_models) extra_env: ClassVar[dict[str, str]] = { "OPENCODE_CONFIG_CONTENT": json.dumps( {"permission": {"bash": "deny", "edit": "deny", "webfetch": "deny"}} diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index 6e49f2c..295abd5 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -21,6 +21,7 @@ from secfoo import mcp as mcp_module from secfoo import memory as memory_module from secfoo.__about__ import __version__ +from secfoo.agents.models import discover_models, validate_model_selection from secfoo.agents.registry import ADAPTERS, get_adapter from secfoo.aibom import AIBOMParseError, parse_ai_bom from secfoo.attachments import infer_attachment_kind @@ -34,7 +35,14 @@ from secfoo.report.jsonl import findings_to_jsonl from secfoo.report.sarif import findings_to_sarif from secfoo.runner import _project_display_name, already_scanned_skills, execute_runs -from secfoo.settings import CONFIG_PATH, ConfigError, load_config +from secfoo.settings import ( + CONFIG_PATH, + ConfigError, + get_config_value, + load_config, + resolve_model, + set_config_value, +) from secfoo.skills.loader import ( SkillLoadError, load_all_skills, @@ -315,7 +323,10 @@ def run( help="Which agent CLI runs the assessment. Falls back to [defaults].agent in " "~/.secfoo/config.toml, then to claude.", ), - model: str | None = typer.Option(None, "--model", help="Model for this run; overrides [agents.].model."), + model: str | None = typer.Option(None, "--model", help="Model for this run; overrides configured defaults."), + model_unchecked: bool = typer.Option( + False, "--model-unchecked", help="Skip pre-run model validation against the agent's discovered model list." + ), depth: DepthId | None = typer.Option( None, "--depth", @@ -480,8 +491,44 @@ def run( if model is not None and not model.strip(): err_console.print("[red]Error:[/] --model must be a non-empty string") raise typer.Exit(code=1) - if model is None: - model = file_config.agent_models.get(agent.value) + + adapter_instance = get_adapter(agent.value) + resolved_models: dict[str, str | None] = {} + cached_available_models = None + for s_id in skill_ids: + chosen_model, model_source = resolve_model( + file_config, agent_id=agent.value, skill_id=s_id, cli_model=model + ) + if chosen_model is not None: + if not adapter_instance.accepts_model(): + if model_source in {"cli", "agent", "agent_skill"}: + err_console.print( + f"[red]Error:[/] Agent {agent.value!r} does not support model selection." + ) + raise typer.Exit(code=1) + (err_console if json_output else console).print( + f"[yellow]Warning:[/] Agent {agent.value!r} does not support model selection; " + f"ignoring skill default {chosen_model!r}." + ) + chosen_model = None + elif not model_unchecked: + if cached_available_models is None: + cached_available_models = discover_models(adapter_instance) + validation = validate_model_selection( + agent.value, + chosen_model, + models=cached_available_models, + supports_model=adapter_instance.accepts_model(), + ) + if not validation.ok: + err_console.print(f"[red]Error:[/] {validation.message}") + raise typer.Exit(code=1) + if validation.is_warning and validation.message: + (err_console if json_output else console).print(f"[yellow]Warning:[/] {validation.message}") + resolved_models[s_id] = chosen_model + + unique_models = set(resolved_models.values()) + uniform_model = next(iter(unique_models)) if len(unique_models) == 1 else model if max_input_tokens is None: max_input_tokens = file_config.agent_max_input_tokens.get(agent.value) if depth is None: @@ -568,24 +615,27 @@ def handle_complete(skill_name: str, result_status: str) -> None: with progress: try: - outcomes = execute_runs( - skill_ids=skill_ids, - target=target, - confluence_urls=run_context.confluence_urls, - context_sources=run_context.sources, - mcp_servers=file_config.mcp_servers, - agent_id=agent.value, - model=model, - max_input_tokens=max_input_tokens, - depth=depth.value, - timeout=timeout, - on_skill_start=handle_start, - on_skill_complete=handle_complete, - assessment_id=assessment, - exclude_paths=exclude_paths, - project_display_name=project_name, - assessment_application_id=app_id, - ) + run_kwargs: dict = { + "skill_ids": skill_ids, + "target": target, + "confluence_urls": run_context.confluence_urls, + "context_sources": run_context.sources, + "mcp_servers": file_config.mcp_servers, + "agent_id": agent.value, + "model": uniform_model, + "max_input_tokens": max_input_tokens, + "depth": depth.value, + "timeout": timeout, + "on_skill_start": handle_start, + "on_skill_complete": handle_complete, + "assessment_id": assessment, + "exclude_paths": exclude_paths, + "project_display_name": project_name, + "assessment_application_id": app_id, + } + if len(unique_models) > 1: + run_kwargs["models_by_skill"] = resolved_models + outcomes = execute_runs(**run_kwargs) except TargetResolutionError as exc: err_console.print(f"[red]Error:[/] {exc}") raise typer.Exit(code=1) from None @@ -633,6 +683,7 @@ def handle_complete(skill_name: str, result_status: str) -> None: "run_uuid": o.run_uuid, "skill_id": o.skill_id, "skill_name": o.skill_name, + "model": o.model, "status": o.status, "failure_reason": o.failure_reason, "exit_code": o.exit_code, @@ -772,6 +823,7 @@ def list_runs( table.add_column("Project") table.add_column("Skill") table.add_column("Agent") + table.add_column("Model") table.add_column("Status") table.add_column("Cost", justify="right") table.add_column("Run ID") @@ -783,6 +835,7 @@ def list_runs( r.project_display_name or "", r.skill_name, r.agent_id, + r.model or "-", f"[{style}]{r.status}[/]", format_cost(r.cost_usd), r.run_uuid, @@ -807,7 +860,8 @@ def show( console.print_json(json.dumps(record.__dict__)) return - console.print(f"[bold]{record.skill_name}[/] via {record.agent_id} — status: {record.status}") + model_part = f" ({record.model})" if record.model else "" + console.print(f"[bold]{record.skill_name}[/] via {record.agent_id}{model_part} — status: {record.status}") if record.report_path and Path(record.report_path).exists(): console.print(Path(record.report_path).read_text(encoding="utf-8", errors="replace")) else: @@ -993,15 +1047,83 @@ def agents() -> None: console.print(table) +@app.command() +def models( + agent: AgentId | None = typer.Option(None, "--agent", "-a", help="Show models for a specific agent."), + refresh: bool = typer.Option(False, "--refresh", help="Bypass the 24h cache and query live sources."), + json_output: bool = typer.Option(False, "--json", help="Print available models as JSON."), +) -> None: + """List models available for each installed agent (or for --agent).""" + if agent is not None: + target_ids = [agent.value] + else: + target_ids = [aid for aid in ADAPTERS if get_adapter(aid).is_available()] + + payload = [] + for agent_id in target_ids: + adapter_inst = get_adapter(agent_id) + supports = adapter_inst.accepts_model() + found = discover_models(adapter_inst, refresh=refresh) if supports else [] + payload.append( + { + "agent": agent_id, + "available": adapter_inst.is_available(), + "supports_model": supports, + "models": [ + { + "id": m.id, + "display_name": m.display_name, + "source": m.source, + "verified_at": m.verified_at, + } + for m in found + ], + } + ) + + if json_output: + print(json.dumps({"agents": payload}, indent=2)) + return + + if not payload: + console.print( + "No agents found on PATH and no API keys set. Pass [bold]--agent [/] to inspect a specific adapter." + ) + return + + table = Table(title="Available models") + table.add_column("Agent") + table.add_column("Model ID") + table.add_column("Display name") + table.add_column("Source") + for entry in payload: + if not entry["supports_model"]: + table.add_row(entry["agent"], "-", "Model selection not supported", "none") + continue + if not entry["models"]: + table.add_row(entry["agent"], "-", "No models discovered (set a provider API key or check CLI)", "-") + continue + for m in entry["models"]: + src = m["source"] + if src == "curated": + ver = f", verified {m['verified_at']}" if m["verified_at"] else "" + src_label = f"[yellow]curated (unverified{ver})[/]" + else: + src_label = f"[green]{src}[/]" + table.add_row(entry["agent"], m["id"], m["display_name"] or m["id"], src_label) + console.print(table) + + class CostGroup(str, Enum): AGENT = "agent" SKILL = "skill" PROJECT = "project" + MODEL = "model" @app.command() def cost( - by: CostGroup = typer.Option(CostGroup.AGENT, "--by", help="Group spend by agent, skill, or project."), + by: CostGroup = typer.Option(CostGroup.AGENT, "--by", help="Group spend by agent, skill, project, or model."), since: str | None = typer.Option( None, "--since", help="Only count runs started on or after this date, YYYY-MM-DD.", callback=_validate_date ), @@ -2656,6 +2778,36 @@ def config_init( console.print(f"Wrote {CONFIG_PATH}. Edit it, then run [bold]secfoo mcp list[/] to confirm.") +@config_app.command(name="set") +def config_set( + key: str = typer.Argument(..., help="Dotted key path, e.g. agents.claude.model or skills.sast.model."), + value: str = typer.Argument(..., help="Value to set."), +) -> None: + """Set a single value in ~/.secfoo/config.toml without overwriting other settings.""" + try: + path = set_config_value(key, value) + except ConfigError as exc: + err_console.print(f"[red]Error:[/] {exc}") + raise typer.Exit(code=1) from None + console.print(f"Set [bold]{key}[/] = {value!r} in {path}.") + + +@config_app.command(name="get") +def config_get( + key: str = typer.Argument(..., help="Dotted key path, e.g. agents.claude.model."), +) -> None: + """Read a single value from ~/.secfoo/config.toml.""" + try: + value = get_config_value(key) + except ConfigError as exc: + err_console.print(f"[red]Error:[/] {exc}") + raise typer.Exit(code=1) from None + if value is None: + err_console.print(f"[yellow]{key} is not set in {CONFIG_PATH}.[/]") + raise typer.Exit(code=1) + console.print(str(value)) + + @mcp_app.command(name="list") def mcp_list() -> None: """Show MCP servers configured in ~/.secfoo/config.toml.""" diff --git a/src/secfoo/runner.py b/src/secfoo/runner.py index 93f3a32..355cb6f 100644 --- a/src/secfoo/runner.py +++ b/src/secfoo/runner.py @@ -119,6 +119,7 @@ class RunOutcome: exit_code: int | None duration_seconds: float | None report_path: str | None + model: str | None = None cost_usd: float | None = None input_tokens: int | None = None output_tokens: int | None = None @@ -588,6 +589,7 @@ def _run_single_skill( exit_code=result.exit_code, duration_seconds=result.duration_seconds, report_path=str(report_path), + model=model, cost_usd=result.cost_usd, input_tokens=result.input_tokens, output_tokens=result.output_tokens, @@ -612,6 +614,7 @@ def execute_runs( mcp_servers: list[MCPServerConfig] | None = None, agent_id: str, model: str | None = None, + models_by_skill: dict[str, str | None] | None = None, max_input_tokens: int | None = None, depth: Literal["quick", "standard"] = "quick", timeout: int | None = None, @@ -718,7 +721,7 @@ def execute_runs( skill_id=skill_id, project_id=project_id, agent_id=agent_id, - model=model, + model=(models_by_skill[skill_id] if models_by_skill and skill_id in models_by_skill else model), max_input_tokens=max_input_tokens, target_ctx=target_ctx, confluence_urls=confluence_urls, diff --git a/src/secfoo/settings.py b/src/secfoo/settings.py index a57a899..bae8b2c 100644 --- a/src/secfoo/settings.py +++ b/src/secfoo/settings.py @@ -8,6 +8,8 @@ from __future__ import annotations +import json +import re import sys from dataclasses import dataclass, field from pathlib import Path @@ -75,6 +77,8 @@ class SecfooConfig: # without a key there is nothing to wire in either way. memory_enabled: bool = True agent_models: dict[str, str] = field(default_factory=dict) + skill_models: dict[str, str] = field(default_factory=dict) + agent_skill_models: dict[tuple[str, str], str] = field(default_factory=dict) # [agents.].max_input_tokens -- pre-flight prompt-size cap (#32). agent_max_input_tokens: dict[str, int] = field(default_factory=dict) # [skills] paths -- extra folders of custom skill definitions (#79). @@ -221,6 +225,7 @@ def load_config(path: Path | None = None) -> SecfooConfig: if not isinstance(agents_raw, dict): raise ConfigError("[agents] must be a table") agent_models = {} + agent_skill_models: dict[tuple[str, str], str] = {} agent_max_input_tokens = {} for agent_id, options in agents_raw.items(): if not isinstance(options, dict): @@ -235,6 +240,18 @@ def load_config(path: Path | None = None) -> SecfooConfig: if isinstance(max_input_tokens, bool) or not isinstance(max_input_tokens, int) or max_input_tokens <= 0: raise ConfigError(f"agents.{agent_id}.max_input_tokens must be a positive integer") agent_max_input_tokens[agent_id] = max_input_tokens + agent_skills_raw = options.get("skills") + if agent_skills_raw is not None: + if not isinstance(agent_skills_raw, dict): + raise ConfigError(f"agents.{agent_id}.skills must be a table") + for skill_id, skill_opts in agent_skills_raw.items(): + if not isinstance(skill_opts, dict): + raise ConfigError(f"agents.{agent_id}.skills.{skill_id} must be a table") + s_model = skill_opts.get("model") + if s_model is not None: + if not isinstance(s_model, str) or not s_model.strip(): + raise ConfigError(f"agents.{agent_id}.skills.{skill_id}.model must be a non-empty string") + agent_skill_models[(agent_id, skill_id)] = s_model servers = [] seen_names: set[str] = set() @@ -258,6 +275,17 @@ def load_config(path: Path | None = None) -> SecfooConfig: skill_paths = skills_raw.get("paths", []) if not isinstance(skill_paths, list) or not all(isinstance(p, str) and p.strip() for p in skill_paths): raise ConfigError("skills.paths must be an array of folder paths") + skill_models: dict[str, str] = {} + for key, value in skills_raw.items(): + if key == "paths": + continue + if not isinstance(value, dict): + raise ConfigError(f"skills.{key} must be a table") + s_model = value.get("model") + if s_model is not None: + if not isinstance(s_model, str) or not s_model.strip(): + raise ConfigError(f"skills.{key}.model must be a non-empty string") + skill_models[key] = s_model memory_raw = data.get("memory", {}) if not isinstance(memory_raw, dict): @@ -271,6 +299,141 @@ def load_config(path: Path | None = None) -> SecfooConfig: mcp_servers=servers, memory_enabled=memory_enabled, agent_models=agent_models, + skill_models=skill_models, + agent_skill_models=agent_skill_models, agent_max_input_tokens=agent_max_input_tokens, skill_paths=list(skill_paths), ) + + +def resolve_model( + config: SecfooConfig, + *, + agent_id: str, + skill_id: str, + cli_model: str | None = None, +) -> tuple[str | None, str]: + """Return `(model, source)` in precedence order: + cli_model > agents..skills..model > skills..model > agents..model > default. + """ + if cli_model is not None: + return cli_model, "cli" + if (agent_id, skill_id) in config.agent_skill_models: + return config.agent_skill_models[(agent_id, skill_id)], "agent_skill" + if skill_id in config.skill_models: + return config.skill_models[skill_id], "skill" + if agent_id in config.agent_models: + return config.agent_models[agent_id], "agent" + return None, "default" + + +_KEY_SEGMENT_RE = re.compile(r"^[A-Za-z0-9_-]+$") +_TABLE_HEADER_RE = re.compile(r"^\s*\[([^\[\]]+)\]\s*(?:#.*)?$") +_KV_LINE_RE = re.compile(r"^\s*([A-Za-z0-9_-]+)\s*=") +_STRING_LEAVES = frozenset({"model", "agent", "depth", "fail_on"}) +_INT_LEAVES = frozenset({"timeout", "max_input_tokens"}) +_FLOAT_LEAVES = frozenset({"max_cost_usd"}) +_BOOL_LEAVES = frozenset({"enabled"}) + + +def _parse_dotted_key(key: str) -> tuple[list[str], str]: + parts = [p.strip() for p in key.split(".")] + if len(parts) < 2 or any(not _KEY_SEGMENT_RE.match(p) for p in parts): + raise ConfigError( + f"Invalid config key {key!r}; expected dotted path like 'agents.claude.model' or 'skills.sast.model'" + ) + return parts[:-1], parts[-1] + + +def _format_toml_value(leaf: str, raw_value: str) -> str: + if leaf in _STRING_LEAVES: + return json.dumps(raw_value) + if leaf in _INT_LEAVES: + try: + return str(int(raw_value)) + except ValueError as exc: + raise ConfigError(f"{leaf} must be an integer, got {raw_value!r}") from exc + if leaf in _FLOAT_LEAVES: + try: + return str(float(raw_value)) + except ValueError as exc: + raise ConfigError(f"{leaf} must be a number, got {raw_value!r}") from exc + if leaf in _BOOL_LEAVES: + lower = raw_value.strip().lower() + if lower in {"true", "false"}: + return lower + raise ConfigError(f"{leaf} must be true or false, got {raw_value!r}") + return json.dumps(raw_value) + + +def get_config_value(key: str, *, path: Path | None = None) -> object | None: + """Read one dotted key (e.g. `agents.claude.model`) from config.toml.""" + path = path or CONFIG_PATH + table_parts, leaf = _parse_dotted_key(key) + load_config(path) # ensures file parses and passes validation + if not path.exists(): + return None + node: object = tomllib.loads(path.read_text(encoding="utf-8")) + for part in table_parts: + if not isinstance(node, dict) or part not in node: + return None + node = node[part] + return node.get(leaf) if isinstance(node, dict) else None + + +def set_config_value(key: str, value: str, *, path: Path | None = None) -> Path: + """Set one dotted key in config.toml, preserving comments and validating via load_config.""" + path = path or CONFIG_PATH + table_parts, leaf = _parse_dotted_key(key) + table_name = ".".join(table_parts) + formatted_value = _format_toml_value(leaf, value) + assignment = f"{leaf} = {formatted_value}" + + existing = path.read_text(encoding="utf-8") if path.exists() else "" + lines = existing.splitlines() + out: list[str] = [] + current_table: str | None = None + found_table = False + replaced = False + + for line in lines: + header_match = _TABLE_HEADER_RE.match(line) + if header_match: + if current_table == table_name and not replaced: + out.append(assignment) + replaced = True + current_table = header_match.group(1).strip() + if current_table == table_name: + found_table = True + out.append(line) + continue + + if current_table == table_name: + kv_match = _KV_LINE_RE.match(line) + if kv_match and kv_match.group(1) == leaf: + if not replaced: + out.append(assignment) + replaced = True + continue + out.append(line) + + if not found_table: + if out and out[-1].strip(): + out.append("") + out.append(f"[{table_name}]") + out.append(assignment) + elif not replaced: + out.append(assignment) + + updated_text = "\n".join(out) + "\n" + # Validate before touching the real config file. + tmp_path = path.with_suffix(".toml.tmp") + path.parent.mkdir(parents=True, exist_ok=True) + tmp_path.write_text(updated_text, encoding="utf-8") + try: + load_config(tmp_path) + except Exception: + tmp_path.unlink(missing_ok=True) + raise + tmp_path.replace(path) + return path diff --git a/src/secfoo/storage/repository.py b/src/secfoo/storage/repository.py index f7f5e88..0ba063f 100644 --- a/src/secfoo/storage/repository.py +++ b/src/secfoo/storage/repository.py @@ -717,12 +717,13 @@ def severity_totals(self, *, project_id: int | None = None) -> SeverityCounts: 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 + """AI spend grouped by agent, skill, project, or model. 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", + "model": "COALESCE(NULLIF(runs.model, ''), '(default)')", }[group_by] query = ( f"SELECT {group_sql} AS label, COUNT(*) AS runs, " # nosec B608 -- group_sql comes from the fixed dict above diff --git a/src/secfoo/web/routes/overview.py b/src/secfoo/web/routes/overview.py index 5096ec4..ca902c4 100644 --- a/src/secfoo/web/routes/overview.py +++ b/src/secfoo/web/routes/overview.py @@ -12,7 +12,8 @@ @router.get("/") -def overview(request: Request): +def overview(request: Request, spend: str = "agent"): + spend_by = spend if spend in {"agent", "model"} else "agent" with RunRepository() as repo: projects = repo.list_projects() assessments = repo.list_assessments(limit=10) @@ -23,6 +24,7 @@ def overview(request: Request): models_count, tools_count = repo.ai_bom_counts_total() top_findings = build_top_findings(repo) cost_by_agent = repo.cost_summary(group_by="agent") + cost_by_model = repo.cost_summary(group_by="model") agent_stats = repo.agent_run_stats() recent_runs = repo.list_runs(limit=6) assessment_count = repo.count_assessments() @@ -55,7 +57,9 @@ def overview(request: Request): "models_count": models_count, "tools_count": tools_count, "top_findings": top_findings, + "spend_by": spend_by, "cost_by_agent": cost_by_agent, + "cost_by_model": cost_by_model, "cost_reporting_agents": COST_REPORTING_AGENTS, "agents": agent_health(agent_stats), "recent_runs": recent_runs, diff --git a/src/secfoo/web/templates/assessments/detail.html b/src/secfoo/web/templates/assessments/detail.html index 60271cb..6ea84e7 100644 --- a/src/secfoo/web/templates/assessments/detail.html +++ b/src/secfoo/web/templates/assessments/detail.html @@ -87,13 +87,14 @@

Attached runs

{% if runs %}
- + {% for run in runs %} + diff --git a/src/secfoo/web/templates/overview.html b/src/secfoo/web/templates/overview.html index d7861aa..2eba38c 100644 --- a/src/secfoo/web/templates/overview.html +++ b/src/secfoo/web/templates/overview.html @@ -200,12 +200,40 @@

Responsible AI risk mix

- {% call info_tip("AI spend by agent") %} -

Cost and token use reported per agent.

+ {% call info_tip("AI spend by model" if spend_by == "model" else "AI spend by agent") %} +

Cost and token use reported per {{ 'model' if spend_by == 'model' else 'agent' }}.

Metered agents send a price. Subscription agents run on your own plan and show no cost here.

{% endcall %} -

AI spend by agent

- {% if cost_by_agent %} +
+

{{ 'AI spend by model' if spend_by == 'model' else 'AI spend by agent' }}

+ +
+ {% if spend_by == 'model' %} + {% if cost_by_model %} +
+
StartedSkillAgentStatusCost
StartedSkillAgentModelStatusCost
{{ run.started_at | fmt_time }} {{ run.skill_name }} {{ run.agent_id }}{{ run.model or '-' }} {% if run.status in ('binary_not_found', 'failed', 'timeout') %}Blocked {{ run.status }}{% else %}{{ run.status }}{% endif %} {{ run.cost_usd | fmt_cost }}
+ + + {% for row in cost_by_model %} + {% set priced = row.unpriced_runs < row.runs %} + {% set tokens_known = row.input_tokens is not none or row.output_tokens is not none %} + + + + + + + {% endfor %} + +
ModelRunsTokensCost
{{ row.label }}{{ row.runs }}{{ (((row.input_tokens or 0) + (row.output_tokens or 0)) | fmt_tokens) if tokens_known else '-' }}{{ (row.cost_usd | fmt_cost) if priced else '-' }}
+
+ {% else %} +

No runs yet.

+ {% endif %} + {% elif cost_by_agent %}
@@ -243,7 +271,7 @@

Recent runs

{{ r.skill_name }} - {{ r.project_display_name }} · {{ r.agent_id }} · + {{ r.project_display_name }} · {{ r.agent_id }}{% if r.model %} ({{ r.model }}){% endif %} · {% if blocked %}Blocked {% else %}{{ r.status }}{% endif %} diff --git a/src/secfoo/web/templates/project.html b/src/secfoo/web/templates/project.html index 0aae26e..cb9562d 100644 --- a/src/secfoo/web/templates/project.html +++ b/src/secfoo/web/templates/project.html @@ -33,13 +33,14 @@

Activity coverage

Runs

AgentRunsTokensCost
- + {% for run in runs %} + diff --git a/src/secfoo/web/templates/run_detail.html b/src/secfoo/web/templates/run_detail.html index d4e56f4..140adef 100644 --- a/src/secfoo/web/templates/run_detail.html +++ b/src/secfoo/web/templates/run_detail.html @@ -8,7 +8,7 @@

{{ run.skill_name }}

{% else %}{{ run.status }}{% endif %}

- {{ run.project_display_name or 'Project' }} · {{ run.agent_id }} · started {{ run.started_at | fmt_time }} + {{ run.project_display_name or 'Project' }} · {{ run.agent_id }}{% if run.model %} ({{ run.model }}){% endif %} · started {{ run.started_at | fmt_time }}

@@ -37,6 +37,7 @@

Progress

Run receipt

agent{{ run.agent_id }}
+
model{{ run.model or 'CLI default' }}
skill{{ run.skill_id }}
{% if run.skill_source %}
diff --git a/tests/test_agents/test_models.py b/tests/test_agents/test_models.py index f173944..771d21a 100644 --- a/tests/test_agents/test_models.py +++ b/tests/test_agents/test_models.py @@ -1,15 +1,39 @@ -"""Model selection stays per adapter and preserves execution boundaries.""" +"""Model discovery, caching, pre-run validation, precedence, and UI/cost display (#111).""" from __future__ import annotations +import json +import sys +import types +from datetime import datetime, timedelta, timezone + import pytest +from fastapi.testclient import TestClient +from typer.testing import CliRunner +from secfoo.agents import models as models_module +from secfoo.agents.base import UnsupportedModelError +from secfoo.agents.models import ModelInfo, discover_models, validate_model_selection from secfoo.agents.registry import ADAPTERS, get_adapter +from secfoo.cli import app +from secfoo.runner import RunOutcome +from secfoo.settings import ( + ConfigError, + SecfooConfig, + get_config_value, + load_config, + resolve_model, + set_config_value, +) +from secfoo.storage.repository import RunRepository +from secfoo.web.app import create_app MODEL_FLAGS = { "claude": "--model", "codex": "--model", "gemini": "--model", "copilot": "--model", "agent": "--model", "droid": "-m", "opencode": "-m", } +cli_runner = CliRunner() + @pytest.mark.parametrize("agent_id", ADAPTERS) def test_model_selection_command_contract(agent_id, tmp_path): @@ -30,7 +54,7 @@ def test_model_selection_command_contract(agent_id, tmp_path): assert adapter.model == model assert adapter.build_command("review", workdir=tmp_path) == [] else: - with pytest.warns(UserWarning, match="ignoring model"): + with pytest.raises(UnsupportedModelError, match="does not support model selection"): adapter.configure_model(model) assert adapter.model is None assert adapter.build_command("review this\ncarefully", workdir=tmp_path) == baseline @@ -47,3 +71,398 @@ def test_selected_model_preserves_stdin_and_process_options(agent_id, tmp_path, assert fake.call_kwargs["cwd"] == tmp_path assert fake.call_kwargs["start_new_session"] is True assert fake.stdin_input == ("multi\nline prompt" if adapter.prompt_via_stdin else None) + + +def test_list_models_all_adapters_curated_or_empty(monkeypatch): + for var in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY"): + monkeypatch.delenv(var, raising=False) + monkeypatch.setattr("secfoo.agents.models.shutil.which", lambda name: None) + + for agent_id in ADAPTERS: + found = get_adapter(agent_id).list_models() + if agent_id in ("agy", "devin", "api"): + assert found == [] + else: + assert found + assert all(m.source == "curated" and m.verified_at for m in found) + + +@pytest.mark.parametrize( + ("agent_id", "stdout", "expected_id"), + [ + ("opencode", "anthropic/claude-sonnet-4-5\nopenai/gpt-5\n", "anthropic/claude-sonnet-4-5"), + ("codex", "gpt-5.4\no3\n", "gpt-5.4"), + ("copilot", "gpt-5\nclaude-sonnet-4.5\n", "gpt-5"), + ("agent", "auto\nclaude-4.5-sonnet\n", "auto"), + ("droid", "claude-sonnet-4-5-20250929\n", "claude-sonnet-4-5-20250929"), + ], +) +def test_list_models_cli_discovery(monkeypatch, agent_id, stdout, expected_id): + monkeypatch.setattr("secfoo.agents.models.shutil.which", lambda name: f"/usr/bin/{name}") + + def fake_run(cmd, **kwargs): + return types.SimpleNamespace(returncode=0, stdout=stdout, stderr="") + + monkeypatch.setattr("secfoo.agents.models.subprocess.run", fake_run) + found = get_adapter(agent_id).list_models() + assert found[0].id == expected_id + assert found[0].source == "cli" + assert found[0].is_live is True + + +def test_list_models_provider_apis(monkeypatch): + monkeypatch.setattr("secfoo.agents.models.shutil.which", lambda name: None) + monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-test") + monkeypatch.setenv("OPENAI_API_KEY", "sk-openai-test") + monkeypatch.setenv("GEMINI_API_KEY", "gem-test") + + def fake_http_get(url, headers): + if "anthropic.com" in url: + return {"data": [{"id": "claude-sonnet-4-6", "display_name": "Claude Sonnet 4.6"}]} + if "openai.com" in url: + return {"data": [{"id": "gpt-5.4"}, {"id": "o3"}]} + if "generativelanguage.googleapis.com" in url: + return { + "models": [ + {"name": "models/gemini-2.5-pro", "displayName": "Gemini 2.5 Pro", "supportedGenerationMethods": ["generateContent"]}, + {"name": "models/embedding-001", "supportedGenerationMethods": ["embedContent"]}, + ] + } + return None + + monkeypatch.setattr("secfoo.agents.models._http_get_json", fake_http_get) + + claude_ids = [m.id for m in get_adapter("claude").list_models()] + assert "claude-sonnet-4-6" in claude_ids + assert "sonnet" in claude_ids + + codex_models = get_adapter("codex").list_models() + assert [m.id for m in codex_models] == ["gpt-5.4", "o3"] + assert all(m.source == "provider" for m in codex_models) + + gemini_models = get_adapter("gemini").list_models() + assert [m.id for m in gemini_models] == ["gemini-2.5-pro"] + assert gemini_models[0].source == "provider" + + +def test_api_adapter_filters_litellm_by_present_keys(monkeypatch): + for var in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY"): + monkeypatch.delenv(var, raising=False) + fake_litellm = types.SimpleNamespace( + model_cost={ + "gpt-4.1-mini": {"litellm_provider": "openai", "mode": "chat"}, + "ft:gpt-3.5-turbo": {"litellm_provider": "openai", "mode": "chat"}, + "text-embedding-3-small": {"litellm_provider": "openai", "mode": "embedding"}, + "claude-sonnet-4-5": {"litellm_provider": "anthropic", "mode": "chat"}, + "gemini/gemini-2.5-flash": {"litellm_provider": "gemini", "mode": "chat"}, + } + ) + monkeypatch.setitem(sys.modules, "litellm", fake_litellm) + + assert get_adapter("api").list_models() == [] + + monkeypatch.setenv("OPENAI_API_KEY", "sk-test") + openai_only = get_adapter("api").list_models() + assert [m.id for m in openai_only] == ["openai/gpt-4.1-mini"] + assert openai_only[0].source == "litellm" + + monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant") + both = [m.id for m in get_adapter("api").list_models()] + assert both == ["anthropic/claude-sonnet-4-5", "openai/gpt-4.1-mini"] + + +def test_models_cache_24h_ttl_and_refresh(tmp_path, monkeypatch): + monkeypatch.setattr("secfoo.config.STORE_DIR", tmp_path) + calls = 0 + + class _CountingAdapter(get_adapter("codex").__class__): + def list_models(self): + nonlocal calls + calls += 1 + return [ModelInfo(id=f"model-v{calls}", display_name=f"Model {calls}", source="provider")] + + adapter = _CountingAdapter() + first = discover_models(adapter) + second = discover_models(adapter) + assert calls == 1 + assert first == second == [ModelInfo(id="model-v1", display_name="Model 1", source="provider")] + + refreshed = discover_models(adapter, refresh=True) + assert calls == 2 + assert refreshed[0].id == "model-v2" + + # Expire the cache manually (>24h ago) and verify re-fetch. + cache_path = models_module.models_cache_path() + data = json.loads(cache_path.read_text(encoding="utf-8")) + data["codex"]["fetched_at"] = (datetime.now(timezone.utc) - timedelta(hours=25)).isoformat() + cache_path.write_text(json.dumps(data), encoding="utf-8") + + expired = discover_models(adapter) + assert calls == 3 + assert expired[0].id == "model-v3" + + +def test_validate_model_selection_live_curated_and_unsupported(): + live_models = [ + ModelInfo(id="claude-sonnet-4-6", source="provider"), + ModelInfo(id="claude-opus-4-6", source="provider"), + ModelInfo(id="claude-haiku-4-5", source="provider"), + ModelInfo(id="gpt-5", source="provider"), + ] + bad = validate_model_selection("claude", "claude-sonet-4-6", models=live_models, supports_model=True) + assert not bad.ok + assert "claude-sonnet-4-6" in bad.suggestions + assert len(bad.suggestions) == 3 + assert "secfoo models --agent claude" in (bad.message or "") + + curated_only = [ModelInfo(id="gpt-5.4", source="curated", verified_at="2026-11-29")] + warn = validate_model_selection("codex", "custom-model", models=curated_only, supports_model=True) + assert warn.ok is True + assert warn.is_warning is True + + unsupported = validate_model_selection("agy", "anything", models=[], supports_model=False) + assert unsupported.ok is False + + +def test_run_rejects_unknown_live_model_and_allows_unchecked(monkeypatch, tmp_path): + monkeypatch.setattr("secfoo.config.STORE_DIR", tmp_path) + monkeypatch.setattr("secfoo.cli.load_config", lambda: SecfooConfig(defaults=types.SimpleNamespace( + agent="claude", depth="quick", timeout=None, exclude=[], fail_on=None, max_cost_usd=None, context=[] + ), mcp_servers=[])) + live = [ + ModelInfo(id="claude-sonnet-4-6", source="provider"), + ModelInfo(id="claude-opus-4-6", source="provider"), + ModelInfo(id="claude-haiku-4-5", source="provider"), + ] + monkeypatch.setattr("secfoo.cli.discover_models", lambda adapter, refresh=False: live) + captured = {} + monkeypatch.setattr("secfoo.cli.execute_runs", lambda **kw: captured.update(kw) or []) + + bad = cli_runner.invoke(app, ["run", "--skill", "sast", "--agent", "claude", "--model", "claude-sonet-4-6"]) + assert bad.exit_code == 1 + assert "claude-sonnet-4-6" in bad.output + assert "execute" not in captured + + bypassed = cli_runner.invoke( + app, ["run", "--skill", "sast", "--agent", "claude", "--model", "claude-sonet-4-6", "--model-unchecked"] + ) + assert bypassed.exit_code == 0, bypassed.output + assert captured["model"] == "claude-sonet-4-6" + + +@pytest.mark.parametrize("agent_id", ["agy", "devin"]) +def test_run_explicit_model_errors_for_unsupported_agents(monkeypatch, agent_id): + monkeypatch.setattr("secfoo.cli.execute_runs", lambda **kw: pytest.fail("must not run")) + result = cli_runner.invoke(app, ["run", "--skill", "sast", "--agent", agent_id, "--model", "some-model"]) + assert result.exit_code == 1 + assert "does not support model selection" in result.output + + +def test_four_level_model_precedence_and_config_set_get(tmp_path, monkeypatch): + cfg_path = tmp_path / "config.toml" + cfg_path.write_text("# Keep comment\n[defaults]\nagent = \"claude\"\n", encoding="utf-8") + + set_config_value("agents.claude.model", "agent-default", path=cfg_path) + set_config_value("skills.sast.model", "skill-sast", path=cfg_path) + set_config_value("agents.claude.skills.sast.model", "claude-sast", path=cfg_path) + set_config_value("skills.secret-scanning.model", "cheap-secret", path=cfg_path) + + assert "# Keep comment" in cfg_path.read_text(encoding="utf-8") + assert get_config_value("agents.claude.model", path=cfg_path) == "agent-default" + assert get_config_value("skills.sast.model", path=cfg_path) == "skill-sast" + assert get_config_value("agents.claude.skills.sast.model", path=cfg_path) == "claude-sast" + + cfg = load_config(cfg_path) + # 1. --model wins over everything + assert resolve_model(cfg, agent_id="claude", skill_id="sast", cli_model="cli-win") == ("cli-win", "cli") + # 2. agent+skill wins over skill and agent + assert resolve_model(cfg, agent_id="claude", skill_id="sast") == ("claude-sast", "agent_skill") + # 3. skill wins over agent + assert resolve_model(cfg, agent_id="claude", skill_id="secret-scanning") == ("cheap-secret", "skill") + # 4. agent wins over default + assert resolve_model(cfg, agent_id="claude", skill_id="threat-modeling") == ("agent-default", "agent") + # 5. default when nothing matches + assert resolve_model(cfg, agent_id="codex", skill_id="threat-modeling") == (None, "default") + + # CLI `config set` and `config get` + monkeypatch.setattr("secfoo.settings.CONFIG_PATH", cfg_path) + monkeypatch.setattr("secfoo.cli.CONFIG_PATH", cfg_path) + assert cli_runner.invoke(app, ["config", "set", "agents.codex.model", "gpt-5.4"]).exit_code == 0 + got = cli_runner.invoke(app, ["config", "get", "agents.codex.model"]) + assert got.exit_code == 0 + assert "gpt-5.4" in got.output + + +def test_models_command_json_and_table(monkeypatch, tmp_path): + monkeypatch.setattr("secfoo.config.STORE_DIR", tmp_path) + monkeypatch.setattr("secfoo.agents.base.shutil.which", lambda b: "/usr/bin/claude" if b == "claude" else None) + for var in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY"): + monkeypatch.delenv(var, raising=False) + + res_json = cli_runner.invoke(app, ["models", "--json"]) + assert res_json.exit_code == 0, res_json.output + data = json.loads(res_json.output) + assert [a["agent"] for a in data["agents"]] == ["claude"] + assert data["agents"][0]["models"] + + res_table = cli_runner.invoke(app, ["models", "--agent", "claude"]) + assert res_table.exit_code == 0 + assert "curated (unverified" in res_table.output + + res_agy = cli_runner.invoke(app, ["models", "--agent", "agy"]) + assert res_agy.exit_code == 0 + assert "not supported" in res_agy.output + + +def test_model_shown_in_cli_json_cost_and_dashboard(tmp_path, monkeypatch): + monkeypatch.setattr("secfoo.storage.repository.DB_PATH", tmp_path / "db.sqlite") + monkeypatch.setattr("secfoo.storage.repository.ensure_store_dirs", lambda: None) + + with RunRepository() as repo: + pid = repo.upsert_project("https://github.com/org/app", "org/app", "github") + aid = repo.create_assessment(project_id=pid, assessment_type="internal", status="in_progress") + r1 = repo.create_run( + project_id=pid, assessment_id=aid, skill_id="sast", skill_name="SAST", + agent_id="api", confluence_urls=[], model="openai/gpt-4.1-mini", + ) + repo.complete_run( + r1, status="success", exit_code=0, duration_seconds=2.0, report_path=None, + prompt_path=None, stderr_excerpt=None, input_tokens=100, output_tokens=50, cost_usd=0.12, + ) + r2 = repo.create_run( + project_id=pid, assessment_id=aid, skill_id="secret-scanning", skill_name="Secret Scanning", + agent_id="claude", confluence_urls=[], model=None, + ) + repo.complete_run( + r2, status="success", exit_code=0, duration_seconds=1.0, report_path=None, + prompt_path=None, stderr_excerpt=None, input_tokens=50, output_tokens=20, cost_usd=0.05, + ) + + listed = cli_runner.invoke(app, ["list"], env={"COLUMNS": "200"}) + assert listed.exit_code == 0 + assert "openai/gpt-4.1-mini" in listed.output + + shown = cli_runner.invoke(app, ["show", r1], env={"COLUMNS": "200"}) + assert shown.exit_code == 0 + assert "openai/gpt-4.1-mini" in shown.output + + cost_res = cli_runner.invoke(app, ["cost", "--by", "model"], env={"COLUMNS": "200"}) + assert cost_res.exit_code == 0 + assert "openai/gpt-4.1-mini" in cost_res.output + assert "(default)" in cost_res.output + assert "$0.12" in cost_res.output + + client = TestClient(create_app()) + assert "openai/gpt-4.1-mini" in client.get(f"/runs/{r1}").text + assert "CLI default" in client.get(f"/runs/{r2}").text + assert "openai/gpt-4.1-mini" in client.get(f"/projects/{pid}").text + assert "openai/gpt-4.1-mini" in client.get(f"/assessments/{aid}").text + + ov_model = client.get("/?spend=model") + assert ov_model.status_code == 200 + assert "AI spend by model" in ov_model.text + assert "openai/gpt-4.1-mini" in ov_model.text + + # `secfoo run --json` includes `model` per run + monkeypatch.setattr( + "secfoo.cli.execute_runs", + lambda **kw: [ + RunOutcome( + run_uuid="u1", skill_id="sast", skill_name="SAST", agent_id="api", + status="success", exit_code=0, duration_seconds=1.0, report_path=None, + model="openai/gpt-4.1-mini", + ) + ], + ) + monkeypatch.setattr("secfoo.cli.discover_models", lambda a, refresh=False: [ModelInfo(id="openai/gpt-4.1-mini", source="litellm")]) + run_json = cli_runner.invoke(app, ["run", "--skill", "sast", "--agent", "api", "--model", "openai/gpt-4.1-mini", "--json"]) + assert run_json.exit_code == 0, run_json.output + doc = json.loads(run_json.output) + assert doc["runs"][0]["model"] == "openai/gpt-4.1-mini" + + +def test_run_passes_per_skill_models_when_skills_differ(tmp_path, monkeypatch): + cfg_path = tmp_path / "config.toml" + cfg_path.write_text( + '[defaults]\nagent = "claude"\n' + '[skills.secret-scanning]\nmodel = "claude-haiku-4-5"\n' + '[agents.claude.skills.threat-modeling]\nmodel = "claude-opus-4-6"\n', + encoding="utf-8", + ) + monkeypatch.setattr("secfoo.cli.load_config", lambda: load_config(cfg_path)) + monkeypatch.setattr( + "secfoo.cli.discover_models", + lambda a, refresh=False: [ + ModelInfo(id="claude-haiku-4-5", source="provider"), + ModelInfo(id="claude-opus-4-6", source="provider"), + ], + ) + captured = {} + monkeypatch.setattr("secfoo.cli.execute_runs", lambda **kw: captured.update(kw) or []) + + res = cli_runner.invoke(app, ["run", "--skill", "secret-scanning", "--skill", "threat-modeling"]) + assert res.exit_code == 0, res.output + assert captured["models_by_skill"] == { + "secret-scanning": "claude-haiku-4-5", + "threat-modeling": "claude-opus-4-6", + } + + +def test_settings_validation_for_skill_and_agent_skill_models(tmp_path): + bad_cases = [ + '[skills]\nsast = "not-a-table"\n', + '[skills.sast]\nmodel = ""\n', + '[agents.claude]\nskills = "not-a-table"\n', + '[agents.claude.skills]\nsast = "not-a-table"\n', + '[agents.claude.skills.sast]\nmodel = " "\n', + ] + for idx, content in enumerate(bad_cases): + p = tmp_path / f"bad_{idx}.toml" + p.write_text(content, encoding="utf-8") + with pytest.raises(ConfigError, match="must be"): + load_config(p) + + +def test_config_set_get_typed_values_and_errors(tmp_path, monkeypatch): + cfg_path = tmp_path / "config.toml" + set_config_value("defaults.timeout", "900", path=cfg_path) + set_config_value("defaults.max_cost_usd", "1.5", path=cfg_path) + set_config_value("memory.enabled", "false", path=cfg_path) + set_config_value("defaults.timeout", "1200", path=cfg_path) + + assert get_config_value("defaults.timeout", path=cfg_path) == 1200 + assert get_config_value("defaults.max_cost_usd", path=cfg_path) == 1.5 + assert get_config_value("memory.enabled", path=cfg_path) is False + assert get_config_value("defaults.nonexistent", path=cfg_path) is None + + for key, val in [("badkey", "1"), ("defaults.timeout", "abc"), ("defaults.max_cost_usd", "xyz"), ("memory.enabled", "maybe")]: + with pytest.raises(ConfigError): + set_config_value(key, val, path=cfg_path) + + monkeypatch.setattr("secfoo.settings.CONFIG_PATH", cfg_path) + monkeypatch.setattr("secfoo.cli.CONFIG_PATH", cfg_path) + assert cli_runner.invoke(app, ["config", "get", "defaults.missing"]).exit_code == 1 + assert cli_runner.invoke(app, ["config", "set", "defaults.timeout", "notanint"]).exit_code == 1 + + +def test_models_edge_cases_cache_corrupt_and_cli_errors(tmp_path, monkeypatch): + monkeypatch.setattr("secfoo.config.STORE_DIR", tmp_path) + cache_path = models_module.models_cache_path() + cache_path.write_text("{corrupt", encoding="utf-8") + + # Non-HTTPS URL rejected without network + assert models_module._http_get_json("http://example.com", {}) is None + + # CLI failure returns None + monkeypatch.setattr("secfoo.agents.models.shutil.which", lambda b: "/usr/bin/" + b) + monkeypatch.setattr("secfoo.agents.models.subprocess.run", lambda *a, **kw: types.SimpleNamespace(returncode=1, stdout="err")) + assert models_module.run_cli_models_command("opencode", ["models"]) is None + + # Blank / header-only CLI lines ignored + parsed = models_module.parse_plain_model_lines("# header\nMODEL\n---\ngpt-5\ngpt-5\n") + assert [m.id for m in parsed] == ["gpt-5"] + + # Cache recovers from corrupt file + adapter = get_adapter("opencode") + found = discover_models(adapter) + assert found and all(m.source == "curated" for m in found) From d90e8424d835b926332299d3b9cc157353f10735 Mon Sep 17 00:00:00 2001 From: aitechnology <40792067+vsn411@users.noreply.github.com> Date: Sun, 29 Nov 2026 09:45:16 +0000 Subject: [PATCH 2/4] fix(config): keep config.toml private and respect [[array]] tables in config set config set wrote config.toml with write_text (0644 under a default umask); the file can hold MCP bearer tokens, so write it with write_private_text (0600, atomic, symlink-safe) like the rest of secfoo. A [[mcp_servers]] header was not recognised as a table boundary, so a key appended to the table above it could land inside the last MCP server entry instead. Co-Authored-By: Claude Opus 5.5 --- src/secfoo/settings.py | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/secfoo/settings.py b/src/secfoo/settings.py index bae8b2c..ba21ec3 100644 --- a/src/secfoo/settings.py +++ b/src/secfoo/settings.py @@ -19,7 +19,7 @@ else: import tomli as tomllib -from secfoo.config import STORE_DIR +from secfoo.config import STORE_DIR, write_private_text CONFIG_PATH = STORE_DIR / "config.toml" @@ -329,6 +329,9 @@ def resolve_model( _KEY_SEGMENT_RE = re.compile(r"^[A-Za-z0-9_-]+$") _TABLE_HEADER_RE = re.compile(r"^\s*\[([^\[\]]+)\]\s*(?:#.*)?$") +# `[[mcp_servers]]` starts an array-of-tables entry: a key after it belongs to +# that entry, never to the [table] above it. +_ARRAY_TABLE_HEADER_RE = re.compile(r"^\s*\[\[([^\[\]]+)\]\]\s*(?:#.*)?$") _KV_LINE_RE = re.compile(r"^\s*([A-Za-z0-9_-]+)\s*=") _STRING_LEAVES = frozenset({"model", "agent", "depth", "fail_on"}) _INT_LEAVES = frozenset({"timeout", "max_input_tokens"}) @@ -397,12 +400,14 @@ def set_config_value(key: str, value: str, *, path: Path | None = None) -> Path: replaced = False for line in lines: - header_match = _TABLE_HEADER_RE.match(line) + array_match = _ARRAY_TABLE_HEADER_RE.match(line) + header_match = array_match or _TABLE_HEADER_RE.match(line) if header_match: if current_table == table_name and not replaced: out.append(assignment) replaced = True - current_table = header_match.group(1).strip() + name = header_match.group(1).strip() + current_table = f"[[{name}]]" if array_match else name if current_table == table_name: found_table = True out.append(line) @@ -429,11 +434,12 @@ def set_config_value(key: str, value: str, *, path: Path | None = None) -> Path: # Validate before touching the real config file. tmp_path = path.with_suffix(".toml.tmp") path.parent.mkdir(parents=True, exist_ok=True) - tmp_path.write_text(updated_text, encoding="utf-8") + # config.toml can hold MCP bearer tokens: write it (and the temp copy) + # 0600, atomically, and through a symlink without replacing it. + write_private_text(tmp_path, updated_text) try: load_config(tmp_path) - except Exception: + finally: tmp_path.unlink(missing_ok=True) - raise - tmp_path.replace(path) + write_private_text(path, updated_text) return path From 537653070e5aa900c0d092b8b82022300904b863 Mon Sep 17 00:00:00 2001 From: aitechnology <40792067+vsn411@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:19:55 +0000 Subject: [PATCH 3/4] fix(models): break the agents.base <-> agents.models import cycle CodeQL flagged py/unsafe-cyclic-import: base.py imported ModelInfo at runtime while models.py imports base. base.py only uses it in annotations, so import it under TYPE_CHECKING. Also explain the empty except around the cache write, and match provider URLs by prefix in the test fake. Co-Authored-By: Claude Opus 5.5 --- src/secfoo/agents/base.py | 7 +++++-- src/secfoo/agents/models.py | 2 +- tests/test_agents/test_models.py | 6 +++--- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/secfoo/agents/base.py b/src/secfoo/agents/base.py index 48593b4..ed6d01e 100644 --- a/src/secfoo/agents/base.py +++ b/src/secfoo/agents/base.py @@ -17,9 +17,12 @@ from abc import ABC, abstractmethod from dataclasses import dataclass from pathlib import Path -from typing import ClassVar, Literal +from typing import TYPE_CHECKING, ClassVar, Literal -from secfoo.agents.models import ModelInfo +if TYPE_CHECKING: + # Annotations only: models.py imports this module, so a runtime import + # here would be a cycle. + from secfoo.agents.models import ModelInfo Status = Literal["success", "failed", "timeout", "binary_not_found", "not_configured"] diff --git a/src/secfoo/agents/models.py b/src/secfoo/agents/models.py index 8cc6c8e..a096c45 100644 --- a/src/secfoo/agents/models.py +++ b/src/secfoo/agents/models.py @@ -112,7 +112,7 @@ def discover_models(adapter: AgentAdapter, *, refresh: bool = False) -> list[Mod try: _write_cache(cache) except OSError: - pass + pass # an unwritable store only means no cache; the models are still returned return models diff --git a/tests/test_agents/test_models.py b/tests/test_agents/test_models.py index 771d21a..6ed86ac 100644 --- a/tests/test_agents/test_models.py +++ b/tests/test_agents/test_models.py @@ -117,11 +117,11 @@ def test_list_models_provider_apis(monkeypatch): monkeypatch.setenv("GEMINI_API_KEY", "gem-test") def fake_http_get(url, headers): - if "anthropic.com" in url: + if url.startswith("https://api.anthropic.com/"): return {"data": [{"id": "claude-sonnet-4-6", "display_name": "Claude Sonnet 4.6"}]} - if "openai.com" in url: + if url.startswith("https://api.openai.com/"): return {"data": [{"id": "gpt-5.4"}, {"id": "o3"}]} - if "generativelanguage.googleapis.com" in url: + if url.startswith("https://generativelanguage.googleapis.com/"): return { "models": [ {"name": "models/gemini-2.5-pro", "displayName": "Gemini 2.5 Pro", "supportedGenerationMethods": ["generateContent"]}, From e781a333f2fa93ea64d952a808ac2ac339d3b9af Mon Sep 17 00:00:00 2001 From: aitechnology <40792067+vsn411@users.noreply.github.com> Date: Sun, 29 Nov 2026 10:48:50 +0000 Subject: [PATCH 4/4] refactor(models): move ModelInfo into agents/model_info.py CodeQL still reported the base <-> models cycle with the import under TYPE_CHECKING. ModelInfo now lives in a module both import, so there is no cycle at all. agents.models still exports it. Co-Authored-By: Claude Opus 5.5 --- src/secfoo/agents/base.py | 7 ++----- src/secfoo/agents/model_info.py | 20 ++++++++++++++++++++ src/secfoo/agents/models.py | 15 +-------------- 3 files changed, 23 insertions(+), 19 deletions(-) create mode 100644 src/secfoo/agents/model_info.py diff --git a/src/secfoo/agents/base.py b/src/secfoo/agents/base.py index ed6d01e..c14a715 100644 --- a/src/secfoo/agents/base.py +++ b/src/secfoo/agents/base.py @@ -17,12 +17,9 @@ from abc import ABC, abstractmethod from dataclasses import dataclass from pathlib import Path -from typing import TYPE_CHECKING, ClassVar, Literal +from typing import ClassVar, Literal -if TYPE_CHECKING: - # Annotations only: models.py imports this module, so a runtime import - # here would be a cycle. - from secfoo.agents.models import ModelInfo +from secfoo.agents.model_info import ModelInfo Status = Literal["success", "failed", "timeout", "binary_not_found", "not_configured"] diff --git a/src/secfoo/agents/model_info.py b/src/secfoo/agents/model_info.py new file mode 100644 index 0000000..babd134 --- /dev/null +++ b/src/secfoo/agents/model_info.py @@ -0,0 +1,20 @@ +"""ModelInfo, in a module of its own: both agents.base and agents.models use +it, and agents.models imports agents.base, so it can't live in either.""" + +from __future__ import annotations + +from dataclasses import dataclass + + +@dataclass(frozen=True) +class ModelInfo: + """One model choice exposed by an agent adapter.""" + + id: str + display_name: str = "" + source: str = "curated" # "cli" | "provider" | "litellm" | "curated" + verified_at: str | None = None + + @property + def is_live(self) -> bool: + return self.source != "curated" diff --git a/src/secfoo/agents/models.py b/src/secfoo/agents/models.py index a096c45..b3136d7 100644 --- a/src/secfoo/agents/models.py +++ b/src/secfoo/agents/models.py @@ -17,6 +17,7 @@ from typing import TYPE_CHECKING from secfoo import config as config_module +from secfoo.agents.model_info import ModelInfo if TYPE_CHECKING: from secfoo.agents.base import AgentAdapter @@ -28,20 +29,6 @@ _PROVIDER_KEY_VARS = ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY") -@dataclass(frozen=True) -class ModelInfo: - """One model choice exposed by an agent adapter.""" - - id: str - display_name: str = "" - source: str = "curated" # "cli" | "provider" | "litellm" | "curated" - verified_at: str | None = None - - @property - def is_live(self) -> bool: - return self.source != "curated" - - def models_cache_path() -> Path: return config_module.STORE_DIR / "models.json"
StartedSkillAgentStatusDurationCost
StartedSkillAgentModelStatusDurationCost
{{ run.started_at | fmt_time }} {{ run.skill_name }} {{ run.agent_id }}{{ run.model or '-' }} {{ run.status }} {{ run.duration_seconds | fmt_duration }} {{ run.cost_usd | fmt_cost }}