Skip to content

Commit 91ade50

Browse files
authored
feat(agents): verify the copilot adapter against the real CLI 1.0.117 (#214)
Part of #116.
1 parent 4a4e58f commit 91ade50

10 files changed

Lines changed: 885 additions & 4 deletions

File tree

‎docs/agents.md‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,32 @@ brackets indicate optional arguments. All CLI processes run in `WORKDIR`.
1515
| `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. |
1616
| `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. |
1717
| `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). |
18-
| `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. |
18+
| `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. |
1919
| `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. |
2020
| `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. |
2121
| `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`. |
2222

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

26+
## Real-CLI verification matrix (issue #116)
27+
28+
`✓` means checked against a real installed CLI, with the transcript committed
29+
under `tests/fixtures/agents/<id>/<cli-version>/` and replayed by
30+
`tests/test_agents/test_copilot_recordings.py`. `—` means not verified yet;
31+
the setup notes above still come from help output or documentation only.
32+
Recordings are redacted by `scripts/record_agent.py`, which refuses to save a
33+
fixture if a credential-shaped string survives.
34+
35+
| Adapter | CLI version | Date (UTC) | Verifier | Install | Auth | Full non-interactive run | Timeout | Cost/tokens | Evidence |
36+
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
37+
| `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` |
38+
| `claude`, `agent`, `agy`, `gemini`, `codex`, `droid`, `devin`, `opencode` | — | — | — | — | — | — | — | — | Not verified in this PR; `opencode` is covered separately in upstream PR #207. |
39+
40+
`not_configured` is the `api` adapter's status for a missing model key, not a
41+
CLI adapter status. CLI adapters report a missing binary as `binary_not_found`
42+
and rejected credentials as `failed`.
43+
2644
## Troubleshooting
2745

2846
- `binary_not_found`: `binary '<name>' not found on PATH` means the CLI

‎scripts/record_agent.py‎

Lines changed: 301 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,301 @@
1+
"""Record a real agent CLI transcript as a redacted JSON fixture.
2+
3+
Usage (from the repo root):
4+
5+
python scripts/record_agent.py --agent claude --scenario success \
6+
--skill secret-scanning --workdir examples --timeout 240
7+
8+
The script runs the *real* secfoo adapter (same argv, same stdin/stdout
9+
contract), then stores stdout, stderr, exit code, status and usage under
10+
``tests/fixtures/agents/<id>/<cli-version>/<scenario>.json``. Before writing
11+
anything it redacts known credential shapes and refuses to save if a key
12+
pattern is still present. JSONL transcripts also have opaque provider IDs
13+
and encrypted reasoning blobs replaced, and bulky tool output truncated,
14+
while every event and the final report are kept. Environment variable values
15+
are never recorded -- only their names, for scenarios that isolate credentials.
16+
"""
17+
18+
from __future__ import annotations
19+
20+
import argparse
21+
import hashlib
22+
import json
23+
import os
24+
import platform
25+
import re
26+
import shutil
27+
import subprocess
28+
import sys
29+
import tempfile
30+
from datetime import datetime, timezone
31+
from pathlib import Path
32+
33+
ROOT = Path(__file__).resolve().parents[1]
34+
sys.path.insert(0, str(ROOT / "src"))
35+
36+
from secfoo.agents.registry import get_adapter
37+
from secfoo.skills.loader import load_skill
38+
from secfoo.skills.renderer import TargetContext, render_prompt
39+
40+
REDACTED = "[REDACTED]"
41+
42+
# Provider-generated identifiers and encrypted reasoning are neither useful
43+
# evidence nor safe to publish; replacing them keeps the transcript small and
44+
# reviewable without changing the event sequence secfoo parses.
45+
OPAQUE_KEYS = {
46+
"id",
47+
"parentId",
48+
"sessionId",
49+
"messageId",
50+
"apiCallId",
51+
"reasoningId",
52+
"reasoningOpaque",
53+
"toolCallId",
54+
"interactionId",
55+
"ownerNativeSessionId",
56+
"encrypted_content",
57+
"timestamp",
58+
"occurredAt",
59+
"startTime",
60+
"endTime",
61+
"cacheExpiresAt",
62+
}
63+
MAX_TEXT = 1200
64+
65+
# Patterns are deliberately broad: a false positive aborts the recording and
66+
# the operator can inspect it locally, while a false negative would commit a
67+
# credential to a public repository.
68+
KEY_PATTERNS = {
69+
"openai": re.compile(r"\bsk-(?:proj-)?[A-Za-z0-9_-]{16,}\b"),
70+
"anthropic": re.compile(r"\bsk-ant-[A-Za-z0-9_-]{16,}\b"),
71+
"github": re.compile(r"\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{30,})\b"),
72+
"aws": re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"),
73+
"slack": re.compile(r"\bxox[baprs]-[A-Za-z0-9-]{10,}\b"),
74+
"private_key": re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),
75+
"assignment": re.compile(
76+
r"(?i)\b(api[_-]?key|access[_-]?token|auth[_-]?token|password|secret)\b"
77+
r"\s*[:=]\s*[\"']?(?!" + re.escape(REDACTED) + r")([^\s,;\"']{8,})"
78+
),
79+
}
80+
81+
82+
class KeyFound(RuntimeError):
83+
"""A credential-shaped string survived redaction; do not write the file."""
84+
85+
86+
def redact(text: str) -> str:
87+
for name, pattern in KEY_PATTERNS.items():
88+
replacement = r"\1=" + REDACTED if name == "assignment" else REDACTED
89+
text = pattern.sub(replacement, text)
90+
return text
91+
92+
93+
def assert_no_keys(text: str, *, where: str) -> None:
94+
for name, pattern in KEY_PATTERNS.items():
95+
if pattern.search(text):
96+
raise KeyFound(f"{name} pattern found in {where}; refusing to save")
97+
98+
99+
def scrub_event(event: object, *, keep_full: bool = False) -> object:
100+
"""Keep a real CLI event, minus opaque IDs and oversized non-report text."""
101+
if not isinstance(event, dict):
102+
return event
103+
# The final main-agent answer is the evidence extract_report() consumes,
104+
# so it is kept in full; all other long strings (subagent answers, tool
105+
# output, reasoning deltas, echoed prompt) are truncated with a marker.
106+
keep = {".data.content"} if keep_full else set()
107+
108+
def scrub(value: object, *, key: str | None = None, path: str = "") -> object:
109+
if key in OPAQUE_KEYS:
110+
return REDACTED
111+
if isinstance(value, dict):
112+
return {name: scrub(item, key=name, path=f"{path}.{name}") for name, item in value.items()}
113+
if isinstance(value, list):
114+
return [scrub(item, key=key, path=f"{path}[]") for item in value]
115+
if isinstance(value, str):
116+
value = redact(value)
117+
if path in keep or len(value) <= MAX_TEXT:
118+
return value
119+
return f"{value[:MAX_TEXT]}\n[{REDACTED} {len(value) - MAX_TEXT} chars]"
120+
return value
121+
122+
return scrub(event)
123+
124+
125+
def redact_transcript(text: str) -> str:
126+
"""Redact JSONL stdin/stdout while preserving one line per CLI event."""
127+
parsed: list[object] = []
128+
for line in text.splitlines():
129+
try:
130+
parsed.append(json.loads(line))
131+
except json.JSONDecodeError:
132+
parsed.append(line)
133+
134+
keep_index = -1
135+
for index, event in enumerate(parsed):
136+
if isinstance(event, dict) and event.get("type") == "assistant.message" and "agentId" not in event:
137+
keep_index = index
138+
139+
lines = [
140+
json.dumps(
141+
scrub_event(event, keep_full=(index == keep_index)),
142+
ensure_ascii=False,
143+
separators=(",", ":"),
144+
)
145+
if isinstance(event, dict)
146+
else redact(event)
147+
for index, event in enumerate(parsed)
148+
]
149+
return "\n".join(lines) + ("\n" if text.endswith("\n") else "")
150+
151+
152+
def version_slug(version: str) -> str:
153+
match = re.search(r"\d+\.\d+(?:\.\d+)?", version)
154+
slug = match.group(0) if match else re.sub(r"[^A-Za-z0-9._-]+", "-", version).strip("-")
155+
return slug or "unknown"
156+
157+
158+
def cli_version(binary: str) -> str:
159+
try:
160+
found = shutil.which(binary) or binary
161+
out = subprocess.run([found, "--version"], capture_output=True, text=True, timeout=15, check=False)
162+
text = (out.stdout or out.stderr).strip()
163+
# copilot 1.0.117 prints a package-extraction banner before its
164+
# version; take the first line that actually looks like a version.
165+
match = re.search(r"\b\d+\.\d+\.\d+\b", text)
166+
return match.group(0) if match else (text.splitlines() or ["unknown"])[0]
167+
except (OSError, subprocess.SubprocessError):
168+
return "unknown"
169+
170+
171+
def render(skill_id: str, workdir: Path, depth: str) -> str:
172+
return render_prompt(
173+
load_skill(skill_id),
174+
TargetContext(kind="local", local_path=workdir, display_source=str(workdir)),
175+
depth=depth,
176+
)
177+
178+
179+
def main() -> int:
180+
parser = argparse.ArgumentParser(description=__doc__)
181+
parser.add_argument("--agent", default="claude", help="Adapter id (default: claude)")
182+
parser.add_argument(
183+
"--scenario",
184+
required=True,
185+
choices=["success", "auth_failure", "timeout", "binary_not_found"],
186+
help="Which real execution to record",
187+
)
188+
parser.add_argument("--skill", default="secret-scanning")
189+
parser.add_argument("--workdir", type=Path, default=Path("examples"))
190+
parser.add_argument("--depth", default="quick", choices=["quick", "standard"])
191+
parser.add_argument("--timeout", type=int, default=240, help="Seconds passed to adapter.run()")
192+
parser.add_argument("--expect", help="Assert the resulting status (e.g. timeout)")
193+
args = parser.parse_args()
194+
195+
workdir = (ROOT / args.workdir).resolve() if not args.workdir.is_absolute() else args.workdir.resolve()
196+
if not workdir.is_dir():
197+
parser.error(f"workdir does not exist: {workdir}")
198+
199+
adapter = get_adapter(args.agent)
200+
version = cli_version(adapter.binary)
201+
prompt = render(args.skill, workdir, args.depth)
202+
env_changes: dict[str, str | None] = {}
203+
saved_env: dict[str, str | None] = {}
204+
restore_which = None
205+
try:
206+
if args.scenario == "auth_failure":
207+
isolated = tempfile.mkdtemp(prefix=f"secfoo-no-auth-{args.agent}-")
208+
if args.agent == "claude":
209+
# An isolated config dir has no /login session; removing the
210+
# key env vars leaves the real CLI with no credentials.
211+
env_changes = {
212+
"CLAUDE_CONFIG_DIR": isolated,
213+
"ANTHROPIC_API_KEY": None,
214+
"CLAUDE_CODE_OAUTH_TOKEN": None,
215+
}
216+
elif args.agent == "copilot":
217+
# An isolated COPILOT_HOME plus a deliberately invalid token
218+
# makes the real CLI reject auth with a 401 (no real key is
219+
# written to the fixture -- stdout/stderr are redacted).
220+
env_changes = {
221+
"COPILOT_HOME": isolated,
222+
"COPILOT_GITHUB_TOKEN": None,
223+
"GITHUB_TOKEN": None,
224+
"GH_TOKEN": "invalid-token-for-test",
225+
}
226+
else:
227+
parser.error(f"auth_failure scenario not implemented for {args.agent!r}")
228+
for name, value in env_changes.items():
229+
saved_env[name] = os.environ.get(name)
230+
if value is None:
231+
os.environ.pop(name, None)
232+
else:
233+
os.environ[name] = value
234+
if args.scenario == "binary_not_found":
235+
from secfoo.agents import base
236+
237+
restore_which = base.shutil.which
238+
base.shutil.which = lambda _name: None # type: ignore[assignment]
239+
240+
# build_command is called separately only to record the exact argv;
241+
# run() still builds and executes it itself, unmodified.
242+
argv = [str(part) for part in adapter.build_command(prompt, workdir=workdir)]
243+
result = adapter.run(prompt, workdir=workdir, timeout=args.timeout)
244+
finally:
245+
for name, value in saved_env.items():
246+
if value is None:
247+
os.environ.pop(name, None)
248+
else:
249+
os.environ[name] = value
250+
if restore_which is not None:
251+
from secfoo.agents import base
252+
253+
base.shutil.which = restore_which # type: ignore[assignment]
254+
255+
if args.expect and result.status != args.expect:
256+
raise SystemExit(f"expected status {args.expect!r}, got {result.status!r}: {result.stderr[:500]}")
257+
258+
payload = {
259+
"schema_version": 1,
260+
"agent": args.agent,
261+
"scenario": args.scenario,
262+
"cli_version": version,
263+
"recorded_at": datetime.now(timezone.utc).isoformat(),
264+
"platform": platform.platform(),
265+
"python": platform.python_version(),
266+
"skill": args.skill,
267+
"depth": args.depth,
268+
"workdir": str(workdir.relative_to(ROOT)) if workdir.is_relative_to(ROOT) else "<external>",
269+
"argv": [redact(part) for part in argv],
270+
"env_names_isolated": sorted(env_changes),
271+
"prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(),
272+
"exit_code": result.exit_code,
273+
"status": result.status,
274+
"duration_seconds": round(result.duration_seconds, 3),
275+
"stdout": redact_transcript(result.stdout),
276+
"stderr": redact_transcript(result.stderr),
277+
"raw_report": redact(result.raw_report),
278+
"usage": {
279+
"input_tokens": result.input_tokens,
280+
"output_tokens": result.output_tokens,
281+
"cost_usd": result.cost_usd,
282+
},
283+
# CopilotAdapter keeps the exact JSON the CLI wrote so the test can
284+
# check secfoo's numbers against the CLI's printed numbers.
285+
"usage_file": getattr(adapter, "last_usage_payload", None),
286+
}
287+
text = json.dumps(payload, indent=2, ensure_ascii=False) + "\n"
288+
assert_no_keys(text, where="the complete fixture")
289+
290+
fixture = ROOT / "tests" / "fixtures" / "agents" / args.agent / version_slug(version) / f"{args.scenario}.json"
291+
fixture.parent.mkdir(parents=True, exist_ok=True)
292+
fixture.write_text(text, encoding="utf-8")
293+
print(
294+
f"{args.agent}/{version_slug(version)}/{args.scenario}: status={result.status} "
295+
f"exit={result.exit_code} bytes={len(result.stdout)} saved={fixture.relative_to(ROOT)}"
296+
)
297+
return 0
298+
299+
300+
if __name__ == "__main__":
301+
raise SystemExit(main())

0 commit comments

Comments
 (0)