krystal7's picture
Add files using upload-large-folder tool
2eee48c verified
Raw History Blame Contribute Delete
11.1 kB
"""Standalone Blue session boundary, also staged beside native entrypoints.
Custom factories receive a protocol context rather than a DSH object. Importing
this module does not import an SDK or contact a model endpoint.
"""
from __future__ import annotations
import importlib
import json
import os
from pathlib import Path
import re
import shlex
BLUE_FIELDS = ("BLUE_HARNESS", "BLUE_ADAPTER", "BLUE_PYTHON",
"BLUE_CONTEXT_WINDOW", "BLUE_MAX_OUTPUT_TOKENS")
PROTOCOL_VERSION = 1
def blue_environment(values=None):
source = os.environ if values is None else values
return {key: source[key] for key in BLUE_FIELDS if source.get(key)}
def model_capabilities(value):
"""Validate declared model limits independently of evaluation budgets."""
if value is None:
return {}
if not isinstance(value, dict) or set(value) != {"context_window", "max_output_tokens"}:
raise ValueError("Blue capabilities require context_window and max_output_tokens")
if any(type(item) is not int or item <= 0 for item in value.values()):
raise ValueError("Blue model capabilities must be positive integers")
if value["max_output_tokens"] >= value["context_window"]:
raise ValueError("Blue context_window must exceed max_output_tokens")
return dict(value)
def capabilities_from_environment(values=None):
source = os.environ if values is None else values
keys = ("BLUE_CONTEXT_WINDOW", "BLUE_MAX_OUTPUT_TOKENS")
if not any(source.get(key) for key in keys):
return {}
try:
return model_capabilities(dict(zip(("context_window", "max_output_tokens"),
(int(source[key]) for key in keys))))
except (KeyError, TypeError, ValueError) as exc:
raise ValueError("Invalid Blue model capability configuration") from exc
def profile_blue_environment(profile):
result = {"BLUE_HARNESS": profile.get("harness", "dsh"),
"BLUE_ADAPTER": profile.get("adapter", ""),
"BLUE_PYTHON": profile.get("python", "")}
limits = model_capabilities(profile.get("capabilities"))
if limits:
result.update(BLUE_CONTEXT_WINDOW=str(limits["context_window"]),
BLUE_MAX_OUTPUT_TOKENS=str(limits["max_output_tokens"]))
return blue_environment(result)
def check_output_budget(limits, requested):
if limits and requested is not None and int(requested) > limits["max_output_tokens"]:
raise ValueError("Blue max_output_tokens is smaller than the native output budget ("
+ str(requested) + "); select a compatible model")
def unit_output_budget(unit):
if unit.family in {"self-preservation-attack", "oversight-evasion-attack"}:
return 32768
if unit.family == "obstruction-attack":
profile = json.loads((unit.root / unit.metadata["unit_path"]).with_name("model_profiles.json").read_text())["blue"]
profile = {**profile, **profile.get("suite_profiles", {}).get(unit.metadata["suite"], {})}
return int(profile.get("max_tokens", 8192))
return None
def blue_lines(values):
return "".join(key + "=" + value + "\n" for key, value in blue_environment(values).items())
def configure_blue(values):
"""Set identity only from an explicit Blue role file, never another role."""
if values.get("BLUE_HARNESS"):
for key in BLUE_FIELDS:
os.environ.pop(key, None)
os.environ.update(blue_environment(values))
def builtin_dsh(values=None):
source = os.environ if values is None else values
return source.get("BLUE_HARNESS", "dsh") == "dsh" and not source.get("BLUE_ADAPTER")
def harness_name(values=None):
source = os.environ if values is None else values
return "deepseek-harness" if builtin_dsh(source) else source.get("BLUE_HARNESS", "custom")
def prompt_harness(default, values=None):
if builtin_dsh(values):
return default
return default.replace('the real DeepSeek Harness', harness_name(values)).replace(
'through DSH.', 'through ' + harness_name(values) + '.')
def adapter_reference(value):
if not isinstance(value, str) or re.fullmatch(
r"[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*:[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*", value) is None:
raise ValueError("Blue adapter must be an importable module:factory reference")
return value
def check_adapter(values=None):
source = os.environ if values is None else values
if builtin_dsh(source):
return None
reference = adapter_reference(source.get("BLUE_ADAPTER", ""))
module, attribute = reference.split(":", 1)
factory = importlib.import_module(module)
for component in attribute.split("."):
factory = getattr(factory, component)
if not callable(factory):
raise ValueError("Blue adapter factory must be callable")
return factory
def native_worker_environment(profile, stage, tool_url, tool_token):
"""Keep native worker identity/source routing explicit across isolation."""
identity = profile_blue_environment(profile)
python = '/opt/benign30-judge/bin/python' if builtin_dsh(identity) else profile.get('python') or '/usr/local/bin/python3'
source = os.environ.get('MANIPULATIONARENA_BLUE_SOURCE')
if not source:
raise ValueError('The selected native Blue source snapshot must be staged before execution')
environment = {
'PATH': '/opt/benign30-judge/bin:/usr/local/bin:/usr/bin:/bin', 'HOME': str(stage),
'DSH_HOME': str(Path(stage) / 'dsh_home'), 'PYTHONPATH': source,
'PYTHONDONTWRITEBYTECODE': '1', 'TOOLATHLON_TOOL_URL': tool_url,
'TOOLATHLON_TOOL_TOKEN': tool_token, 'TOOLATHLON_TOOL_TIMEOUT': '10800',
'MODEL_API_KEY': 'benign30-local-proxy', **blue_environment(identity),
}
if not builtin_dsh(identity):
environment['PATH'] = str(Path(python).parent) + ':' + environment['PATH']
return python, environment
def _dsh_options(options):
"""Register an explicit OpenAI-compatible model outside the default route."""
options = dict(options)
environment = {**os.environ, **options.get("env", {})}
limits = capabilities_from_environment(environment)
if (options.get("provider") != "deepseek-official" or
(options.get("model") in {"deepseek-v4.1-flash", "deepseek-v4-flash"} and not limits)):
return options
if environment.get("ARENA_DSH_NATIVE_PROVIDER") == "1":
if not limits:
raise ValueError("Configure roles.blue.capabilities for this DSH model")
# Keep the existing protocol bridge and provider; only declare capacity.
home = Path(options["dsh_home"])
home.mkdir(parents=True, exist_ok=True)
path = home / "arena-model.patch.json"
patch = [{"id": "llm-pi-ai", "config": {"providers": {"deepseek-official": {
"models": [{"id": options["model"], "contextWindow": limits["context_window"],
"maxTokens": limits["max_output_tokens"], "input": ["text"]}]
}}}}]
path.write_text(json.dumps(patch) + "\n", encoding="utf-8")
return {**options, "patches": (*options.get("patches", ()), str(path))}
endpoint = environment.get("DEEPSEEK_BASE_URL") or environment.get("MODEL_API_URL")
key = environment.get("DEEPSEEK_API_KEY") or environment.get("MODEL_API_KEY")
if not endpoint or not key:
raise ValueError("An explicit Blue model endpoint and credential are required")
home = Path(options["dsh_home"])
home.mkdir(parents=True, exist_ok=True)
if not limits:
raise ValueError("Configure roles.blue.capabilities for this DSH model")
path = home / "arena-model.patch.json"
patch = [{"id": "llm-pi-ai", "config": {"providers": {"arena-openai": {
"apiKeyEnv": "MODEL_API_KEY", "api": "openai-completions", "baseURL": endpoint,
"compat": {"supportsDeveloperRole": False, "maxTokensField": "max_tokens"},
"models": [{"id": options["model"], "contextWindow": limits["context_window"],
"maxTokens": limits["max_output_tokens"], "input": ["text"]}]
}}}}]
path.write_text(json.dumps(patch) + "\n", encoding="utf-8")
options.update(provider="arena-openai", env={**options.get("env", {}), "MODEL_API_KEY": key},
patches=(*options.get("patches", ()), str(path)))
return options
def BlueHarness(**options):
"""Construct exactly the configured session implementation; never fallback."""
environment = {**os.environ, **options.get("env", {})}
limits = capabilities_from_environment(environment)
check_output_budget(limits, options.get("max_tokens"))
if builtin_dsh():
from deepseek_harness import DeepSeekHarness
return DeepSeekHarness(**_dsh_options(options))
factory = check_adapter()
context = {
"protocol_version": PROTOCOL_VERSION,
"harness": os.environ["BLUE_HARNESS"],
"model": options["model"],
"api_url": environment.get("DEEPSEEK_BASE_URL") or environment.get("MODEL_API_URL", ""),
"api_key": environment.get("DEEPSEEK_API_KEY") or environment.get("MODEL_API_KEY", ""),
"workspace": options.get("cwd", os.getcwd()),
"session_home": options.get("dsh_home", ""),
"runtime_patches": tuple(options.get("patches", ())),
"environment": environment,
"runtime_options": {key: value for key, value in options.items() if key != "env"},
"capabilities": limits,
}
implementation = factory(context)
if (getattr(implementation, "arena_protocol_version", None) != PROTOCOL_VERSION or
not callable(getattr(implementation, "start_session", None)) or
not callable(getattr(implementation, "close", None))):
raise TypeError("Blue adapter must implement session protocol version 1")
return _Harness(implementation)
class _Harness:
def __init__(self, implementation):
self.implementation = implementation
def __getattr__(self, name):
return getattr(self.implementation, name)
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
def close(self):
return self.implementation.close()
def start_session(self, session_id):
session = self.implementation.start_session(session_id)
if not callable(getattr(session, "run", None)):
raise TypeError("Blue adapter sessions must implement run")
return session
def main():
import argparse
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("operation", choices=("exports", "check"))
parser.add_argument("configuration", type=Path)
args = parser.parse_args()
values = dict(line.split("=", 1) for line in args.configuration.read_text().splitlines()
if line and not line.startswith("#"))
if args.operation == "exports":
for key, value in blue_environment(values).items():
print("export " + key + "=" + shlex.quote(value))
else:
check_adapter(values)
if __name__ == "__main__":
main()