2020 lines
65 KiB
Python
2020 lines
65 KiB
Python
#!/usr/bin/env python3
|
|
"""Query OpenCode-hosted models over an OpenAI-compatible API and record SAST results.
|
|
|
|
The runner is intentionally dependency-free: it uses only the Python standard
|
|
library. It is designed for batch evaluation of the benchmark samples, with
|
|
resumable SQLite storage, CSV export, retries, JSON repair, and optional
|
|
comparison against the benchmark's expected-results file.
|
|
|
|
Typical use:
|
|
|
|
export OPENCODE_API_KEY="..."
|
|
python3 run_sast_eval.py \
|
|
--input Samples_Obfuscated_v2/BenchmarkTest00002.py \
|
|
--model deepseek-v4.1-flash
|
|
|
|
python3 run_sast_eval.py \
|
|
--input Samples_Obfuscated_v2 \
|
|
--model opencode-go/deepseek-v4.1-flash \
|
|
--run-id obfuscated-v2-deepseek
|
|
|
|
The model can be given as ``<id>`` (OpenCode Console), ``opencode/<id>``, or
|
|
``opencode-go/<id>``. The corresponding API base URL is selected
|
|
automatically; use ``--base-url`` for another OpenAI-compatible endpoint.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import csv
|
|
import getpass
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import random
|
|
import re
|
|
import socket
|
|
import sqlite3
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
import uuid
|
|
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
from dataclasses import dataclass
|
|
from datetime import datetime, timezone
|
|
from email.utils import parsedate_to_datetime
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
SCRIPT_VERSION = "1.1.0"
|
|
BASE_DIR = Path(__file__).resolve().parent
|
|
|
|
DEFAULT_PROMPT_PATH = BASE_DIR / "prompts" / "sast_v2.txt"
|
|
DEFAULT_EXPECTED_PATH = BASE_DIR / "data" / "expectedresults-0.1.csv"
|
|
FALLBACK_EXPECTED_PATH = BASE_DIR / "sample_expected.csv"
|
|
DEFAULT_DB_PATH = BASE_DIR / "results" / "sast_runs.sqlite3"
|
|
|
|
DEFAULT_CONSOLE_BASE_URL = "https://opencode.ai/inference/openai/v1"
|
|
DEFAULT_GO_BASE_URL = "https://opencode.ai/inference/go/openai/v1"
|
|
|
|
CODE_MARKER = "[INSERT_CODE_HERE]"
|
|
|
|
TARGET_CATEGORIES = frozenset(
|
|
{
|
|
"pathtraver",
|
|
"sqli",
|
|
"xpathi",
|
|
"xxe",
|
|
"cmdi",
|
|
"deserialization",
|
|
"xss",
|
|
"weakrand",
|
|
"trustbound",
|
|
"hash",
|
|
"codeinj",
|
|
"securecookie",
|
|
"redirect",
|
|
"ldapi",
|
|
}
|
|
)
|
|
|
|
# Canonical short category names used by the benchmark's expected-results file.
|
|
CATEGORY_ALIASES = {
|
|
"path traversal": "pathtraver",
|
|
"pathtraver": "pathtraver",
|
|
"sql injection": "sqli",
|
|
"sqli": "sqli",
|
|
"xpath injection": "xpathi",
|
|
"xpathi": "xpathi",
|
|
"xml external entity": "xxe",
|
|
"xml external entity xxe": "xxe",
|
|
"xxe": "xxe",
|
|
"command injection": "cmdi",
|
|
"cmdi": "cmdi",
|
|
"insecure deserialization": "deserialization",
|
|
"insecure deserialisation": "deserialization",
|
|
"deserialization": "deserialization",
|
|
"deserialisation": "deserialization",
|
|
"cross site scripting": "xss",
|
|
"cross site scripting xss": "xss",
|
|
"xss": "xss",
|
|
"weak randomness": "weakrand",
|
|
"weak random": "weakrand",
|
|
"insecure randomness": "weakrand",
|
|
"weakrand": "weakrand",
|
|
"trust boundary violation": "trustbound",
|
|
"trust boundary": "trustbound",
|
|
"trustbound": "trustbound",
|
|
"weak hash": "hash",
|
|
"weak hashing": "hash",
|
|
"insecure hash": "hash",
|
|
"hash": "hash",
|
|
"code injection": "codeinj",
|
|
"codeinj": "codeinj",
|
|
"insecure cookie": "securecookie",
|
|
"secure cookie": "securecookie",
|
|
"securecookie": "securecookie",
|
|
"open redirect": "redirect",
|
|
"redirect": "redirect",
|
|
"ldap injection": "ldapi",
|
|
"ldapi": "ldapi",
|
|
"none": "None",
|
|
"": "None",
|
|
}
|
|
|
|
CWE_TO_CATEGORY = {
|
|
22: "pathtraver",
|
|
89: "sqli",
|
|
643: "xpathi",
|
|
611: "xxe",
|
|
78: "cmdi",
|
|
502: "deserialization",
|
|
79: "xss",
|
|
330: "weakrand",
|
|
501: "trustbound",
|
|
328: "hash",
|
|
94: "codeinj",
|
|
614: "securecookie",
|
|
601: "redirect",
|
|
90: "ldapi",
|
|
# Some scanners report CWE-327 for weak hash; the benchmark uses CWE-328.
|
|
# Keep the category mapping so category scoring is still possible, while
|
|
# exact CWE scoring records the mismatch.
|
|
327: "hash",
|
|
}
|
|
|
|
CATEGORY_TO_CWE = {
|
|
"pathtraver": "CWE-22",
|
|
"sqli": "CWE-89",
|
|
"xpathi": "CWE-643",
|
|
"xxe": "CWE-611",
|
|
"cmdi": "CWE-78",
|
|
"deserialization": "CWE-502",
|
|
"xss": "CWE-79",
|
|
"weakrand": "CWE-330",
|
|
"trustbound": "CWE-501",
|
|
"hash": "CWE-328",
|
|
"codeinj": "CWE-94",
|
|
"securecookie": "CWE-614",
|
|
"redirect": "CWE-601",
|
|
"ldapi": "CWE-90",
|
|
}
|
|
|
|
RETRYABLE_HTTP_STATUS = {408, 425, 429, 500, 502, 503, 504}
|
|
FENCE_RE = re.compile(r"^\s*```(?:json)?\s*(.*?)\s*```\s*$", re.IGNORECASE | re.DOTALL)
|
|
TRAILING_COMMA_RE = re.compile(r",\s*([}\]])")
|
|
# JSON only allows a fixed set of backslash escapes. Some models emit
|
|
# Python-style escapes such as \' inside their reasoning strings.
|
|
INVALID_ESCAPE_RE = re.compile(r'\\(?!["\\/bfnrtu])')
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Utilities
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def now_iso() -> str:
|
|
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
|
|
|
|
|
def sha256_text(text: str) -> str:
|
|
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
|
|
|
|
|
def safe_filename(value: str) -> str:
|
|
cleaned = re.sub(r"[^A-Za-z0-9_.-]+", "_", value).strip("._")
|
|
return cleaned or "run"
|
|
|
|
|
|
def clean_words(value: Any) -> str:
|
|
"""Normalise a category-ish string for alias matching."""
|
|
if value is None:
|
|
return ""
|
|
text = str(value).strip().lower()
|
|
text = re.sub(r"\(?\bcwe[\s_-]*\d+\b\)?", " ", text)
|
|
text = text.replace("/", " ")
|
|
text = re.sub(r"[^a-z0-9]+", " ", text)
|
|
return re.sub(r"\s+", " ", text).strip()
|
|
|
|
|
|
def normalize_flag(value: Any) -> str | None:
|
|
if isinstance(value, bool):
|
|
return "Yes" if value else "No"
|
|
text = str(value or "").strip().lower()
|
|
if text in {"yes", "y", "true", "1", "vulnerable", "flagged"}:
|
|
return "Yes"
|
|
if text in {"no", "n", "false", "0", "not vulnerable", "none", "clean"}:
|
|
return "No"
|
|
return None
|
|
|
|
|
|
def normalize_cwe(value: Any) -> str:
|
|
if value is None:
|
|
return "None"
|
|
text = str(value).strip()
|
|
if not text or text.lower() in {"none", "n/a", "na", "null"}:
|
|
return "None"
|
|
match = re.search(r"(\d+)", text)
|
|
if match:
|
|
return f"CWE-{int(match.group(1))}"
|
|
return text
|
|
|
|
|
|
def normalize_category(value: Any) -> str:
|
|
raw = str(value or "")
|
|
cwe_match = re.search(r"\bcwe[\s_-]*(\d+)\b", raw, re.IGNORECASE)
|
|
if cwe_match:
|
|
mapped = CWE_TO_CATEGORY.get(int(cwe_match.group(1)))
|
|
if mapped:
|
|
return mapped
|
|
cleaned = clean_words(value)
|
|
if not cleaned:
|
|
return "None"
|
|
if cleaned in CATEGORY_ALIASES:
|
|
return CATEGORY_ALIASES[cleaned]
|
|
# Accept phrases such as "Path Traversal (CWE-22)" or
|
|
# "Cross-Site Scripting / XSS".
|
|
for alias, canonical in CATEGORY_ALIASES.items():
|
|
if alias and alias in cleaned:
|
|
return canonical
|
|
original = str(value or "").strip()
|
|
return original or "None"
|
|
|
|
|
|
def category_from_cwe(cwe: str) -> str | None:
|
|
match = re.search(r"(\d+)", cwe or "")
|
|
if not match:
|
|
return None
|
|
return CWE_TO_CATEGORY.get(int(match.group(1)))
|
|
|
|
|
|
def display_path(path: Path) -> str:
|
|
try:
|
|
return str(path.resolve().relative_to(Path.cwd().resolve()))
|
|
except ValueError:
|
|
return str(path.resolve())
|
|
|
|
|
|
def infer_condition(path: Path) -> str:
|
|
parent = path.parent.name.lower()
|
|
if "obfuscated" in parent:
|
|
return "obfuscated_v2" if ("v2" in parent or "2" in parent) else "obfuscated"
|
|
if parent in {"samples", "testcode", "testcode-0.1"} or "sample" in parent:
|
|
return "original"
|
|
return parent or "unknown"
|
|
|
|
|
|
def git_commit() -> str | None:
|
|
try:
|
|
result = subprocess.run(
|
|
["git", "rev-parse", "HEAD"],
|
|
cwd=BASE_DIR,
|
|
capture_output=True,
|
|
text=True,
|
|
check=False,
|
|
)
|
|
value = result.stdout.strip()
|
|
return value or None
|
|
except OSError:
|
|
return None
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Prompt, labels, inputs
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def load_prompt(path: Path) -> str:
|
|
if not path.is_file():
|
|
raise SystemExit(f"Prompt file not found: {path}")
|
|
text = path.read_text(encoding="utf-8")
|
|
if path.suffix.lower() == ".json":
|
|
try:
|
|
data = json.loads(text)
|
|
except json.JSONDecodeError as exc:
|
|
raise SystemExit(f"Invalid prompt JSON in {path}: {exc}") from exc
|
|
if not isinstance(data, dict) or not isinstance(data.get("prompt"), str):
|
|
raise SystemExit(
|
|
f"Prompt JSON in {path} must be an object with a string 'prompt' field"
|
|
)
|
|
text = data["prompt"]
|
|
if not text.strip():
|
|
raise SystemExit(f"Prompt file is empty: {path}")
|
|
return text
|
|
|
|
|
|
def build_messages(prompt_text: str, code: str, code_in: str) -> list[dict[str, str]]:
|
|
if CODE_MARKER in prompt_text:
|
|
if code_in == "user":
|
|
system = prompt_text.replace(
|
|
CODE_MARKER, "(provided in the user message below)"
|
|
)
|
|
user = (
|
|
"Code to analyze:\n\n"
|
|
f"{code}\n\n"
|
|
"Return only the JSON object matching the schema."
|
|
)
|
|
return [
|
|
{"role": "system", "content": system},
|
|
{"role": "user", "content": user},
|
|
]
|
|
system = prompt_text.replace(CODE_MARKER, code)
|
|
return [
|
|
{"role": "system", "content": system},
|
|
{
|
|
"role": "user",
|
|
"content": "Return only the JSON object matching the schema.",
|
|
},
|
|
]
|
|
|
|
if code_in == "user":
|
|
return [
|
|
{"role": "system", "content": prompt_text},
|
|
{
|
|
"role": "user",
|
|
"content": (
|
|
"Code to analyze:\n\n"
|
|
f"{code}\n\n"
|
|
"Return only the JSON object matching the schema."
|
|
),
|
|
},
|
|
]
|
|
|
|
return [
|
|
{
|
|
"role": "system",
|
|
"content": f"{prompt_text}\n\nCode to analyze:\n\n{code}",
|
|
},
|
|
{
|
|
"role": "user",
|
|
"content": "Return only the JSON object matching the schema.",
|
|
},
|
|
]
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ExpectedLabel:
|
|
vulnerable: str
|
|
category: str
|
|
cwe: str
|
|
|
|
@property
|
|
def in_target_scope(self) -> bool:
|
|
return self.category in TARGET_CATEGORIES
|
|
|
|
|
|
def load_expected(path: Path) -> dict[str, ExpectedLabel]:
|
|
labels: dict[str, ExpectedLabel] = {}
|
|
with path.open("r", encoding="utf-8", newline="") as handle:
|
|
for row in csv.reader(handle):
|
|
if not row or not row[0].strip() or row[0].lstrip().startswith("#"):
|
|
continue
|
|
name = row[0].strip()
|
|
category = normalize_category(row[1] if len(row) > 1 else "None")
|
|
raw_vulnerable = row[2].strip().lower() if len(row) > 2 else ""
|
|
vulnerable = "Yes" if raw_vulnerable in {"true", "1", "yes"} else "No"
|
|
cwe = normalize_cwe(row[3] if len(row) > 3 else "None")
|
|
labels[name] = ExpectedLabel(vulnerable, category, cwe)
|
|
return labels
|
|
|
|
|
|
def pick_expected_path(explicit: Path | None) -> Path | None:
|
|
if explicit is not None:
|
|
if not explicit.is_file():
|
|
raise SystemExit(f"Expected-results CSV not found: {explicit}")
|
|
return explicit
|
|
for candidate in (DEFAULT_EXPECTED_PATH, FALLBACK_EXPECTED_PATH):
|
|
if candidate.is_file():
|
|
return candidate
|
|
return None
|
|
|
|
|
|
def expand_inputs(spec: str, pattern: str) -> list[Path]:
|
|
path = Path(spec).expanduser()
|
|
files: list[Path] = []
|
|
|
|
if path.is_file():
|
|
files = [path]
|
|
elif path.is_dir():
|
|
files = sorted(path.rglob(pattern))
|
|
else:
|
|
import glob
|
|
|
|
files = [Path(item) for item in glob.glob(str(path), recursive=True)]
|
|
files = sorted(item for item in files if item.is_file())
|
|
|
|
# Deduplicate while preserving deterministic order.
|
|
unique: dict[str, Path] = {}
|
|
for item in files:
|
|
unique[str(item.resolve())] = item
|
|
result = list(unique.values())
|
|
if not result:
|
|
raise SystemExit(f"No input files matched: {spec!r} (pattern {pattern!r})")
|
|
return result
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# API response handling
|
|
# ---------------------------------------------------------------------------
|
|
|
|
@dataclass
|
|
class HttpResponse:
|
|
status: int | None
|
|
body: str
|
|
headers: dict[str, str]
|
|
error: str | None
|
|
retryable: bool
|
|
retry_after: float | None
|
|
|
|
|
|
def _error_message(status: int, body: str) -> str:
|
|
text = (body or "").strip()
|
|
message = ""
|
|
if text:
|
|
try:
|
|
payload = json.loads(text)
|
|
except json.JSONDecodeError:
|
|
payload = None
|
|
if isinstance(payload, dict):
|
|
error = payload.get("error")
|
|
if isinstance(error, dict):
|
|
message = str(error.get("message") or error.get("type") or "")
|
|
elif error is not None:
|
|
message = str(error)
|
|
if not message:
|
|
message = str(payload.get("message") or "")
|
|
if not message:
|
|
message = text[:1200]
|
|
return f"HTTP {status}: {message}" if message else f"HTTP {status}"
|
|
|
|
|
|
def _retry_after(headers: dict[str, str]) -> float | None:
|
|
value = headers.get("retry-after")
|
|
if not value:
|
|
return None
|
|
try:
|
|
return max(0.0, float(value))
|
|
except ValueError:
|
|
try:
|
|
when = parsedate_to_datetime(value)
|
|
if when.tzinfo is None:
|
|
when = when.replace(tzinfo=timezone.utc)
|
|
return max(0.0, (when - datetime.now(timezone.utc)).total_seconds())
|
|
except (TypeError, ValueError):
|
|
return None
|
|
|
|
|
|
def http_post_json(
|
|
url: str, headers: dict[str, str], payload: dict[str, Any], timeout: float
|
|
) -> HttpResponse:
|
|
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
|
request = urllib.request.Request(url, data=data, headers=headers, method="POST")
|
|
try:
|
|
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
body = response.read().decode("utf-8", "replace")
|
|
response_headers = {
|
|
key.lower(): value for key, value in response.headers.items()
|
|
}
|
|
return HttpResponse(
|
|
status=response.status,
|
|
body=body,
|
|
headers=response_headers,
|
|
error=None,
|
|
retryable=False,
|
|
retry_after=None,
|
|
)
|
|
except urllib.error.HTTPError as exc:
|
|
body = exc.read().decode("utf-8", "replace")
|
|
response_headers = (
|
|
{key.lower(): value for key, value in exc.headers.items()}
|
|
if exc.headers
|
|
else {}
|
|
)
|
|
return HttpResponse(
|
|
status=exc.code,
|
|
body=body,
|
|
headers=response_headers,
|
|
error=_error_message(exc.code, body),
|
|
retryable=exc.code in RETRYABLE_HTTP_STATUS,
|
|
retry_after=_retry_after(response_headers),
|
|
)
|
|
except (urllib.error.URLError, TimeoutError, socket.timeout, OSError) as exc:
|
|
return HttpResponse(
|
|
status=None,
|
|
body="",
|
|
headers={},
|
|
error=f"{type(exc).__name__}: {exc}",
|
|
retryable=True,
|
|
retry_after=None,
|
|
)
|
|
|
|
|
|
def http_get_json(
|
|
url: str, headers: dict[str, str], timeout: float
|
|
) -> tuple[Any | None, str | None]:
|
|
request = urllib.request.Request(url, headers=headers, method="GET")
|
|
try:
|
|
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
body = response.read().decode("utf-8", "replace")
|
|
return json.loads(body), None
|
|
except urllib.error.HTTPError as exc:
|
|
body = exc.read().decode("utf-8", "replace")
|
|
return None, _error_message(exc.code, body)
|
|
except (urllib.error.URLError, TimeoutError, socket.timeout, OSError) as exc:
|
|
return None, f"{type(exc).__name__}: {exc}"
|
|
except json.JSONDecodeError as exc:
|
|
return None, f"Invalid JSON from {url}: {exc}"
|
|
|
|
|
|
def extract_message(data: Any) -> tuple[str | None, str | None, str | None]:
|
|
if not isinstance(data, dict):
|
|
return None, None, None
|
|
choices = data.get("choices")
|
|
if not isinstance(choices, list) or not choices:
|
|
return None, None, None
|
|
choice = choices[0]
|
|
if not isinstance(choice, dict):
|
|
return None, None, None
|
|
|
|
message = choice.get("message")
|
|
if not isinstance(message, dict):
|
|
message = {}
|
|
content = message.get("content")
|
|
if content is None:
|
|
content = choice.get("text")
|
|
|
|
text: str | None
|
|
if isinstance(content, str):
|
|
text = content
|
|
elif isinstance(content, list):
|
|
parts: list[str] = []
|
|
for part in content:
|
|
if isinstance(part, str):
|
|
parts.append(part)
|
|
elif isinstance(part, dict):
|
|
piece = part.get("text") or part.get("content")
|
|
if isinstance(piece, str):
|
|
parts.append(piece)
|
|
text = "".join(parts) if parts else None
|
|
else:
|
|
text = None
|
|
|
|
reasoning = (
|
|
message.get("reasoning_content")
|
|
or message.get("reasoning")
|
|
or message.get("reasoning_text")
|
|
)
|
|
if not isinstance(reasoning, str):
|
|
reasoning = None
|
|
|
|
# Some gateways put the usable answer only in the reasoning channel.
|
|
if not text and reasoning:
|
|
text = reasoning
|
|
|
|
finish = choice.get("finish_reason")
|
|
if not isinstance(finish, str):
|
|
finish = None
|
|
return text, reasoning, finish
|
|
|
|
|
|
def _token_value(usage: dict[str, Any], *keys: str) -> int | None:
|
|
for key in keys:
|
|
value = usage.get(key)
|
|
if isinstance(value, (int, float)):
|
|
return int(value)
|
|
return None
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# JSON extraction and result normalisation
|
|
# ---------------------------------------------------------------------------
|
|
|
|
@dataclass
|
|
class ParsedResult:
|
|
ok: bool
|
|
obj: dict[str, Any] | None = None
|
|
flagged: str | None = None
|
|
category_raw: str | None = None
|
|
category: str | None = None
|
|
cwe_raw: str | None = None
|
|
cwe: str | None = None
|
|
reasoning: str | None = None
|
|
error: str | None = None
|
|
|
|
|
|
def _balanced_object(text: str) -> dict[str, Any] | None:
|
|
start = text.find("{")
|
|
while start != -1:
|
|
depth = 0
|
|
in_string = False
|
|
escaped = False
|
|
for index in range(start, len(text)):
|
|
char = text[index]
|
|
if in_string:
|
|
if escaped:
|
|
escaped = False
|
|
elif char == "\\":
|
|
escaped = True
|
|
elif char == '"':
|
|
in_string = False
|
|
continue
|
|
if char == '"':
|
|
in_string = True
|
|
elif char == "{":
|
|
depth += 1
|
|
elif char == "}":
|
|
depth -= 1
|
|
if depth == 0:
|
|
candidate = text[start : index + 1]
|
|
without_trailing_comma = TRAILING_COMMA_RE.sub(r"\1", candidate)
|
|
for attempt in (
|
|
candidate,
|
|
without_trailing_comma,
|
|
INVALID_ESCAPE_RE.sub("", candidate),
|
|
INVALID_ESCAPE_RE.sub("", without_trailing_comma),
|
|
):
|
|
try:
|
|
parsed = json.loads(attempt)
|
|
except json.JSONDecodeError:
|
|
continue
|
|
if isinstance(parsed, dict):
|
|
return parsed
|
|
break
|
|
start = text.find("{", start + 1)
|
|
return None
|
|
|
|
|
|
def extract_json_object(text: str | None) -> dict[str, Any] | None:
|
|
if not text:
|
|
return None
|
|
cleaned = text.strip().lstrip("\ufeff")
|
|
fence = FENCE_RE.match(cleaned)
|
|
if fence:
|
|
cleaned = fence.group(1).strip()
|
|
try:
|
|
parsed = json.loads(cleaned)
|
|
if isinstance(parsed, dict):
|
|
return parsed
|
|
except json.JSONDecodeError:
|
|
pass
|
|
return _balanced_object(cleaned)
|
|
|
|
|
|
def parse_result(text: str | None) -> ParsedResult:
|
|
obj = extract_json_object(text)
|
|
if obj is None:
|
|
return ParsedResult(ok=False, error="response is not a valid JSON object")
|
|
|
|
# v2 prompts ask for {"vulnerable": true/false, "cwe": "CWE-..."}.
|
|
# Keep accepting the v1 "flagged"/"category" schema for old runs.
|
|
flag_value = obj.get("vulnerable")
|
|
if flag_value is None:
|
|
flag_value = obj.get("flagged")
|
|
flagged = normalize_flag(flag_value)
|
|
if flagged is None:
|
|
return ParsedResult(
|
|
ok=False,
|
|
obj=obj,
|
|
error="JSON object has no valid 'vulnerable' or 'flagged' value",
|
|
)
|
|
|
|
category_raw_value = obj.get("category")
|
|
cwe_raw_value = obj.get("cwe")
|
|
category_raw = str(category_raw_value).strip() if category_raw_value is not None else "None"
|
|
cwe_raw = str(cwe_raw_value).strip() if cwe_raw_value is not None else "None"
|
|
|
|
cwe = normalize_cwe(cwe_raw)
|
|
if flagged == "Yes":
|
|
# CWE is the canonical label in v2; the category is derived from it.
|
|
# Fall back to the category field, then derive a CWE if necessary.
|
|
cwe_category = category_from_cwe(cwe)
|
|
if cwe_category is not None:
|
|
category = cwe_category
|
|
else:
|
|
category = normalize_category(category_raw)
|
|
if cwe == "None":
|
|
cwe = CATEGORY_TO_CWE.get(category, "None")
|
|
else:
|
|
category = "None"
|
|
cwe = "None"
|
|
|
|
reasoning_value = obj.get("reasoning")
|
|
reasoning = str(reasoning_value) if reasoning_value is not None else None
|
|
|
|
return ParsedResult(
|
|
ok=True,
|
|
obj=obj,
|
|
flagged=flagged,
|
|
category_raw=category_raw,
|
|
category=category,
|
|
cwe_raw=cwe_raw,
|
|
cwe=cwe,
|
|
reasoning=reasoning,
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Attempts and HTTP calls
|
|
# ---------------------------------------------------------------------------
|
|
|
|
@dataclass
|
|
class Attempt:
|
|
call_index: int
|
|
phase: str
|
|
created_at: str
|
|
latency_ms: int = 0
|
|
http_status: int | None = None
|
|
finish_reason: str | None = None
|
|
prompt_tokens: int | None = None
|
|
completion_tokens: int | None = None
|
|
total_tokens: int | None = None
|
|
response_text: str | None = None
|
|
reasoning_text: str | None = None
|
|
parsed_json: str | None = None
|
|
flagged: str | None = None
|
|
category_raw: str | None = None
|
|
category: str | None = None
|
|
cwe_raw: str | None = None
|
|
cwe: str | None = None
|
|
parse_ok: int = 0
|
|
error: str | None = None
|
|
|
|
|
|
def apply_parsed(attempt: Attempt, parsed: ParsedResult) -> None:
|
|
attempt.parse_ok = 1 if parsed.ok else 0
|
|
if parsed.ok:
|
|
attempt.error = None
|
|
elif not attempt.error:
|
|
attempt.error = parsed.error
|
|
if parsed.obj is not None:
|
|
attempt.parsed_json = json.dumps(parsed.obj, ensure_ascii=False)
|
|
attempt.flagged = parsed.flagged
|
|
attempt.category_raw = parsed.category_raw
|
|
attempt.category = parsed.category
|
|
attempt.cwe_raw = parsed.cwe_raw
|
|
attempt.cwe = parsed.cwe
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Database
|
|
# ---------------------------------------------------------------------------
|
|
|
|
SCHEMA = """
|
|
CREATE TABLE IF NOT EXISTS run_meta (
|
|
run_id TEXT PRIMARY KEY,
|
|
started_at TEXT NOT NULL,
|
|
finished_at TEXT,
|
|
model TEXT NOT NULL,
|
|
base_url TEXT NOT NULL,
|
|
prompt_hash TEXT NOT NULL,
|
|
prompt_name TEXT,
|
|
temperature REAL,
|
|
condition TEXT,
|
|
input_spec TEXT,
|
|
expected_csv TEXT,
|
|
git_commit TEXT,
|
|
script_version TEXT NOT NULL,
|
|
arguments_json TEXT
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS prompts (
|
|
prompt_hash TEXT PRIMARY KEY,
|
|
prompt_name TEXT,
|
|
prompt_text TEXT NOT NULL,
|
|
created_at TEXT NOT NULL
|
|
);
|
|
|
|
CREATE TABLE IF NOT EXISTS attempts (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
run_id TEXT NOT NULL,
|
|
sample_path TEXT NOT NULL,
|
|
sample_name TEXT NOT NULL,
|
|
condition TEXT,
|
|
code_sha256 TEXT NOT NULL,
|
|
call_index INTEGER NOT NULL,
|
|
phase TEXT NOT NULL,
|
|
created_at TEXT NOT NULL,
|
|
latency_ms INTEGER,
|
|
http_status INTEGER,
|
|
finish_reason TEXT,
|
|
prompt_tokens INTEGER,
|
|
completion_tokens INTEGER,
|
|
total_tokens INTEGER,
|
|
response_text TEXT,
|
|
reasoning_text TEXT,
|
|
parsed_json TEXT,
|
|
flagged TEXT,
|
|
category_raw TEXT,
|
|
category TEXT,
|
|
cwe_raw TEXT,
|
|
cwe TEXT,
|
|
parse_ok INTEGER NOT NULL DEFAULT 0,
|
|
error TEXT,
|
|
expected_vulnerable TEXT,
|
|
expected_category TEXT,
|
|
expected_cwe TEXT,
|
|
in_target_scope INTEGER,
|
|
UNIQUE(run_id, sample_path, call_index),
|
|
FOREIGN KEY(run_id) REFERENCES run_meta(run_id)
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_attempts_run_sample
|
|
ON attempts(run_id, sample_path);
|
|
CREATE INDEX IF NOT EXISTS idx_attempts_run_name
|
|
ON attempts(run_id, sample_name);
|
|
"""
|
|
|
|
|
|
def open_db(path: Path) -> sqlite3.Connection:
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
connection = sqlite3.connect(path, timeout=30)
|
|
connection.row_factory = sqlite3.Row
|
|
connection.execute("PRAGMA journal_mode=WAL")
|
|
connection.execute("PRAGMA foreign_keys=ON")
|
|
connection.execute("PRAGMA busy_timeout=30000")
|
|
connection.executescript(SCHEMA)
|
|
connection.commit()
|
|
return connection
|
|
|
|
|
|
def store_prompt(
|
|
connection: sqlite3.Connection, prompt_name: str, prompt_text: str, prompt_hash: str
|
|
) -> None:
|
|
connection.execute(
|
|
"""
|
|
INSERT OR IGNORE INTO prompts(prompt_hash, prompt_name, prompt_text, created_at)
|
|
VALUES (?, ?, ?, ?)
|
|
""",
|
|
(prompt_hash, prompt_name, prompt_text, now_iso()),
|
|
)
|
|
|
|
|
|
def prepare_run(
|
|
connection: sqlite3.Connection,
|
|
*,
|
|
run_id: str,
|
|
args: argparse.Namespace,
|
|
model: str,
|
|
base_url: str,
|
|
prompt_name: str,
|
|
prompt_hash: str,
|
|
expected_path: Path | None,
|
|
) -> bool:
|
|
row = connection.execute(
|
|
"SELECT * FROM run_meta WHERE run_id = ?", (run_id,)
|
|
).fetchone()
|
|
if row is not None:
|
|
if not args.resume:
|
|
raise SystemExit(
|
|
f"Run ID {run_id!r} already exists. Use --resume or choose a new --run-id."
|
|
)
|
|
mismatches = []
|
|
if row["model"] != model:
|
|
mismatches.append(f"model {row['model']!r} != {model!r}")
|
|
if row["base_url"] != base_url:
|
|
mismatches.append(f"base_url {row['base_url']!r} != {base_url!r}")
|
|
if row["prompt_hash"] != prompt_hash:
|
|
mismatches.append("prompt hash differs")
|
|
if mismatches:
|
|
raise SystemExit(
|
|
"Cannot resume with different settings: " + "; ".join(mismatches)
|
|
)
|
|
return False
|
|
|
|
safe_args = {
|
|
key: (str(value) if isinstance(value, Path) else value)
|
|
for key, value in vars(args).items()
|
|
if key != "api_key"
|
|
}
|
|
connection.execute(
|
|
"""
|
|
INSERT INTO run_meta(
|
|
run_id, started_at, model, base_url, prompt_hash, prompt_name,
|
|
temperature, condition, input_spec, expected_csv, git_commit,
|
|
script_version, arguments_json
|
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
""",
|
|
(
|
|
run_id,
|
|
now_iso(),
|
|
model,
|
|
base_url,
|
|
prompt_hash,
|
|
prompt_name,
|
|
args.temperature if not args.no_temperature else None,
|
|
args.condition or "auto",
|
|
str(args.input),
|
|
str(expected_path) if expected_path else None,
|
|
git_commit(),
|
|
SCRIPT_VERSION,
|
|
json.dumps(safe_args, default=str, sort_keys=True),
|
|
),
|
|
)
|
|
connection.commit()
|
|
return True
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Job execution
|
|
# ---------------------------------------------------------------------------
|
|
|
|
@dataclass
|
|
class Job:
|
|
path: Path
|
|
display: str
|
|
name: str
|
|
condition: str
|
|
expected: ExpectedLabel | None
|
|
start_call_index: int = 1
|
|
|
|
|
|
class Runner:
|
|
def __init__(
|
|
self,
|
|
*,
|
|
args: argparse.Namespace,
|
|
prompt_text: str,
|
|
model: str,
|
|
base_url: str,
|
|
api_key: str,
|
|
run_id: str,
|
|
):
|
|
self.args = args
|
|
self.prompt_text = prompt_text
|
|
self.model = model
|
|
self.base_url = base_url
|
|
self.chat_url = base_url.rstrip("/") + "/chat/completions"
|
|
self.api_key = api_key
|
|
self.run_id = run_id
|
|
self.session_id = re.sub(r"[^A-Za-z0-9_.-]", "-", run_id)
|
|
|
|
def _headers(self, session_id: str) -> dict[str, str]:
|
|
return {
|
|
"Authorization": f"Bearer {self.api_key}",
|
|
"Content-Type": "application/json",
|
|
"Accept": "application/json",
|
|
"User-Agent": "JU-ResearchMethods-SAST-Eval/1.0",
|
|
"x-opencode-session": session_id,
|
|
}
|
|
|
|
def _call_chat(
|
|
self,
|
|
messages: list[dict[str, str]],
|
|
*,
|
|
phase: str,
|
|
start_call_index: int,
|
|
session_id: str,
|
|
) -> list[Attempt]:
|
|
payload: dict[str, Any] = {
|
|
"model": self.model,
|
|
"messages": messages,
|
|
"stream": False,
|
|
}
|
|
if self.args.temperature is not None and not self.args.no_temperature:
|
|
payload["temperature"] = self.args.temperature
|
|
if self.args.max_tokens is not None:
|
|
payload["max_tokens"] = self.args.max_tokens
|
|
if getattr(self.args, "no_reasoning", False):
|
|
# OpenRouter supports this unified switch for reasoning models.
|
|
# Other OpenAI-compatible providers generally ignore unknown fields.
|
|
payload["reasoning"] = {"enabled": False}
|
|
|
|
attempts: list[Attempt] = []
|
|
call_index = start_call_index
|
|
retries = 0
|
|
total_calls = 0
|
|
while True:
|
|
total_calls += 1
|
|
started = time.monotonic()
|
|
response = http_post_json(
|
|
self.chat_url, self._headers(session_id), payload, self.args.timeout
|
|
)
|
|
latency = int((time.monotonic() - started) * 1000)
|
|
attempt = Attempt(
|
|
call_index=call_index,
|
|
phase=phase,
|
|
created_at=now_iso(),
|
|
latency_ms=latency,
|
|
http_status=response.status,
|
|
error=response.error,
|
|
)
|
|
|
|
if response.status == 200 and response.body:
|
|
try:
|
|
data = json.loads(response.body)
|
|
except json.JSONDecodeError as exc:
|
|
attempt.error = f"Invalid JSON response: {exc}"
|
|
else:
|
|
text, reasoning, finish = extract_message(data)
|
|
attempt.finish_reason = finish
|
|
attempt.response_text = text
|
|
attempt.reasoning_text = reasoning
|
|
usage = data.get("usage")
|
|
if isinstance(usage, dict):
|
|
attempt.prompt_tokens = _token_value(
|
|
usage, "prompt_tokens", "input_tokens"
|
|
)
|
|
attempt.completion_tokens = _token_value(
|
|
usage, "completion_tokens", "output_tokens"
|
|
)
|
|
attempt.total_tokens = _token_value(usage, "total_tokens")
|
|
if attempt.total_tokens is None and (
|
|
attempt.prompt_tokens is not None
|
|
or attempt.completion_tokens is not None
|
|
):
|
|
attempt.total_tokens = (
|
|
(attempt.prompt_tokens or 0)
|
|
+ (attempt.completion_tokens or 0)
|
|
)
|
|
if not text:
|
|
attempt.error = "Response contained no assistant text"
|
|
elif isinstance(data, dict) and data.get("error"):
|
|
attempt.error = str(data["error"])
|
|
elif response.status == 200:
|
|
attempt.error = "Empty HTTP response"
|
|
|
|
attempts.append(attempt)
|
|
call_index += 1
|
|
|
|
# Some reasoning models reject the temperature parameter. Retry
|
|
# once without it rather than failing the whole sample.
|
|
error_lower = (response.error or "").lower()
|
|
if (
|
|
response.status in {400, 422}
|
|
and "temperature" in payload
|
|
and "temperature" in error_lower
|
|
):
|
|
payload.pop("temperature", None)
|
|
if total_calls < self.args.max_retries + 3:
|
|
continue
|
|
break
|
|
|
|
if not response.retryable or retries >= self.args.max_retries:
|
|
break
|
|
|
|
retries += 1
|
|
delay = min(60.0, 2.0 ** (retries - 1)) + random.uniform(0.0, 0.5)
|
|
if response.retry_after is not None:
|
|
delay = max(delay, min(120.0, response.retry_after))
|
|
time.sleep(delay)
|
|
|
|
return attempts
|
|
|
|
def process(self, job: Job) -> list[Attempt]:
|
|
try:
|
|
code = job.path.read_text(encoding="utf-8")
|
|
except (OSError, UnicodeError) as exc:
|
|
return [
|
|
Attempt(
|
|
call_index=job.start_call_index,
|
|
phase="initial",
|
|
created_at=now_iso(),
|
|
error=f"Could not read sample: {type(exc).__name__}: {exc}",
|
|
)
|
|
]
|
|
|
|
messages = build_messages(self.prompt_text, code, self.args.code_in)
|
|
attempts: list[Attempt] = []
|
|
next_index = job.start_call_index
|
|
session_id = f"{self.session_id}-{job.name}"[:200]
|
|
|
|
def run_phase(phase: str, phase_messages: list[dict[str, str]]) -> None:
|
|
nonlocal next_index
|
|
records = self._call_chat(
|
|
phase_messages,
|
|
phase=phase,
|
|
start_call_index=next_index,
|
|
session_id=session_id,
|
|
)
|
|
for record in records:
|
|
apply_parsed(record, parse_result(record.response_text))
|
|
attempts.extend(records)
|
|
next_index += len(records)
|
|
|
|
run_phase("initial", messages)
|
|
if not attempts:
|
|
return [
|
|
Attempt(
|
|
call_index=next_index,
|
|
phase="initial",
|
|
created_at=now_iso(),
|
|
error="No attempt was made",
|
|
)
|
|
]
|
|
|
|
last = attempts[-1]
|
|
parsed = parse_result(last.response_text)
|
|
raw = last.response_text
|
|
repairs = 0
|
|
while not parsed.ok and raw and repairs < self.args.repair_attempts:
|
|
repair_messages = messages + [
|
|
{"role": "assistant", "content": raw},
|
|
{
|
|
"role": "user",
|
|
"content": (
|
|
"Your previous response was not valid JSON. "
|
|
"Return ONLY a valid JSON object matching the schema. "
|
|
"No markdown fences, no explanation, no extra text."
|
|
),
|
|
},
|
|
]
|
|
run_phase("repair", repair_messages)
|
|
last = attempts[-1]
|
|
parsed = parse_result(last.response_text)
|
|
raw = last.response_text
|
|
repairs += 1
|
|
|
|
return attempts
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Persistence and reporting
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def insert_attempt(
|
|
connection: sqlite3.Connection,
|
|
run_id: str,
|
|
job: Job,
|
|
code_sha256: str,
|
|
attempt: Attempt,
|
|
) -> None:
|
|
expected = job.expected
|
|
connection.execute(
|
|
"""
|
|
INSERT INTO attempts(
|
|
run_id, sample_path, sample_name, condition, code_sha256,
|
|
call_index, phase, created_at, latency_ms, http_status,
|
|
finish_reason, prompt_tokens, completion_tokens, total_tokens,
|
|
response_text, reasoning_text, parsed_json, flagged,
|
|
category_raw, category, cwe_raw, cwe, parse_ok, error,
|
|
expected_vulnerable, expected_category, expected_cwe,
|
|
in_target_scope
|
|
) VALUES (
|
|
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
|
|
?, ?, ?, ?, ?, ?
|
|
)
|
|
""",
|
|
(
|
|
run_id,
|
|
job.display,
|
|
job.name,
|
|
job.condition,
|
|
code_sha256,
|
|
attempt.call_index,
|
|
attempt.phase,
|
|
attempt.created_at,
|
|
attempt.latency_ms,
|
|
attempt.http_status,
|
|
attempt.finish_reason,
|
|
attempt.prompt_tokens,
|
|
attempt.completion_tokens,
|
|
attempt.total_tokens,
|
|
attempt.response_text,
|
|
attempt.reasoning_text,
|
|
attempt.parsed_json,
|
|
attempt.flagged,
|
|
attempt.category_raw,
|
|
attempt.category,
|
|
attempt.cwe_raw,
|
|
attempt.cwe,
|
|
attempt.parse_ok,
|
|
attempt.error,
|
|
expected.vulnerable if expected else None,
|
|
expected.category if expected else None,
|
|
expected.cwe if expected else None,
|
|
1 if expected and expected.in_target_scope else (0 if expected else None),
|
|
),
|
|
)
|
|
|
|
|
|
def completed_samples(connection: sqlite3.Connection, run_id: str) -> set[str]:
|
|
rows = connection.execute(
|
|
"""
|
|
SELECT DISTINCT sample_path FROM attempts
|
|
WHERE run_id = ? AND parse_ok = 1
|
|
""",
|
|
(run_id,),
|
|
).fetchall()
|
|
return {row["sample_path"] for row in rows}
|
|
|
|
|
|
def max_call_index(
|
|
connection: sqlite3.Connection, run_id: str, sample_path: str
|
|
) -> int:
|
|
row = connection.execute(
|
|
"""
|
|
SELECT COALESCE(MAX(call_index), 0) AS max_index FROM attempts
|
|
WHERE run_id = ? AND sample_path = ?
|
|
""",
|
|
(run_id, sample_path),
|
|
).fetchone()
|
|
return int(row["max_index"] or 0)
|
|
|
|
|
|
def latest_rows(connection: sqlite3.Connection, run_id: str) -> list[sqlite3.Row]:
|
|
return connection.execute(
|
|
"""
|
|
SELECT a.*
|
|
FROM attempts a
|
|
JOIN (
|
|
SELECT sample_path, MAX(call_index) AS max_index
|
|
FROM attempts
|
|
WHERE run_id = ?
|
|
GROUP BY sample_path
|
|
) latest
|
|
ON latest.sample_path = a.sample_path
|
|
AND latest.max_index = a.call_index
|
|
WHERE a.run_id = ?
|
|
ORDER BY a.sample_name
|
|
""",
|
|
(run_id, run_id),
|
|
).fetchall()
|
|
|
|
|
|
def print_summary(connection: sqlite3.Connection, run_id: str) -> None:
|
|
rows = latest_rows(connection, run_id)
|
|
total = len(rows)
|
|
parsed = sum(1 for row in rows if row["parse_ok"])
|
|
failed = total - parsed
|
|
|
|
meta = connection.execute(
|
|
"SELECT model, prompt_name, expected_csv FROM run_meta WHERE run_id = ?",
|
|
(run_id,),
|
|
).fetchone()
|
|
print()
|
|
print(f"Run: {run_id}")
|
|
if meta is not None:
|
|
print(
|
|
f"Model: {meta['model']} | Prompt: {meta['prompt_name']} | "
|
|
f"Labels: {meta['expected_csv'] or 'none'}"
|
|
)
|
|
print(f"Samples: {total} (parsed {parsed}, failed {failed})")
|
|
|
|
labelled = [row for row in rows if row["expected_vulnerable"] is not None]
|
|
in_scope = [row for row in labelled if row["in_target_scope"] == 1]
|
|
out_scope = [row for row in labelled if row["in_target_scope"] == 0]
|
|
print(
|
|
f"Expected labels: {len(labelled)} matched; "
|
|
f"in-scope {len(in_scope)}, out-of-scope {len(out_scope)}"
|
|
)
|
|
|
|
evaluable = [
|
|
row
|
|
for row in in_scope
|
|
if row["parse_ok"] and row["expected_vulnerable"] in {"Yes", "No"}
|
|
]
|
|
if evaluable:
|
|
tp = fp = tn = fn = 0
|
|
category_correct = 0
|
|
cwe_correct = 0
|
|
strict_correct = 0
|
|
wrong_category_tp = 0
|
|
for row in evaluable:
|
|
expected_positive = row["expected_vulnerable"] == "Yes"
|
|
predicted_positive = row["flagged"] == "Yes"
|
|
category_ok = row["category"] == row["expected_category"]
|
|
cwe_ok = row["cwe"] == row["expected_cwe"]
|
|
if expected_positive and predicted_positive:
|
|
tp += 1
|
|
if category_ok:
|
|
category_correct += 1
|
|
else:
|
|
wrong_category_tp += 1
|
|
if cwe_ok:
|
|
cwe_correct += 1
|
|
elif expected_positive:
|
|
fn += 1
|
|
elif predicted_positive:
|
|
fp += 1
|
|
else:
|
|
tn += 1
|
|
if expected_positive == predicted_positive and (
|
|
not expected_positive or cwe_ok
|
|
):
|
|
strict_correct += 1
|
|
count = tp + fp + tn + fn
|
|
accuracy = (tp + tn) / count if count else 0.0
|
|
strict_accuracy = strict_correct / count if count else 0.0
|
|
precision = tp / (tp + fp) if tp + fp else 0.0
|
|
recall = tp / (tp + fn) if tp + fn else 0.0
|
|
cat_accuracy = category_correct / tp if tp else 0.0
|
|
cwe_accuracy = cwe_correct / tp if tp else 0.0
|
|
print(
|
|
"In-scope confusion: "
|
|
f"TP={tp} FP={fp} TN={tn} FN={fn}"
|
|
)
|
|
print(
|
|
f"Flag accuracy: {accuracy:.3f} ({tp + tn}/{count}); "
|
|
f"precision={precision:.3f}, recall={recall:.3f}"
|
|
)
|
|
print(
|
|
f"Strict accuracy (flag + CWE): {strict_accuracy:.3f} "
|
|
f"({strict_correct}/{count}); "
|
|
f"wrong-category TPs={wrong_category_tp}"
|
|
)
|
|
print(
|
|
f"Category accuracy on true positives: {cat_accuracy:.3f} "
|
|
f"({category_correct}/{tp})"
|
|
)
|
|
print(
|
|
f"CWE accuracy on true positives: {cwe_accuracy:.3f} "
|
|
f"({cwe_correct}/{tp})"
|
|
)
|
|
elif labelled:
|
|
print("No evaluable in-scope rows (parse failures or missing labels).")
|
|
|
|
totals = connection.execute(
|
|
"""
|
|
SELECT
|
|
COALESCE(SUM(prompt_tokens), 0) AS prompt_tokens,
|
|
COALESCE(SUM(completion_tokens), 0) AS completion_tokens,
|
|
COALESCE(SUM(total_tokens), 0) AS total_tokens,
|
|
COUNT(*) AS calls
|
|
FROM attempts WHERE run_id = ?
|
|
""",
|
|
(run_id,),
|
|
).fetchone()
|
|
print(
|
|
"Tokens across all calls: "
|
|
f"prompt={totals['prompt_tokens']}, "
|
|
f"completion={totals['completion_tokens']}, "
|
|
f"total={totals['total_tokens']} ({totals['calls']} calls)"
|
|
)
|
|
|
|
if failed:
|
|
print("Failed samples:")
|
|
failed_rows = [row for row in rows if not row["parse_ok"]]
|
|
for row in failed_rows[:20]:
|
|
reason = (row["error"] or "unknown error").replace("\n", " ")[:160]
|
|
print(f" - {row['sample_name']}: {reason}")
|
|
if len(failed_rows) > 20:
|
|
print(f" ... and {len(failed_rows) - 20} more (see the database)")
|
|
|
|
|
|
def export_csv(connection: sqlite3.Connection, run_id: str, path: Path) -> None:
|
|
rows = connection.execute(
|
|
"""
|
|
SELECT
|
|
a.*,
|
|
r.model,
|
|
r.prompt_hash,
|
|
(
|
|
SELECT COUNT(*) FROM attempts b
|
|
WHERE b.run_id = a.run_id AND b.sample_path = a.sample_path
|
|
) AS call_count,
|
|
(
|
|
SELECT COALESCE(SUM(b.total_tokens), 0) FROM attempts b
|
|
WHERE b.run_id = a.run_id AND b.sample_path = a.sample_path
|
|
) AS total_tokens_all
|
|
FROM attempts a
|
|
JOIN run_meta r ON r.run_id = a.run_id
|
|
JOIN (
|
|
SELECT sample_path, MAX(call_index) AS max_index
|
|
FROM attempts
|
|
WHERE run_id = ?
|
|
GROUP BY sample_path
|
|
) latest
|
|
ON latest.sample_path = a.sample_path
|
|
AND latest.max_index = a.call_index
|
|
WHERE a.run_id = ?
|
|
ORDER BY a.sample_name
|
|
""",
|
|
(run_id, run_id),
|
|
)
|
|
columns = [description[0] for description in rows.description]
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
with path.open("w", encoding="utf-8", newline="") as handle:
|
|
writer = csv.writer(handle)
|
|
writer.writerow(columns)
|
|
for row in rows:
|
|
writer.writerow([row[column] for column in columns])
|
|
print(f"CSV: {path}")
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Model selection and API-key handling
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def resolve_model(raw_model: str, explicit_base_url: str | None) -> tuple[str, str]:
|
|
raw = raw_model.strip()
|
|
if raw.startswith("opencode-go/"):
|
|
default_base = DEFAULT_GO_BASE_URL
|
|
model = raw[len("opencode-go/") :]
|
|
elif raw.startswith("opencode/"):
|
|
default_base = DEFAULT_CONSOLE_BASE_URL
|
|
model = raw[len("opencode/") :]
|
|
else:
|
|
default_base = DEFAULT_CONSOLE_BASE_URL
|
|
model = raw
|
|
|
|
base = (explicit_base_url or default_base).rstrip("/")
|
|
if base.endswith("/chat/completions"):
|
|
base = base[: -len("/chat/completions")].rstrip("/")
|
|
if not model:
|
|
raise SystemExit("Model ID is empty")
|
|
return model, base
|
|
|
|
|
|
def models_url_for_base(base_url: str) -> str:
|
|
base = base_url.rstrip("/")
|
|
if base.endswith("/openai/v1"):
|
|
return base[: -len("/openai/v1")] + "/v1/models"
|
|
return base + "/models"
|
|
|
|
|
|
def resolve_api_key(args: argparse.Namespace, *, required: bool) -> str | None:
|
|
def clean(value: str) -> str:
|
|
value = value.strip()
|
|
if value.lower().startswith("bearer "):
|
|
value = value[7:].strip()
|
|
return value
|
|
|
|
if args.api_key:
|
|
return clean(args.api_key)
|
|
if args.api_key_file:
|
|
path = Path(args.api_key_file).expanduser()
|
|
try:
|
|
value = path.read_text(encoding="utf-8").strip()
|
|
except OSError as exc:
|
|
raise SystemExit(f"Could not read API key file {path}: {exc}") from exc
|
|
if value:
|
|
return clean(value)
|
|
value = os.environ.get(args.api_key_env, "").strip()
|
|
if value:
|
|
return clean(value)
|
|
if required and sys.stdin.isatty():
|
|
value = getpass.getpass(f"OpenCode API key ({args.api_key_env}): ").strip()
|
|
if value:
|
|
return clean(value)
|
|
if required:
|
|
raise SystemExit(
|
|
"No API key found. Set OPENCODE_API_KEY, use --api-key-file, or pass --api-key."
|
|
)
|
|
return None
|
|
|
|
|
|
def list_models(args: argparse.Namespace) -> int:
|
|
model, base_url = resolve_model(args.model or "opencode/placeholder", args.base_url)
|
|
api_key = resolve_api_key(args, required=False)
|
|
headers = {
|
|
"Accept": "application/json",
|
|
"User-Agent": "JU-ResearchMethods-SAST-Eval/1.0",
|
|
}
|
|
if api_key:
|
|
headers["Authorization"] = f"Bearer {api_key}"
|
|
url = models_url_for_base(base_url)
|
|
data, error = http_get_json(url, headers, args.timeout)
|
|
if error:
|
|
print(f"Could not list models from {url}: {error}", file=sys.stderr)
|
|
return 1
|
|
models = data.get("data") if isinstance(data, dict) else data
|
|
if not isinstance(models, list):
|
|
print(f"Unexpected model-list response from {url}", file=sys.stderr)
|
|
return 1
|
|
|
|
search = (args.search or "").lower()
|
|
shown = 0
|
|
for item in models:
|
|
if not isinstance(item, dict):
|
|
continue
|
|
model_id = str(item.get("id") or "")
|
|
name = str(item.get("name") or model_id)
|
|
if not model_id:
|
|
continue
|
|
if search and search not in model_id.lower() and search not in name.lower():
|
|
continue
|
|
print(f"{model_id}\t{name}")
|
|
shown += 1
|
|
print(f"\n{shown} models from {url}", file=sys.stderr)
|
|
return 0
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Main runner
|
|
# ---------------------------------------------------------------------------
|
|
|
|
@dataclass
|
|
class RunContext:
|
|
args: argparse.Namespace
|
|
model: str
|
|
base_url: str
|
|
prompt_name: str
|
|
prompt_text: str
|
|
prompt_hash: str
|
|
expected_path: Path | None
|
|
labels: dict[str, ExpectedLabel]
|
|
jobs: list[Job]
|
|
run_id: str
|
|
|
|
|
|
def build_context(args: argparse.Namespace, *, need_key: bool) -> tuple[RunContext, str | None]:
|
|
prompt_path = Path(args.prompt_file).expanduser()
|
|
prompt_text = load_prompt(prompt_path)
|
|
prompt_hash = sha256_text(prompt_text)
|
|
prompt_name = prompt_path.stem
|
|
|
|
expected_path = pick_expected_path(
|
|
Path(args.expected_csv).expanduser() if args.expected_csv else None
|
|
)
|
|
labels = load_expected(expected_path) if expected_path else {}
|
|
|
|
model, base_url = resolve_model(args.model, args.base_url)
|
|
inputs = expand_inputs(args.input, args.pattern)
|
|
jobs: list[Job] = []
|
|
missing_labels: list[str] = []
|
|
for path in inputs:
|
|
name = path.stem
|
|
expected = labels.get(name)
|
|
if expected is None and labels:
|
|
missing_labels.append(name)
|
|
jobs.append(
|
|
Job(
|
|
path=path,
|
|
display=display_path(path),
|
|
name=name,
|
|
condition=args.condition or infer_condition(path),
|
|
expected=expected,
|
|
)
|
|
)
|
|
if missing_labels:
|
|
print(
|
|
f"Warning: {len(missing_labels)} input(s) have no expected label "
|
|
f"(e.g. {', '.join(missing_labels[:5])})",
|
|
file=sys.stderr,
|
|
)
|
|
|
|
run_id = args.run_id or (
|
|
datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S-") + uuid.uuid4().hex[:6]
|
|
)
|
|
api_key = resolve_api_key(args, required=need_key)
|
|
return (
|
|
RunContext(
|
|
args=args,
|
|
model=model,
|
|
base_url=base_url,
|
|
prompt_name=prompt_name,
|
|
prompt_text=prompt_text,
|
|
prompt_hash=prompt_hash,
|
|
expected_path=expected_path,
|
|
labels=labels,
|
|
jobs=jobs,
|
|
run_id=run_id,
|
|
),
|
|
api_key,
|
|
)
|
|
|
|
|
|
def print_dry_run(context: RunContext, args: argparse.Namespace) -> None:
|
|
in_scope = sum(
|
|
1 for job in context.jobs if job.expected and job.expected.in_target_scope
|
|
)
|
|
matched = sum(1 for job in context.jobs if job.expected)
|
|
print("Dry run only; no API calls will be made.")
|
|
print(f"Run ID: {context.run_id}")
|
|
print(f"Model: {context.model}")
|
|
print(f"Chat endpoint: {context.base_url}/chat/completions")
|
|
print(f"Prompt: {context.prompt_name} (sha256 {context.prompt_hash[:16]}...)")
|
|
print(f"Input: {args.input} (pattern {args.pattern})")
|
|
print(f"Files: {len(context.jobs)}")
|
|
print(
|
|
f"Expected labels: {matched} matched, "
|
|
f"{len(context.jobs) - matched} missing; in-scope {in_scope}"
|
|
)
|
|
print(f"Expected CSV: {context.expected_path or 'none'}")
|
|
print(f"Database: {args.db}")
|
|
if args.resume:
|
|
print(f"Resume mode: run ID {context.run_id}")
|
|
if args.workers > 1:
|
|
print(f"Workers: {args.workers}")
|
|
print(f"Code placement: {args.code_in}")
|
|
print(f"Repair attempts: {args.repair_attempts}")
|
|
print(f"Max retries: {args.max_retries}")
|
|
print(
|
|
"Temperature: "
|
|
f"{'omitted' if args.no_temperature else args.temperature}"
|
|
)
|
|
print(f"Reasoning: {'off' if args.no_reasoning else 'provider default'}")
|
|
|
|
|
|
def run(args: argparse.Namespace) -> int:
|
|
context, api_key = build_context(args, need_key=not args.dry_run)
|
|
|
|
if args.dry_run:
|
|
print_dry_run(context, args)
|
|
return 0
|
|
|
|
assert api_key is not None
|
|
connection = open_db(Path(args.db).expanduser())
|
|
try:
|
|
store_prompt(
|
|
connection,
|
|
context.prompt_name,
|
|
context.prompt_text,
|
|
context.prompt_hash,
|
|
)
|
|
prepare_run(
|
|
connection,
|
|
run_id=context.run_id,
|
|
args=args,
|
|
model=context.model,
|
|
base_url=context.base_url,
|
|
prompt_name=context.prompt_name,
|
|
prompt_hash=context.prompt_hash,
|
|
expected_path=context.expected_path,
|
|
)
|
|
|
|
completed = completed_samples(connection, context.run_id) if args.resume else set()
|
|
pending: list[Job] = []
|
|
for job in context.jobs:
|
|
if job.display in completed:
|
|
continue
|
|
if args.resume:
|
|
job.start_call_index = (
|
|
max_call_index(connection, context.run_id, job.display) + 1
|
|
)
|
|
pending.append(job)
|
|
|
|
if completed:
|
|
print(f"Resume: skipping {len(completed)} already-parsed sample(s)")
|
|
print(
|
|
f"Run {context.run_id}: {len(pending)} sample(s), "
|
|
f"model {context.model}, endpoint {context.base_url}"
|
|
)
|
|
if args.verbose:
|
|
print(f"Prompt: {context.prompt_name} (sha256 {context.prompt_hash})")
|
|
print(f"Expected CSV: {context.expected_path or 'none'}")
|
|
print(f"Database: {Path(args.db).expanduser().resolve()}")
|
|
|
|
runner = Runner(
|
|
args=args,
|
|
prompt_text=context.prompt_text,
|
|
model=context.model,
|
|
base_url=context.base_url,
|
|
api_key=api_key,
|
|
run_id=context.run_id,
|
|
)
|
|
|
|
def persist_and_report(index: int, job: Job) -> None:
|
|
try:
|
|
attempts = runner.process(job)
|
|
except Exception as exc: # keep one bad sample from killing a batch
|
|
attempts = [
|
|
Attempt(
|
|
call_index=job.start_call_index,
|
|
phase="initial",
|
|
created_at=now_iso(),
|
|
error=f"Unhandled error: {type(exc).__name__}: {exc}",
|
|
)
|
|
]
|
|
code_sha256 = ""
|
|
try:
|
|
code_sha256 = sha256_text(job.path.read_text(encoding="utf-8"))
|
|
except (OSError, UnicodeError):
|
|
pass
|
|
for attempt in attempts:
|
|
insert_attempt(
|
|
connection,
|
|
context.run_id,
|
|
job,
|
|
code_sha256,
|
|
attempt,
|
|
)
|
|
connection.commit()
|
|
|
|
last = attempts[-1] if attempts else None
|
|
if last and last.parse_ok:
|
|
prediction = f"{last.flagged}/{last.category or 'None'}"
|
|
elif last and last.error:
|
|
prediction = f"FAILED ({last.error.splitlines()[0][:70]})"
|
|
else:
|
|
prediction = "FAILED"
|
|
expected = (
|
|
f"{job.expected.vulnerable}/{job.expected.category}"
|
|
if job.expected
|
|
else "-"
|
|
)
|
|
latency = last.latency_ms if last else 0
|
|
calls = len(attempts)
|
|
print(
|
|
f"[{index:>3}/{len(pending)}] {job.name:<22} "
|
|
f"pred={prediction:<28} exp={expected:<24} "
|
|
f"{latency:>6}ms calls={calls}",
|
|
flush=True,
|
|
)
|
|
|
|
if args.workers <= 1:
|
|
for index, job in enumerate(pending, start=1):
|
|
persist_and_report(index, job)
|
|
if args.delay and index < len(pending):
|
|
time.sleep(args.delay)
|
|
else:
|
|
with ThreadPoolExecutor(max_workers=args.workers) as executor:
|
|
futures = {
|
|
executor.submit(runner.process, job): job for job in pending
|
|
}
|
|
for index, future in enumerate(as_completed(futures), start=1):
|
|
job = futures[future]
|
|
try:
|
|
attempts = future.result()
|
|
except Exception as exc:
|
|
attempts = [
|
|
Attempt(
|
|
call_index=job.start_call_index,
|
|
phase="initial",
|
|
created_at=now_iso(),
|
|
error=f"Unhandled error: {type(exc).__name__}: {exc}",
|
|
)
|
|
]
|
|
code_sha256 = ""
|
|
try:
|
|
code_sha256 = sha256_text(job.path.read_text(encoding="utf-8"))
|
|
except (OSError, UnicodeError):
|
|
pass
|
|
for attempt in attempts:
|
|
insert_attempt(
|
|
connection,
|
|
context.run_id,
|
|
job,
|
|
code_sha256,
|
|
attempt,
|
|
)
|
|
connection.commit()
|
|
|
|
last = attempts[-1] if attempts else None
|
|
if last and last.parse_ok:
|
|
prediction = f"{last.flagged}/{last.category or 'None'}"
|
|
elif last and last.error:
|
|
prediction = f"FAILED ({last.error.splitlines()[0][:70]})"
|
|
else:
|
|
prediction = "FAILED"
|
|
expected = (
|
|
f"{job.expected.vulnerable}/{job.expected.category}"
|
|
if job.expected
|
|
else "-"
|
|
)
|
|
latency = last.latency_ms if last else 0
|
|
calls = len(attempts)
|
|
print(
|
|
f"[{index:>3}/{len(pending)}] {job.name:<22} "
|
|
f"pred={prediction:<28} exp={expected:<24} "
|
|
f"{latency:>6}ms calls={calls}",
|
|
flush=True,
|
|
)
|
|
|
|
connection.execute(
|
|
"UPDATE run_meta SET finished_at = ? WHERE run_id = ?",
|
|
(now_iso(), context.run_id),
|
|
)
|
|
connection.commit()
|
|
|
|
print_summary(connection, context.run_id)
|
|
|
|
if not args.no_csv:
|
|
csv_path = (
|
|
Path(args.csv).expanduser()
|
|
if args.csv
|
|
else BASE_DIR / "results" / f"{safe_filename(context.run_id)}.csv"
|
|
)
|
|
export_csv(connection, context.run_id, csv_path)
|
|
|
|
db_path = Path(args.db).expanduser().resolve()
|
|
print(f"Database: {db_path}")
|
|
return 0
|
|
finally:
|
|
connection.close()
|
|
|
|
|
|
def report_run(args: argparse.Namespace) -> int:
|
|
db_path = Path(args.db).expanduser()
|
|
if not db_path.is_file():
|
|
print(f"Database not found: {db_path}", file=sys.stderr)
|
|
return 1
|
|
connection = sqlite3.connect(db_path, timeout=30)
|
|
connection.row_factory = sqlite3.Row
|
|
try:
|
|
try:
|
|
row = connection.execute(
|
|
"SELECT run_id FROM run_meta WHERE run_id = ?", (args.report,)
|
|
).fetchone()
|
|
except sqlite3.Error as exc:
|
|
print(f"Could not read database {db_path}: {exc}", file=sys.stderr)
|
|
return 1
|
|
if row is None:
|
|
print(f"Run not found: {args.report}", file=sys.stderr)
|
|
return 1
|
|
print_summary(connection, args.report)
|
|
if not args.no_csv:
|
|
csv_path = (
|
|
Path(args.csv).expanduser()
|
|
if args.csv
|
|
else BASE_DIR / "results" / f"{safe_filename(args.report)}.csv"
|
|
)
|
|
export_csv(connection, args.report, csv_path)
|
|
print(f"Database: {db_path.resolve()}")
|
|
return 0
|
|
finally:
|
|
connection.close()
|
|
|
|
|
|
def build_parser() -> argparse.ArgumentParser:
|
|
parser = argparse.ArgumentParser(
|
|
description=(
|
|
"Run a SAST prompt against OpenCode-hosted models and record results "
|
|
"in SQLite (plus CSV)."
|
|
),
|
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
|
)
|
|
parser.add_argument(
|
|
"-i",
|
|
"--input",
|
|
help="File, directory, or glob of Python samples (required for a run).",
|
|
)
|
|
parser.add_argument(
|
|
"--pattern",
|
|
default="*.py",
|
|
help="Glob pattern used when --input is a directory.",
|
|
)
|
|
parser.add_argument(
|
|
"-m",
|
|
"--model",
|
|
help=(
|
|
"Model ID, e.g. deepseek-v4.1-flash, opencode/<id>, or "
|
|
"opencode-go/<id>."
|
|
),
|
|
)
|
|
parser.add_argument(
|
|
"--base-url",
|
|
help=(
|
|
"Override the OpenAI-compatible base URL. Console and Go URLs are "
|
|
"selected automatically from the model prefix."
|
|
),
|
|
)
|
|
parser.add_argument(
|
|
"--api-key",
|
|
help="API key (prefer --api-key-file or OPENCODE_API_KEY).",
|
|
)
|
|
parser.add_argument(
|
|
"--api-key-file",
|
|
help="File containing the API key (safer than --api-key).",
|
|
)
|
|
parser.add_argument(
|
|
"--api-key-env",
|
|
default="OPENCODE_API_KEY",
|
|
help="Environment variable containing the API key.",
|
|
)
|
|
parser.add_argument(
|
|
"--prompt-file",
|
|
default=str(DEFAULT_PROMPT_PATH),
|
|
help="System-prompt text file, or JSON with a 'prompt' field.",
|
|
)
|
|
parser.add_argument(
|
|
"--code-in",
|
|
choices=("system", "user"),
|
|
default="system",
|
|
help="Place the code in the system prompt or in a separate user message.",
|
|
)
|
|
parser.add_argument(
|
|
"--expected-csv",
|
|
help="Expected-results CSV (defaults to data/expectedresults-0.1.csv).",
|
|
)
|
|
parser.add_argument(
|
|
"--condition",
|
|
help="Condition label stored with every result (default: infer from path).",
|
|
)
|
|
parser.add_argument(
|
|
"--db",
|
|
default=str(DEFAULT_DB_PATH),
|
|
help="SQLite results database.",
|
|
)
|
|
parser.add_argument(
|
|
"--csv",
|
|
help="CSV export path (default: results/<run-id>.csv).",
|
|
)
|
|
parser.add_argument(
|
|
"--no-csv",
|
|
action="store_true",
|
|
help="Do not write a CSV export.",
|
|
)
|
|
parser.add_argument(
|
|
"--run-id",
|
|
help="Run identifier (default: timestamp plus random suffix).",
|
|
)
|
|
parser.add_argument(
|
|
"--report",
|
|
metavar="RUN_ID",
|
|
help="Print the summary and export CSV for an existing run; no API calls.",
|
|
)
|
|
parser.add_argument(
|
|
"--resume",
|
|
action="store_true",
|
|
help="Resume an existing run ID, skipping successfully parsed samples.",
|
|
)
|
|
parser.add_argument(
|
|
"--workers",
|
|
type=int,
|
|
default=1,
|
|
help="Number of concurrent API workers.",
|
|
)
|
|
parser.add_argument(
|
|
"--timeout",
|
|
type=float,
|
|
default=180.0,
|
|
help="HTTP timeout in seconds.",
|
|
)
|
|
parser.add_argument(
|
|
"--max-retries",
|
|
type=int,
|
|
default=4,
|
|
help="Retries for 429/5xx/network errors.",
|
|
)
|
|
parser.add_argument(
|
|
"--repair-attempts",
|
|
type=int,
|
|
default=1,
|
|
help="Extra model calls to repair invalid JSON.",
|
|
)
|
|
parser.add_argument(
|
|
"--temperature",
|
|
type=float,
|
|
default=0.0,
|
|
help="Sampling temperature.",
|
|
)
|
|
parser.add_argument(
|
|
"--no-temperature",
|
|
action="store_true",
|
|
help="Omit the temperature parameter entirely.",
|
|
)
|
|
parser.add_argument(
|
|
"--max-tokens",
|
|
type=int,
|
|
default=None,
|
|
help="Optional output-token limit.",
|
|
)
|
|
parser.add_argument(
|
|
"--no-reasoning",
|
|
"--no-thinking",
|
|
dest="no_reasoning",
|
|
action="store_true",
|
|
help=(
|
|
"Disable provider reasoning/thinking where supported. OpenRouter "
|
|
"receives reasoning={enabled: false}; other endpoints may ignore it."
|
|
),
|
|
)
|
|
parser.add_argument(
|
|
"--delay",
|
|
type=float,
|
|
default=0.0,
|
|
help="Delay in seconds between samples (sequential mode).",
|
|
)
|
|
parser.add_argument(
|
|
"--dry-run",
|
|
action="store_true",
|
|
help="Show what would be sent and write nothing.",
|
|
)
|
|
parser.add_argument(
|
|
"--list-models",
|
|
action="store_true",
|
|
help="List models available at the selected endpoint.",
|
|
)
|
|
parser.add_argument(
|
|
"--search",
|
|
help="Filter --list-models by substring.",
|
|
)
|
|
parser.add_argument(
|
|
"--verbose",
|
|
action="store_true",
|
|
help="Print additional diagnostic information.",
|
|
)
|
|
return parser
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
parser = build_parser()
|
|
args = parser.parse_args(argv)
|
|
|
|
if args.workers < 1:
|
|
parser.error("--workers must be at least 1")
|
|
if args.max_retries < 0:
|
|
parser.error("--max-retries must be non-negative")
|
|
if args.repair_attempts < 0:
|
|
parser.error("--repair-attempts must be non-negative")
|
|
if args.timeout <= 0:
|
|
parser.error("--timeout must be positive")
|
|
if args.resume and not args.run_id:
|
|
parser.error("--resume requires --run-id")
|
|
if args.report:
|
|
return report_run(args)
|
|
if not args.list_models:
|
|
if not args.input:
|
|
parser.error("--input is required")
|
|
if not args.model:
|
|
parser.error("--model is required")
|
|
|
|
if args.list_models:
|
|
return list_models(args)
|
|
return run(args)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|