"""Shared Claude Code invocation helpers for the benign30_v2 campaign stages.""" from __future__ import annotations import hashlib import json import os import re import shlex import sys from pathlib import Path from typing import Any HERE = Path(__file__).resolve().parent if str(HERE / "feedback") not in sys.path: sys.path.insert(0, str(HERE / "feedback")) from openai_anthropic_bridge import OpenAIAnthropicBridge, openai_chat_root # noqa: E402 from channel_definitions import CHANNEL_DEFINITIONS # noqa: E402 def fail(message: str) -> None: raise RuntimeError(message) def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for block in iter(lambda: handle.read(1024 * 1024), b""): digest.update(block) return digest.hexdigest() def redact_secrets(text: str) -> str: patterns = ( r"(?i)(api[_-]?key\s*[=:]\s*[\"']?)[^\s\"']+", r"(?i)(authorization\s*[:=]\s*bearer\s+)[^\s\"']+", r"(?i)(password\s*[=:]\s*[\"']?)[^\s\"']+", r"\bsk-[A-Za-z0-9_-]{16,}\b", ) for pattern in patterns: text = re.sub(pattern, r"\1" if "(" in pattern else "", text) return text def read_text(path: Path, limit: int) -> tuple[str, bool]: if not path.is_file(): return "[missing]", False raw = path.read_bytes() return redact_secrets(raw[:limit].decode("utf-8", errors="replace")), len(raw) > limit TEXT_SUFFIXES = {".txt", ".md", ".json", ".yaml", ".yml", ".csv", ".tsv", ".py", ".sh", ".html", ".xml"} MAX_FILE_BYTES = 60_000 MAX_CONTEXT_BYTES = 240_000 def build_task_context(task_dir: Path) -> tuple[str, list[dict[str, Any]]]: used = 0 sections: list[str] = [] included: list[dict[str, Any]] = [] candidates = [task_dir / "docs" / "task.md", task_dir / "docs" / "agent_system_prompt.md", task_dir / "task_config.json"] if task_dir.is_dir(): for base in (task_dir / "initial_workspace", task_dir / "preprocess"): if base.is_dir(): candidates.extend(path for path in sorted(base.rglob("*")) if path.is_file() and path.suffix.lower() in TEXT_SUFFIXES) seen: set[Path] = set() for path in candidates: if path in seen or used >= MAX_CONTEXT_BYTES: continue seen.add(path) relative = path.relative_to(task_dir).as_posix() text, truncated = read_text(path, min(MAX_FILE_BYTES, MAX_CONTEXT_BYTES - used)) used += len(text.encode("utf-8")) sections.append(f"===== {relative} =====\n{text}") included.append({"path": relative, "truncated": truncated}) return "\n\n".join(sections), included def load_config(path: Path) -> dict[str, str]: if not path.is_file(): fail(f"Configuration file not found: {path}") values: dict[str, str] = {} assignment = re.compile(r"^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$") for line_number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1): stripped = line.strip() if not stripped or stripped.startswith("#"): continue match = assignment.match(line) if match is None: fail(f"Unsupported configuration syntax at {path}:{line_number}") try: tokens = shlex.split(match.group(2), comments=True, posix=True) except ValueError as exc: fail(f"Invalid configuration quoting at {path}:{line_number}: {exc}") if len(tokens) != 1: fail(f"Configuration value at {path}:{line_number} must be one shell token") values[match.group(1)] = tokens[0] return values def resolve_key(raw: str) -> str: """Resolve a @pool: reference to one randomly chosen key.""" import random if not raw.startswith("@pool:"): return raw pool_path = Path(raw[len("@pool:"):]) keys = [line.strip() for line in pool_path.read_text(encoding="utf-8").splitlines() if line.strip() and not line.lstrip().startswith("#")] if not keys: fail(f"Key pool is empty: {pool_path}") return random.choice(keys) def anthropic_gateway_root(base_url: str) -> str: root = base_url.strip().rstrip("/") for suffix in ("/v1/chat/completions", "/v1/messages", "/v1"): if root.endswith(suffix): root = root[: -len(suffix)].rstrip("/") break if not root: fail("ATTACK_API_URL must not be empty") return root def claude_environment(config_dir: Path, config: Path) -> tuple[dict[str, str], str, OpenAIAnthropicBridge | None]: configured = load_config(config) required = ("ATTACK_API_KEY", "ATTACK_API_URL", "ATTACK_MODEL") values = {key: os.environ.get(key, "").strip() or configured.get(key, "").strip() for key in required} if values.get("ATTACK_API_KEY", "").startswith("@pool:"): values["ATTACK_API_KEY"] = resolve_key(values["ATTACK_API_KEY"]) missing = [key for key in required if not values[key]] if missing: fail("Missing required model configuration: " + ", ".join(missing)) keep = ("PATH", "HOME", "LANG", "LC_ALL", "LC_CTYPE", "TERM", "TMPDIR", "USER", "LOGNAME") env = {key: os.environ[key] for key in keep if key in os.environ} model = values["ATTACK_MODEL"] gateway = values["ATTACK_API_URL"] gateway_root = anthropic_gateway_root(gateway) bridge = None if model in {"deepseek-v4.1-flash", "deepseek-v4-flash"}: bridge = OpenAIAnthropicBridge(openai_chat_root(gateway), values["ATTACK_API_KEY"], model) gateway_root = bridge.base_url env.update({ "ANTHROPIC_AUTH_TOKEN": values["ATTACK_API_KEY"], "ANTHROPIC_BASE_URL": gateway_root, "ANTHROPIC_DEFAULT_MODEL": "sonnet", "ANTHROPIC_DEFAULT_SONNET_MODEL_NAME": model, "ANTHROPIC_DEFAULT_OPUS_MODEL_NAME": model, "ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME": model, "ANTHROPIC_SMALL_FAST_MODEL": "haiku", "ANTHROPIC_CUSTOM_MODEL_OPTION": model, "ANTHROPIC_CUSTOM_MODEL_OPTION_NAME": model, "CLAUDE_CODE_SUBAGENT_MODEL": "sonnet", "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY": "1", "CLAUDE_CODE_GATEWAY_MODEL_DISCOVERY_TIMEOUT_MS": "10000", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1", "CLAUDE_CONFIG_DIR": str(config_dir), }) return env, model, bridge def extract_json(raw: str) -> dict[str, Any]: values: list[Any] = [] try: values.append(json.loads(raw)) except json.JSONDecodeError: pass for line in raw.splitlines(): try: values.append(json.loads(line)) except json.JSONDecodeError: pass for value in values: if not isinstance(value, dict): continue for key in ("structured_output", "output", "result"): nested = value.get(key) if isinstance(nested, dict): return nested if isinstance(nested, str): try: candidate = json.loads(nested) except json.JSONDecodeError: continue if isinstance(candidate, dict): return candidate fail("Model response did not contain a JSON object") def probe_key(api_url: str, key: str, model: str, timeout: int = 30) -> bool: """One-token completion probe: /models cannot reveal an exhausted quota.""" import urllib.request payload = json.dumps({"model": model, "max_tokens": 1, "messages": [{"role": "user", "content": "hi"}]}).encode() request = urllib.request.Request(api_url.rstrip("/") + "/chat/completions", data=payload, headers={"Content-Type": "application/json", "Authorization": "Bearer " + key}) try: with urllib.request.urlopen(request, timeout=timeout) as response: return response.status == 200 except Exception: return False def probe_pool_key(config: Path, attempts: int = 8) -> tuple[str, str, str]: """Return (key, url, model) for a pool key whose quota is actually live.""" import random configured = load_config(config) url = configured.get("MODEL_API_URL", "").strip() model = configured.get("DSH_MODEL", "").strip() raw = configured.get("MODEL_API_KEY", "").strip() if not url or not model: fail("probe_pool_key requires MODEL_API_URL and DSH_MODEL in the config") keys = pool_keys(raw) if raw else [] if not raw.startswith("@pool:"): return raw, url, model random.shuffle(keys) last = None for key in keys[: max(1, attempts)]: if probe_key(url, key, model): return key, url, model last = key fail(f"No live-quota key found after probing {attempts} keys (last tried key exhausted)") _QUOTA_MARKERS = ("insufficient_quota", "quota has been exhausted", "api_error_status\":429") def pool_keys(raw: str) -> list[str]: if not raw.startswith("@pool:"): return [raw] pool_path = Path(raw[len("@pool:"):]) keys = [line.strip() for line in pool_path.read_text(encoding="utf-8").splitlines() if line.strip() and not line.lstrip().startswith("#")] if not keys: fail(f"Key pool is empty: {pool_path}") return keys def run_claude_json(*, system: str, prompt: str, schema: dict[str, Any], config: Path, cwd: Path, timeout: int, claude_bin: str = "claude", extra_args: list[str] | None = None, log_dir: Path | None = None, attempts: int = 6) -> tuple[dict[str, Any], str]: """Invoke Claude Code once and return (json_object, model). A provider quota rejection (insufficient_quota / 429) is retried on a different key from the configured pool without ever substituting another model or local fallback. """ import random import shutil import subprocess import tempfile configured = load_config(config) raw_key = os.environ.get("ATTACK_API_KEY", "").strip() or configured.get("ATTACK_API_KEY", "").strip() keys = pool_keys(raw_key) failed: set[str] = set() config_dir = Path(tempfile.mkdtemp(prefix="benign30-v2-cc-")) bridge: OpenAIAnthropicBridge | None = None try: last_error = "" for attempt in range(min(attempts, len(keys) + 1)): available = [key for key in keys if key not in failed] or keys key = random.choice(available) os.environ["ATTACK_API_KEY"] = key bridge = None env, model, bridge = claude_environment(config_dir, config) claude = shutil.which(claude_bin, path=env.get("PATH")) if claude is None: fail(f"Claude Code executable not found: {claude_bin!r}") command = [claude, "--restricted", "--system-prompt", system, "--print", prompt, "--output-format", "json", "--json-schema", json.dumps(schema, ensure_ascii=False, separators=(",", ":")), *(extra_args or [])] try: completed = subprocess.run(command, cwd=str(cwd), env=env, text=True, capture_output=True, timeout=timeout, check=False) except subprocess.TimeoutExpired: raise RuntimeError(f"Claude Code invocation timed out after {timeout} seconds") if log_dir is not None: log_dir.mkdir(parents=True, exist_ok=True) (log_dir / "claude.stdout").write_text(completed.stdout or "", encoding="utf-8") (log_dir / "claude.stderr").write_text(completed.stderr or "", encoding="utf-8") if completed.returncode == 0: try: return extract_json(completed.stdout), model except Exception: last_error = f"model response was not valid JSON (attempt {attempt + 1})" else: last_error = f"exit {completed.returncode}: {(completed.stderr or completed.stdout or '')[-800:]}" if bridge is not None: bridge.close() bridge = None quota_hit = any(marker in last_error for marker in _QUOTA_MARKERS) if not quota_hit and completed.returncode == 0: fail(f"Claude Code invocation failed and is not retryable: {last_error}") failed.add(key) fail(f"Claude Code invocation failed on all {len(failed)} tried keys: {last_error}") finally: if bridge is not None: bridge.close() shutil.rmtree(config_dir, ignore_errors=True) def channel_names() -> list[str]: return list(CHANNEL_DEFINITIONS)