Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion docs/agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,32 @@ brackets indicate optional arguments. All CLI processes run in `WORKDIR`.
| `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. |
| `copilot` | Install via `npm install -g @github/copilot` ([docs](https://docs.github.com/en/copilot/how-tos/use-copilot-agents/use-copilot-cli)). Authenticate by running `copilot` and using its `/login` command, or set `GH_TOKEN` / `GITHUB_TOKEN` (a fine-grained token with the Copilot Requests permission) for non-interactive use (verified against the real CLI 1.0.117 on 2026-11-29, Windows: `gh auth login` plus `GH_TOKEN` from `gh auth token` worked; see the matrix below). `copilot [--model MODEL] --output-format json --allow-all-tools --usage-output-file PATH` (prompt on stdin). Token counts come from the usage file; premium requests / AI credits are not USD, so `cost_usd` stays unknown. Tools, including writes, are auto-approved: read-only behavior relies on review instructions, not a sandbox. |
| `droid` | Install via `curl -fsSL https://app.factory.ai/cli \| sh` ([docs](https://docs.factory.ai/cli/getting-started/overview)). Set `FACTORY_API_KEY` for non-interactive use or run `droid` to sign in interactively (checked against official docs on 2026-11-21, not on an installed CLI). `droid exec [-m MODEL] --output-format json --cwd WORKDIR -- PROMPT`. Droid defaults to read-only; a full authenticated secfoo run was not verified in the adapter. |
| `devin` | Install via `brew install --cask devin-cli` ([docs](https://docs.devin.ai)). Authenticate beforehand with `devin auth login`; credential reuse for headless runs is unverified (install and login checked against official docs on 2026-11-21, not on an installed CLI). `devin -p PROMPT --respect-workspace-trust false --permission-mode auto`. The combined command and an authenticated end-to-end run are unverified; `auto` is documented by the CLI as approving read-only tools. |
| `api` | No agent binary is invoked. `litellm` and `langgraph` are installed with secfoo; if importing them fails, reinstall secfoo the way you installed it (`pipx reinstall secfoo` or `pip install --force-reinstall secfoo`). Set `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, or `GEMINI_API_KEY`. Source files are included in the API prompt. Model selection uses the configured model, then `SECFOO_API_MODEL`, then `openai/gpt-4.1-mini`. MCP servers from `[[mcp_servers]]` (and `secfoo-memory`) are connected by secfoo itself. Only their read-only tools are offered to the model (`readOnlyHint: true`, or the server's `tools = [...]` list), with at most 20 tool calls per run (`[agents.api].tool_call_budget`, `0` turns tools off). The tool phase also stops once the input tokens sent reach 4× the first call's. Each call, the number of rounds and the total input tokens are logged to `stderr.log`. |

`agy` and `devin` do not support adapter model selection; secfoo warns and
ignores a requested model. Other CLI model flags are shown above.

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

`✓` means checked against a real installed CLI, with the transcript committed
under `tests/fixtures/agents/<id>/<cli-version>/` and replayed by
`tests/test_agents/test_copilot_recordings.py`. `—` means not verified yet;
the setup notes above still come from help output or documentation only.
Recordings are redacted by `scripts/record_agent.py`, which refuses to save a
fixture if a credential-shaped string survives.

| Adapter | CLI version | Date (UTC) | Verifier | Install | Auth | Full non-interactive run | Timeout | Cost/tokens | Evidence |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| `copilot` | 1.0.117 | 2026-11-29 | Shruti070107 | ✓ `npm install -g @github/copilot` | ✓ `gh auth login`, `GH_TOKEN` from `gh auth token`; 401 with an invalid token | ✓ `secret-scanning --depth quick` on `examples/` | ✓ 1s run killed by secfoo | ✓ tokens from `--usage-output-file`; CLI reports credits, not USD | `success.json`, `auth_failure.json`, `timeout.json`, `binary_not_found.json` |
| `claude`, `agent`, `agy`, `gemini`, `codex`, `droid`, `devin`, `opencode` | — | — | — | — | — | — | — | — | Not verified in this PR; `opencode` is covered separately in upstream PR #207. |

`not_configured` is the `api` adapter's status for a missing model key, not a
CLI adapter status. CLI adapters report a missing binary as `binary_not_found`
and rejected credentials as `failed`.

## Troubleshooting

- `binary_not_found`: `binary '<name>' not found on PATH` means the CLI
Expand Down
301 changes: 301 additions & 0 deletions scripts/record_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,301 @@
"""Record a real agent CLI transcript as a redacted JSON fixture.

Usage (from the repo root):

python scripts/record_agent.py --agent claude --scenario success \
--skill secret-scanning --workdir examples --timeout 240

The script runs the *real* secfoo adapter (same argv, same stdin/stdout
contract), then stores stdout, stderr, exit code, status and usage under
``tests/fixtures/agents/<id>/<cli-version>/<scenario>.json``. Before writing
anything it redacts known credential shapes and refuses to save if a key
pattern is still present. JSONL transcripts also have opaque provider IDs
and encrypted reasoning blobs replaced, and bulky tool output truncated,
while every event and the final report are kept. Environment variable values
are never recorded -- only their names, for scenarios that isolate credentials.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import os
import platform
import re
import shutil
import subprocess
import sys
import tempfile
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))

from secfoo.agents.registry import get_adapter
from secfoo.skills.loader import load_skill
from secfoo.skills.renderer import TargetContext, render_prompt

REDACTED = "[REDACTED]"

# Provider-generated identifiers and encrypted reasoning are neither useful
# evidence nor safe to publish; replacing them keeps the transcript small and
# reviewable without changing the event sequence secfoo parses.
OPAQUE_KEYS = {
"id",
"parentId",
"sessionId",
"messageId",
"apiCallId",
"reasoningId",
"reasoningOpaque",
"toolCallId",
"interactionId",
"ownerNativeSessionId",
"encrypted_content",
"timestamp",
"occurredAt",
"startTime",
"endTime",
"cacheExpiresAt",
}
MAX_TEXT = 1200

# Patterns are deliberately broad: a false positive aborts the recording and
# the operator can inspect it locally, while a false negative would commit a
# credential to a public repository.
KEY_PATTERNS = {
"openai": re.compile(r"\bsk-(?:proj-)?[A-Za-z0-9_-]{16,}\b"),
"anthropic": re.compile(r"\bsk-ant-[A-Za-z0-9_-]{16,}\b"),
"github": re.compile(r"\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{30,})\b"),
"aws": re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"),
"slack": re.compile(r"\bxox[baprs]-[A-Za-z0-9-]{10,}\b"),
"private_key": re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),
"assignment": re.compile(
r"(?i)\b(api[_-]?key|access[_-]?token|auth[_-]?token|password|secret)\b"
r"\s*[:=]\s*[\"']?(?!" + re.escape(REDACTED) + r")([^\s,;\"']{8,})"
),
}


class KeyFound(RuntimeError):
"""A credential-shaped string survived redaction; do not write the file."""


def redact(text: str) -> str:
for name, pattern in KEY_PATTERNS.items():
replacement = r"\1=" + REDACTED if name == "assignment" else REDACTED
text = pattern.sub(replacement, text)
return text


def assert_no_keys(text: str, *, where: str) -> None:
for name, pattern in KEY_PATTERNS.items():
if pattern.search(text):
raise KeyFound(f"{name} pattern found in {where}; refusing to save")


def scrub_event(event: object, *, keep_full: bool = False) -> object:
"""Keep a real CLI event, minus opaque IDs and oversized non-report text."""
if not isinstance(event, dict):
return event
# The final main-agent answer is the evidence extract_report() consumes,
# so it is kept in full; all other long strings (subagent answers, tool
# output, reasoning deltas, echoed prompt) are truncated with a marker.
keep = {".data.content"} if keep_full else set()

def scrub(value: object, *, key: str | None = None, path: str = "") -> object:
if key in OPAQUE_KEYS:
return REDACTED
if isinstance(value, dict):
return {name: scrub(item, key=name, path=f"{path}.{name}") for name, item in value.items()}
if isinstance(value, list):
return [scrub(item, key=key, path=f"{path}[]") for item in value]
if isinstance(value, str):
value = redact(value)
if path in keep or len(value) <= MAX_TEXT:
return value
return f"{value[:MAX_TEXT]}\n[{REDACTED} {len(value) - MAX_TEXT} chars]"
return value

return scrub(event)


def redact_transcript(text: str) -> str:
"""Redact JSONL stdin/stdout while preserving one line per CLI event."""
parsed: list[object] = []
for line in text.splitlines():
try:
parsed.append(json.loads(line))
except json.JSONDecodeError:
parsed.append(line)

keep_index = -1
for index, event in enumerate(parsed):
if isinstance(event, dict) and event.get("type") == "assistant.message" and "agentId" not in event:
keep_index = index

lines = [
json.dumps(
scrub_event(event, keep_full=(index == keep_index)),
ensure_ascii=False,
separators=(",", ":"),
)
if isinstance(event, dict)
else redact(event)
for index, event in enumerate(parsed)
]
return "\n".join(lines) + ("\n" if text.endswith("\n") else "")


def version_slug(version: str) -> str:
match = re.search(r"\d+\.\d+(?:\.\d+)?", version)
slug = match.group(0) if match else re.sub(r"[^A-Za-z0-9._-]+", "-", version).strip("-")
return slug or "unknown"


def cli_version(binary: str) -> str:
try:
found = shutil.which(binary) or binary
out = subprocess.run([found, "--version"], capture_output=True, text=True, timeout=15, check=False)
text = (out.stdout or out.stderr).strip()
# copilot 1.0.117 prints a package-extraction banner before its
# version; take the first line that actually looks like a version.
match = re.search(r"\b\d+\.\d+\.\d+\b", text)
return match.group(0) if match else (text.splitlines() or ["unknown"])[0]
except (OSError, subprocess.SubprocessError):
return "unknown"


def render(skill_id: str, workdir: Path, depth: str) -> str:
return render_prompt(
load_skill(skill_id),
TargetContext(kind="local", local_path=workdir, display_source=str(workdir)),
depth=depth,
)


def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--agent", default="claude", help="Adapter id (default: claude)")
parser.add_argument(
"--scenario",
required=True,
choices=["success", "auth_failure", "timeout", "binary_not_found"],
help="Which real execution to record",
)
parser.add_argument("--skill", default="secret-scanning")
parser.add_argument("--workdir", type=Path, default=Path("examples"))
parser.add_argument("--depth", default="quick", choices=["quick", "standard"])
parser.add_argument("--timeout", type=int, default=240, help="Seconds passed to adapter.run()")
parser.add_argument("--expect", help="Assert the resulting status (e.g. timeout)")
args = parser.parse_args()

workdir = (ROOT / args.workdir).resolve() if not args.workdir.is_absolute() else args.workdir.resolve()
if not workdir.is_dir():
parser.error(f"workdir does not exist: {workdir}")

adapter = get_adapter(args.agent)
version = cli_version(adapter.binary)
prompt = render(args.skill, workdir, args.depth)
env_changes: dict[str, str | None] = {}
saved_env: dict[str, str | None] = {}
restore_which = None
try:
if args.scenario == "auth_failure":
isolated = tempfile.mkdtemp(prefix=f"secfoo-no-auth-{args.agent}-")
if args.agent == "claude":
# An isolated config dir has no /login session; removing the
# key env vars leaves the real CLI with no credentials.
env_changes = {
"CLAUDE_CONFIG_DIR": isolated,
"ANTHROPIC_API_KEY": None,
"CLAUDE_CODE_OAUTH_TOKEN": None,
}
elif args.agent == "copilot":
# An isolated COPILOT_HOME plus a deliberately invalid token
# makes the real CLI reject auth with a 401 (no real key is
# written to the fixture -- stdout/stderr are redacted).
env_changes = {
"COPILOT_HOME": isolated,
"COPILOT_GITHUB_TOKEN": None,
"GITHUB_TOKEN": None,
"GH_TOKEN": "invalid-token-for-test",
}
else:
parser.error(f"auth_failure scenario not implemented for {args.agent!r}")
for name, value in env_changes.items():
saved_env[name] = os.environ.get(name)
if value is None:
os.environ.pop(name, None)
else:
os.environ[name] = value
if args.scenario == "binary_not_found":
from secfoo.agents import base

restore_which = base.shutil.which
base.shutil.which = lambda _name: None # type: ignore[assignment]

# build_command is called separately only to record the exact argv;
# run() still builds and executes it itself, unmodified.
argv = [str(part) for part in adapter.build_command(prompt, workdir=workdir)]
result = adapter.run(prompt, workdir=workdir, timeout=args.timeout)
finally:
for name, value in saved_env.items():
if value is None:
os.environ.pop(name, None)
else:
os.environ[name] = value
if restore_which is not None:
from secfoo.agents import base

base.shutil.which = restore_which # type: ignore[assignment]

if args.expect and result.status != args.expect:
raise SystemExit(f"expected status {args.expect!r}, got {result.status!r}: {result.stderr[:500]}")

payload = {
"schema_version": 1,
"agent": args.agent,
"scenario": args.scenario,
"cli_version": version,
"recorded_at": datetime.now(timezone.utc).isoformat(),
"platform": platform.platform(),
"python": platform.python_version(),
"skill": args.skill,
"depth": args.depth,
"workdir": str(workdir.relative_to(ROOT)) if workdir.is_relative_to(ROOT) else "<external>",
"argv": [redact(part) for part in argv],
"env_names_isolated": sorted(env_changes),
"prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(),
"exit_code": result.exit_code,
"status": result.status,
"duration_seconds": round(result.duration_seconds, 3),
"stdout": redact_transcript(result.stdout),
"stderr": redact_transcript(result.stderr),
"raw_report": redact(result.raw_report),
"usage": {
"input_tokens": result.input_tokens,
"output_tokens": result.output_tokens,
"cost_usd": result.cost_usd,
},
# CopilotAdapter keeps the exact JSON the CLI wrote so the test can
# check secfoo's numbers against the CLI's printed numbers.
"usage_file": getattr(adapter, "last_usage_payload", None),
}
text = json.dumps(payload, indent=2, ensure_ascii=False) + "\n"
assert_no_keys(text, where="the complete fixture")

fixture = ROOT / "tests" / "fixtures" / "agents" / args.agent / version_slug(version) / f"{args.scenario}.json"
fixture.parent.mkdir(parents=True, exist_ok=True)
fixture.write_text(text, encoding="utf-8")
print(
f"{args.agent}/{version_slug(version)}/{args.scenario}: status={result.status} "
f"exit={result.exit_code} bytes={len(result.stdout)} saved={fixture.relative_to(ROOT)}"
)
return 0


if __name__ == "__main__":
raise SystemExit(main())
Loading
Loading