Skip to content
Open
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
39 changes: 38 additions & 1 deletion docs/agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,35 @@ brackets indicate optional arguments. All CLI processes run in `WORKDIR`.
| `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. |
| `opencode` | Install via `npm install -g @opencode/cli` ([docs](https://opencode.ai/docs/)); the installed package was `@opencode/[email protected]` on 2026-11-28, Windows x64. Authenticate for paid providers with `opencode auth login` (or `/connect` in the TUI); the free `opencode/*` models used for verification needed no login (`opencode auth list` reported no integrations). `opencode run --standalone --format json [-m MODEL]` (prompt on stdin). v2 removed the v1 `--pure` and `--dir` flags, and the v1 permission env vars are ignored: the read-only `permissions` array is shipped in `src/secfoo/agents/opencode-readonly.json`, loaded via `OPENCODE_CONFIG`, and requires `--standalone` to take effect. |
| `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`. |

## Verification matrix

Recordings are made with `scripts/record_agent.py` (raw stdout/stderr/exit code,
prompt and CLI version; credentials are redacted and the script refuses to save
a transcript containing a key-shaped value). They live under
`tests/fixtures/agents/<id>/<cli-version>/` and are replayed by tests. A blank
cell means "not checked yet", not "verified working".

| `--agent` | CLI version | Date | Verified by | Install | Auth | Run | Timeout | Cost | Recordings |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| `opencode` | `opencode v2.3.0` (`@opencode/[email protected]`, Windows x64) | 2026-11-28 | Shruti Singh | Command from official docs; installed package observed | Free `opencode/*` models needed no login; paid model returned `provider.no-route` | ✅ `secret-scanning --depth quick` on `examples/`, report parsed by `extract_report()` | ✅ 8 s run killed, `status=timeout` | ✅ `step_finish` cost 0; input 46675 / output 3382 tokens | `success`, `auth_failure`, `timeout`, `permission_denied`, `flag_drift` |

The other adapters' version/date/check notes are in the table above; this
matrix is filled in as real recordings land. Issue #116 stays open until every
CLI adapter has a success and a failure recording.

To repeat the opencode run:

```bash
python scripts/record_agent.py --agent opencode --version 2.3.0 \
--scenario success --verified-by "Your Name" --workdir examples \
--prompt-file prompt.md --timeout 180 \
--env OPENCODE_CONFIG=src/secfoo/agents/opencode-readonly.json -- \
opencode run --standalone --format json -m opencode/big-pickle
```

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

Expand All @@ -28,6 +55,12 @@ ignores a requested model. Other CLI model flags are shown above.
- `binary_not_found`: `binary '<name>' not found on PATH` means the CLI
was not found. Install it and make its binary available on `PATH`.
Detection checks the binary, not authentication.
- OpenCode v2.3.0 ignores the v1 `OPENCODE_CONFIG_CONTENT`/`OPENCODE_PERMISSION`
env vars and the v1 `--pure`/`--dir` flags (`flag_drift.json` records the
CLI's `Unrecognized flag` errors). With those env vars alone a write tool
was observed actually creating `proof.txt`; the shipped v2 `permissions`
array plus `--standalone` denied the same write (`permission_denied.json`).
Keep secfoo updated when upgrading OpenCode majors.
- Authentication or trust prompts cannot be answered during a run: stdin
is closed or used for the prompt. Authenticate beforehand. Droid reports
`Authentication failed` without its key; Devin was observed reporting
Expand All @@ -37,7 +70,11 @@ ignores a requested model. Other CLI model flags are shown above.
- `timeout`: secfoo kills the process tree. Cursor's headless mode has a
documented hang; its default timeout is 900 seconds (other CLI adapters
default to 1800). Antigravity also receives its effective print timeout.
- `failed`: inspect the error. Gemini can report `IneligibleTierError`;
OpenCode's 8-second recording produced `status=timeout` with no report.
- `failed`: inspect the error. OpenCode v2 reports an unconfigured provider as
a stdout JSON event (`provider.no-route`, `Model unavailable: ...`) with an
empty stderr; secfoo extracts that message so the reason is not lost. Gemini
can report `IneligibleTierError`;
the adapter suggests Antigravity (`--agent agy`) if it persists. Codex
reports a failed run if its sandbox rejects commands. Antigravity may
return empty output or `Error: Agent execution terminated due to error.`;
Expand Down
196 changes: 196 additions & 0 deletions scripts/record_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
"""Record a real agent-CLI transcript as a replayable test fixture (#116).

The recordings live under ``tests/fixtures/agents/<id>/<cli-version>/`` and
hold raw stdout, stderr, exit code and the prompt that produced them. Secrets
are redacted before the file is written; if any key-shaped value survives
redaction the script refuses to save the recording at all.

Example (run from the repository root)::

python scripts/record_agent.py --agent opencode --version 2.3.0 \
--scenario success --verified-by "Your Name" \
--workdir examples --prompt-file prompt.md --timeout 120 -- \
opencode run --format json

Use ``--model``-style flags in the command itself; the adapter's argv is what
gets verified, so the recording must invoke the real CLI exactly as secfoo
does. A timeout is recorded with exit_code ``null`` and status ``timeout``.
"""

from __future__ import annotations

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

ROOT = Path(__file__).resolve().parents[1]
FIXTURE_ROOT = ROOT / "tests" / "fixtures" / "agents"

# Anything matching one of these must never reach a committed fixture. The
# generic credential rule covers ``KEY=value`` / ``key: value`` spellings that
# vendor-specific patterns miss.
SECRET_PATTERNS = [
re.compile(r"\bsk-ant-[A-Za-z0-9_-]{16,}\b"),
re.compile(r"\bsk-[A-Za-z0-9_-]{16,}\b"),
re.compile(r"\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}\b"),
re.compile(r"\bgithub_pat_[A-Za-z0-9_]{20,}\b"),
re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
re.compile(r"\bAIza[0-9A-Za-z_-]{30,}\b"),
re.compile(r"\bxox[baprs]-[A-Za-z0-9-]{10,}\b"),
re.compile(r"\bBearer\s+[A-Za-z0-9_.\-+/=]{16,}\b"),
re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----"),
re.compile(
r"(?i)\b(?:api[_-]?key|access[_-]?token|auth[_-]?token|password|secret|credential)\b"
r"\s*[:=]\s*[\"']?[A-Za-z0-9_\-./+=]{12,}"
),
]

REDACTED = "[REDACTED]"


def redact(text: str) -> str:
"""Replace every key-shaped value in ``text`` with ``[REDACTED]``."""
for pattern in SECRET_PATTERNS:
text = pattern.sub(REDACTED, text)
return text


def ensure_no_secrets(text: str) -> None:
"""Raise ``ValueError`` if a key-shaped value is still present."""
for pattern in SECRET_PATTERNS:
match = pattern.search(text)
if match:
raise ValueError(f"refusing to save recording: secret pattern {pattern.pattern!r} still matches")


def _kill(proc: subprocess.Popen[str]) -> None:
"""Stop a timed-out CLI and its children before reading its output."""
if os.name == "nt": # no process groups on Windows; taskkill /T gets descendants
subprocess.run( # nosec B603 B607 -- fixed argv, numeric PID from Popen
["taskkill", "/F", "/T", "/PID", str(proc.pid)],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
else:
try:
os.killpg(os.getpgid(proc.pid), 9)
except (ProcessLookupError, OSError):
proc.kill()
try:
proc.communicate(timeout=5)
except subprocess.TimeoutExpired:
pass


def _relative(path: Path) -> str:
"""Store paths relative to the repo so fixtures are machine-independent."""
try:
return path.relative_to(ROOT).as_posix()
except ValueError:
return str(path)


def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--agent", required=True, help="adapter id, e.g. opencode")
parser.add_argument("--version", required=True, help="exact CLI version string reported by the binary")
parser.add_argument("--scenario", required=True, help="e.g. success, auth_failure, timeout")
parser.add_argument("--verified-by", required=True, help="who ran the real CLI")
parser.add_argument("--workdir", default=".", help="directory the CLI runs in (default: repo root)")
parser.add_argument("--prompt-file", help="file whose contents are sent to the CLI on stdin")
parser.add_argument("--prompt", help="prompt text (alternative to --prompt-file)")
parser.add_argument("--timeout", type=float, default=60.0, help="recording timeout in seconds")
parser.add_argument(
"--env", action="append", default=[], metavar="KEY=VALUE", help="extra environment variable (repeatable)"
)
parser.add_argument("command", nargs=argparse.REMAINDER, help="real CLI argv, after --")
args = parser.parse_args(argv)

command = args.command[1:] if args.command and args.command[0] == "--" else args.command
if not command:
parser.error("a CLI command is required after --")
# Same resolution secfoo.agents.base does: on Windows CreateProcess ignores
# PATHEXT, so a bare npm shim name must be replaced by which()'s result.
command[0] = shutil.which(command[0]) or command[0]

if args.prompt_file and args.prompt is not None:
parser.error("use either --prompt-file or --prompt, not both")
if args.prompt_file:
prompt = Path(args.prompt_file).read_text(encoding="utf-8")
else:
prompt = args.prompt

workdir = Path(args.workdir).resolve()
if not workdir.is_dir():
parser.error(f"workdir is not a directory: {workdir}")

env = os.environ.copy()
for item in args.env:
key, sep, value = item.partition("=")
if not sep or not key:
parser.error(f"invalid --env value: {item!r}")
env[key] = value

started = datetime.now(timezone.utc)
proc = subprocess.Popen( # nosec B603 -- command is supplied by the verifier on purpose
command,
cwd=workdir,
stdin=subprocess.PIPE if prompt is not None else subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
encoding="utf-8",
errors="replace",
env=env,
start_new_session=True,
)
try:
stdout, stderr = proc.communicate(input=prompt, timeout=args.timeout)
run_status, exit_code = "completed", proc.returncode
except subprocess.TimeoutExpired:
_kill(proc)
stdout, stderr = proc.communicate()
run_status, exit_code = "timeout", None

record = {
"schema": 1,
"agent": args.agent,
"cli_version": args.version,
"scenario": args.scenario,
"verified_at": started.isoformat(timespec="seconds"),
"verified_by": args.verified_by,
"platform": platform.platform(),
"command": command,
"workdir": _relative(workdir),
"prompt": prompt,
"status": run_status,
"exit_code": exit_code,
"stdout": stdout,
"stderr": stderr,
}

serialized = redact(json.dumps(record, indent=2, ensure_ascii=False))
try:
ensure_no_secrets(serialized)
json.loads(serialized) # redaction must not corrupt the JSON
except ValueError as exc:
print(f"error: {exc}", file=sys.stderr)
return 2

destination = FIXTURE_ROOT / args.agent / args.version / f"{args.scenario}.json"
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_text(serialized + "\n", encoding="utf-8")
print(f"recorded {run_status} (exit={exit_code}) -> {destination.relative_to(ROOT).as_posix()}")
return 0


if __name__ == "__main__":
raise SystemExit(main())
9 changes: 9 additions & 0 deletions src/secfoo/agents/opencode-readonly.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"$schema": "https://opencode.ai/config.json",
"permissions": [
{ "action": "*", "resource": "*", "effect": "deny" },
{ "action": "read", "resource": "*", "effect": "allow" },
{ "action": "glob", "resource": "*", "effect": "allow" },
{ "action": "grep", "resource": "*", "effect": "allow" }
]
}
41 changes: 31 additions & 10 deletions src/secfoo/agents/opencode.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
"""OpenCode CLI adapter, tested against opencode 1.18.34.
"""OpenCode CLI adapter, verified against @opencode/cli 2.3.0 (Windows x64, 2026-11-27).

The non-interactive `run` command reads the prompt from stdin and rejects
permission requests without --auto. Read-only permissions are configured via
OPENCODE_CONFIG_CONTENT and OPENCODE_PERMISSION; --pure disables external plugins.
OpenCode v2 removed the v1 ``--pure`` and ``--dir`` flags (passing either makes
``run`` print help and exit 1), and moved permissions from the v1 ``permission``
object to an ordered ``permissions`` array. The CLI only loads an explicit
config when ``--standalone`` is used; with the shared background server the
v1 env overrides are ignored and writes are allowed. The read-only policy is
therefore shipped in ``opencode-readonly.json`` and passed via OPENCODE_CONFIG.
"""

from __future__ import annotations
Expand All @@ -24,22 +27,31 @@ def _events(stdout: str):
yield event


def _errors(stdout: str):
for line in stdout.splitlines():
try:
event = json.loads(line)
except json.JSONDecodeError:
continue
if isinstance(event, dict) and event.get("type") == "error" and isinstance(event.get("error"), dict):
yield event["error"]


class OpenCodeAdapter(AgentAdapter):
name = "opencode"
binary = "opencode"
prompt_via_stdin = True
model_flag = "-m"
extra_env: ClassVar[dict[str, str]] = {
"OPENCODE_CONFIG_CONTENT": json.dumps(
{"permission": {"bash": "deny", "edit": "deny", "webfetch": "deny"}}
),
"OPENCODE_PERMISSION": json.dumps({"bash": "deny", "edit": "deny", "webfetch": "deny"}),
"OPENCODE_CONFIG": str(Path(__file__).with_name("opencode-readonly.json")),
}

def build_command(self, prompt: str, *, workdir: Path) -> list[str]:
# --standalone is required for OPENCODE_CONFIG to be applied; cwd is
# set by AgentAdapter.run(), so no --dir is needed (v2 has no --dir).
return [
self.binary, "run", "--pure", "--format", "json",
"--dir", str(workdir), *self.model_arguments(),
self.binary, "run", "--standalone", "--format", "json",
*self.model_arguments(),
]

def extract_report(self, stdout: str) -> str:
Expand All @@ -65,3 +77,12 @@ def total(values):
output_tokens=total(token.get("output") for token in tokens),
cost_usd=total(part.get("cost") for part in steps),
)

def describe_failure(self, stdout: str, stderr: str) -> str | None:
# v2 reports auth/no-route failures as JSON events on stdout with an
# empty stderr; surface the CLI's own message instead of a blank error.
for error in _errors(stdout):
message = error.get("message")
if isinstance(message, str) and message:
return message
return None
24 changes: 24 additions & 0 deletions tests/fixtures/agents/opencode/2.3.0/auth_failure.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"schema": 1,
"agent": "opencode",
"cli_version": "2.3.0",
"scenario": "auth_failure",
"verified_at": "2026-11-27T18:30:17+00:00",
"verified_by": "Shruti Singh",
"platform": "Windows-11-10.0.26300-SP0",
"command": [
"C:\\Users\\shrut\\AppData\\Roaming\\npm\\opencode.CMD",
"run",
"--standalone",
"--format",
"json",
"-m",
"anthropic/claude-sonnet-4-6"
],
"workdir": ".",
"prompt": "Reply with exactly: OK\n",
"status": "completed",
"exit_code": 1,
"stdout": "{\"type\":\"error\",\"timestamp\":1795804221674,\"sessionID\":\"ses_de1ba356effehbijTS1Le1HHsz\",\"error\":{\"type\":\"provider.no-route\",\"message\":\"Model unavailable: anthropic/claude-sonnet-4-6\"}}\n",
"stderr": ""
}
Loading