File size: 12,761 Bytes
04d5e92 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 | """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<REDACTED>" if "(" in pattern else "<REDACTED>", 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)
|