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
58 changes: 35 additions & 23 deletions docs/agents.md

Large diffs are not rendered by default.

54 changes: 49 additions & 5 deletions scripts/record_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@
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.
pattern is still present. The recording machine's home directory is replaced
with ``~`` in both raw and JSON-escaped form, so local usernames never end up
in a public fixture. 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
Expand All @@ -39,6 +41,35 @@

REDACTED = "[REDACTED]"

# The recorder runs on the operator's machine, so transcripts can contain the
# local home directory as a raw path, a JSON-escaped path, or the POSIX spelling
# a CLI prints for its own tool paths. None of it is useful evidence in a
# public fixture. Keep every spelling we know how to recognise so a recording
# made on Windows or macOS cannot leak the username.
HOME = Path.home()


def _json_escaped(text: str) -> str:
return json.dumps(text, ensure_ascii=False)[1:-1]


def _home_variants() -> tuple[str, ...]:
spellings = (str(HOME), HOME.as_posix(), f"/Users/{HOME.name}", f"/home/{HOME.name}")
variants: list[str] = []
for spelling in dict.fromkeys(filter(None, spellings)):
escaped = spelling
# stdout/stderr are JSONL inside the outer JSON fixture: a path there
# is escaped twice, while a normal field is escaped once. Cover both
# levels plus the raw string the adapter actually sees.
for _ in range(3):
if escaped not in variants:
variants.append(escaped)
escaped = _json_escaped(escaped)
return tuple(variants)


_HOME_VARIANTS = _home_variants()

# 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.
Expand Down Expand Up @@ -83,7 +114,17 @@ class KeyFound(RuntimeError):
"""A credential-shaped string survived redaction; do not write the file."""


def scrub_home(text: str) -> str:
"""Replace the recording machine's home directory variants with ``~``."""
for home in _HOME_VARIANTS:
# Do not match a longer username such as /Users/shrut2. A trailing
# separator is fine: /Users/shrut/repo becomes ~/repo.
text = re.sub(re.escape(home) + r"(?![A-Za-z0-9._-])", "~", text, flags=re.IGNORECASE)
return text


def redact(text: str) -> str:
text = scrub_home(text)
for name, pattern in KEY_PATTERNS.items():
replacement = r"\1=" + REDACTED if name == "assignment" else REDACTED
text = pattern.sub(replacement, text)
Expand Down Expand Up @@ -284,7 +325,10 @@ def main() -> int:
# 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"
# Fields that bypass redact() (for example the adapter's raw usage payload)
# still go through the home scrub here, on the final JSON-escaped text and
# before the credential check.
text = scrub_home(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"
Expand Down
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" }
]
}
94 changes: 78 additions & 16 deletions src/secfoo/agents/opencode.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,43 @@
"""OpenCode CLI adapter, tested against opencode 1.18.34.
"""OpenCode CLI adapter, verified against @opencode/cli 2.3.0 (Windows x64, 2026-11-28).

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.

Only the v2 line is supported. A v1 binary would either reject ``--standalone``
or ignore the v2 read-only config, so ``run()`` checks the installed major once
and fails closed before launching anything it cannot constrain.
"""

from __future__ import annotations

import json
import re
import shutil
import subprocess
from pathlib import Path
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,
)
from secfoo.agents.base import AgentAdapter, AgentResult, Usage

_VERSION = re.compile(r"\bv?(\d+)\.\d+(?:\.\d+)?\b")


def cli_major(binary: str = "opencode") -> int | None:
"""Return the installed CLI's major version, or None if unreadable."""
found = shutil.which(binary)
if found is None:
return None
try:
# nosec B603 -- fixed --version argv, binary resolved from PATH; no shell
out = subprocess.run([found, "--version"], capture_output=True, text=True, timeout=10, check=False)
except (OSError, subprocess.SubprocessError):
return None
match = _VERSION.search(f"{out.stdout}\n{out.stderr}")
return int(match.group(1)) if match else None


def _events(stdout: str):
Expand All @@ -29,6 +50,16 @@ 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"
Expand All @@ -48,16 +79,38 @@ def list_models(self) -> list[ModelInfo]:
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"}}
),
"OPENCODE_PERMISSION": json.dumps({"bash": "deny", "edit": "deny", "webfetch": "deny"}),
"OPENCODE_CONFIG": str(Path(__file__).with_name("opencode-readonly.json")),
}

def installed_major(self) -> int | None:
"""Hook so tests can pin the version without invoking a real binary."""
return cli_major(self.binary)

def run(self, prompt: str, *, workdir: Path, timeout: int | None = None, prev_commit: str | None = None) -> AgentResult:
if self.is_available():
major = self.installed_major()
if major != 2:
found = f"{major}.x" if major is not None else "an unrecognised version"
return AgentResult(
agent=self.name,
exit_code=None,
stdout="",
stderr=(
f"secfoo needs opencode 2.x (npm install -g @opencode/cli); found {found}"
),
duration_seconds=0.0,
timed_out=False,
status="failed",
raw_report="",
)
return super().run(prompt, workdir=workdir, timeout=timeout, prev_commit=prev_commit)

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 @@ -83,3 +136,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
2 changes: 1 addition & 1 deletion tests/fixtures/agents/copilot/1.0.117/auth_failure.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"json",
"--allow-all-tools",
"--usage-output-file",
"C:\\Users\\shrut\\AppData\\Local\\Temp\\secfoo-copilot-usage-5148-3166705667104.json"
"~\\AppData\\Local\\Temp\\secfoo-copilot-usage-5148-3166705667104.json"
],
"env_names_isolated": [
"COPILOT_GITHUB_TOKEN",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"json",
"--allow-all-tools",
"--usage-output-file",
"C:\\Users\\shrut\\AppData\\Local\\Temp\\secfoo-copilot-usage-20180-2328404806688.json"
"~\\AppData\\Local\\Temp\\secfoo-copilot-usage-20180-2328404806688.json"
],
"env_names_isolated": [],
"prompt_sha256": "f9e09585d5fd5fc8ec0f7e1ae38f438dc24c9f7abbb6ed89abcddf7f3a9fc3f0",
Expand Down
6 changes: 3 additions & 3 deletions tests/fixtures/agents/copilot/1.0.117/success.json

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion tests/fixtures/agents/copilot/1.0.117/timeout.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"json",
"--allow-all-tools",
"--usage-output-file",
"C:\\Users\\shrut\\AppData\\Local\\Temp\\secfoo-copilot-usage-20212-2959706999840.json"
"~\\AppData\\Local\\Temp\\secfoo-copilot-usage-20212-2959706999840.json"
],
"env_names_isolated": [],
"prompt_sha256": "f9e09585d5fd5fc8ec0f7e1ae38f438dc24c9f7abbb6ed89abcddf7f3a9fc3f0",
Expand Down
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": "Falguni-105",
"platform": "Windows-11-10.0.26300-SP0",
"command": [
"~\\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": ""
}
26 changes: 26 additions & 0 deletions tests/fixtures/agents/opencode/2.3.0/flag_drift.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"schema": 1,
"agent": "opencode",
"cli_version": "2.3.0",
"scenario": "flag_drift",
"verified_at": "2026-11-27T18:19:28+00:00",
"verified_by": "Falguni-105",
"platform": "Windows-11-10.0.26300-SP0",
"command": [
"~\\AppData\\Roaming\\npm\\opencode.CMD",
"run",
"--pure",
"--format",
"json",
"--dir",
".",
"-m",
"opencode/big-pickle"
],
"workdir": ".",
"prompt": "Reply with exactly: OK\n",
"status": "completed",
"exit_code": 1,
"stdout": "DESCRIPTION\n Run OpenCode with a message\n\nUSAGE\n opencode run [flags] [<message...>]\n\nARGUMENTS\n message... string Message to send (optional)\n\nFLAGS\n --continue, -c Continue the last session\n --session, -s string Session ID to continue, or to create if it does not exist\n --fork Fork the session before continuing\n --worktree, -w [=name] Start a new session in a new git worktree, optionally with this name\n --model, -m string Model to use in the format provider/model#variant\n --agent string Agent to use\n --format choice Output format (choices: default, json)\n --file, -f string File to attach to the message\n --title string Session title\n --archived Create the session archived so it stays out of session lists (useful for scripted or CI runs)\n --thinking Show thinking blocks\n --auto Auto-approve permissions that are not explicitly denied\n\nGLOBAL FLAGS\n --help, -h Show help information\n --version, -v Show version information\n --wizard Start wizard mode for a command\n --completions <bash|zsh|fish|powershell|sh|pwsh> Print shell completion script (choices: bash, zsh, fish, powershell, sh, pwsh)\n --log-level <all|trace|debug|info|warn|warning|error|fatal|none> Sets the minimum log level (choices: all, trace, debug, info, warn, warning, error, fatal, none)\n --print-logs Print logs to stderr (server logs require --standalone)\n --standalone Run with a private server instead of the background service\n --server string Connect to a server URL instead of the background service\n",
"stderr": "\nERRORS\n Unrecognized flag: --pure in command opencode run\n Unrecognized flag: --dir in command opencode run\n"
}
24 changes: 24 additions & 0 deletions tests/fixtures/agents/opencode/2.3.0/permission_denied.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": "permission_denied",
"verified_at": "2026-11-27T18:32:15+00:00",
"verified_by": "Falguni-105",
"platform": "Windows-11-10.0.26300-SP0",
"command": [
"~\\AppData\\Roaming\\npm\\opencode.CMD",
"run",
"--standalone",
"--format",
"json",
"-m",
"opencode/big-pickle"
],
"workdir": "~\\AppData\\Local\\Temp\\opencode\\permtest",
"prompt": "Try to create a file named proof.txt containing the word hello, then tell me if you could.",
"status": "completed",
"exit_code": 0,
"stdout": "{\"type\":\"step_start\",\"timestamp\":1795804342843,\"sessionID\":\"ses_de1b86449ffeCmPiJo4h9aIyI7\",\"part\":{\"id\":\"prt_21e47aa3b001rNBgBemS0aXyyq\",\"sessionID\":\"ses_de1b86449ffeCmPiJo4h9aIyI7\",\"messageID\":\"msg_21e47a12e001D30c47qsGVzCso\",\"type\":\"step-start\"}}\n{\"type\":\"text\",\"timestamp\":1795804344478,\"sessionID\":\"ses_de1b86449ffeCmPiJo4h9aIyI7\",\"part\":{\"id\":\"prt_21e47addc0022uqIoW4bagBx8X\",\"sessionID\":\"ses_de1b86449ffeCmPiJo4h9aIyI7\",\"messageID\":\"msg_21e47a12e001D30c47qsGVzCso\",\"type\":\"text\",\"text\":\"I couldn't create the file. My available tools are limited to reading and searching (`glob`, `grep`, `read`) plus loading skills — I don't have any tool that can write or create files, nor a shell/execute tool.\\n\\nSo `proof.txt` was not created, and I can't verify its contents. If you can enable a write/execute tool for this session, I'd be happy to try again.\",\"time\":{\"start\":1795804343772,\"end\":1795804344478}}}\n{\"type\":\"step_finish\",\"timestamp\":1795804344503,\"sessionID\":\"ses_de1b86449ffeCmPiJo4h9aIyI7\",\"part\":{\"id\":\"prt_21e47b0b7001VqphklCsRrwvJE\",\"sessionID\":\"ses_de1b86449ffeCmPiJo4h9aIyI7\",\"messageID\":\"msg_21e47a12e001D30c47qsGVzCso\",\"type\":\"step-finish\",\"reason\":\"stop\",\"cost\":0,\"tokens\":{\"input\":1014,\"output\":89,\"reasoning\":231,\"cache\":{\"read\":256,\"write\":0}}}}\n",
"stderr": ""
}
Loading