Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
Harbor
License:
File size: 10,983 Bytes
32084d2
5873600
32084d2
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32084d2
5538a28
5873600
 
 
 
 
32084d2
5873600
 
 
32084d2
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b710f09
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32084d2
b710f09
5873600
 
5538a28
 
 
 
 
5873600
 
 
 
 
 
 
 
5538a28
 
5873600
 
 
 
b710f09
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9b5504
 
 
 
 
 
 
 
5873600
32084d2
b710f09
5873600
 
 
 
 
 
 
 
b710f09
a9b5504
5873600
b710f09
a9b5504
5873600
 
 
 
 
 
 
b710f09
5873600
 
 
 
 
 
 
b710f09
a9b5504
5873600
 
 
 
5538a28
 
5873600
 
 
 
 
 
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
"""Small config front door to unchanged stock Legion; no study controller.

The evaluated agent is Pi 1.5.0 (256 turns, one-hour Legion guard, no agent
deadline). Its model can come from Google, OpenAI, Anthropic or any
OpenAI-compatible inference endpoint: Pi and the private final-answer readout
both reach it through the task-local model gateway (`model-compat`), the only
host the agent can reach besides `team`. The provider is inferred from the
model name (gemini-*, gpt-*/o*, claude-*), or set with CI_MODEL_PROVIDER;
CI_MODEL_UPSTREAM overrides the provider base URL and is required for a
generic endpoint. This wrapper never substitutes a model or changes the config.
"""

from __future__ import annotations

import argparse
import asyncio
import hashlib
import ipaddress
import json
import os
from pathlib import Path
from urllib.parse import urlsplit


def metadata(config):
    from harbor.agents.agent_auth_resolution import parse_model_name

    from collab_harbor.legion_config import PI_VERSION

    _, evaluated = parse_model_name(config.model)
    if not evaluated or not isinstance(evaluated, str):
        raise ValueError("The configured evaluated model must resolve explicitly")
    return evaluated, {
        "scaffold": config.harness,
        "runner": "stock-legion",
        "version": PI_VERSION,
        "model": evaluated,
        "endpoint": config.inference.base_url,
        "transport": "configured stock Legion endpoint",
        "parameters": {
            "api_format": config.inference.api_format,
            "reasoning_effort": config.inference.reasoning_effort,
            "max_turns": config.limits.agent_max_turns,
        },
    }


def original_role_configuration(environ):
    """Validate configured original partners without contacting any provider."""
    effort = json.loads(environ.get("HARNESS_OPENAI_EFFORT") or "{}")
    if not isinstance(effort, dict) or effort.get("gpt-5-mini", "minimal") != "minimal":
        raise ValueError("The original GPT-5 mini partner requires minimal reasoning effort")
    if not environ.get("ANTHROPIC_API_KEY") or not environ.get("OPENAI_API_KEY"):
        raise ValueError(
            "The original partner/referee panel requires team-only ANTHROPIC_API_KEY and OPENAI_API_KEY"
        )
    name = "Qwen/Qwen3-14B"
    hosted = json.loads(environ.get("HARNESS_OPENAI_COMPAT") or "{}")
    local = json.loads(environ.get("HARNESS_VLLM_ENDPOINTS") or "{}")
    if not isinstance(hosted, dict) or not isinstance(local, dict):
        raise ValueError("Original role endpoint settings must be JSON objects")
    if name in hosted:
        entry = hosted[name]
        if not isinstance(entry, dict) or entry.get("model", name) not in {
            name,
            "qwen/qwen3-14b",
        }:
            raise ValueError("The original Qwen3-14B partner cannot be substituted")
        endpoint = entry.get("base_url")
        key = entry.get("api_key_env")
        if key not in {
            "CI_PARTNER_QWEN14_API_KEY",
            "OPENROUTER_API_KEY",
            "OPENAI_API_KEY",
            "HARNESS_VLLM_API_KEY",
        } or not environ.get(key):
            raise ValueError(
                "Hosted original Qwen3-14B requires one explicit team-forwarded key variable"
            )
        route = {
            "route": "original_openai_compat",
            "model": entry.get("model", name),
            "api_key_env": key,
        }
    else:
        endpoint = local.get(name)
        route = {
            "route": "original_vllm",
            "model": name,
            "api_key_env": "HARNESS_VLLM_API_KEY",
        }
    if not isinstance(endpoint, str):
        raise ValueError(
            "Configure the original Qwen/Qwen3-14B endpoint; the upstream localhost default cannot reach a model inside team"
        )
    parsed = urlsplit(endpoint)
    if (
        parsed.scheme not in {"https", "http"}
        or not parsed.hostname
        or parsed.username
        or parsed.password
        or parsed.query
        or parsed.fragment
    ):
        raise ValueError("Invalid original Qwen3-14B endpoint")
    try:
        loopback = ipaddress.ip_address(parsed.hostname).is_loopback
    except ValueError:
        loopback = parsed.hostname.lower() == "localhost"
    if loopback:
        raise ValueError(
            "Qwen3-14B must be reachable from the private team container, not its internal loopback bridge"
        )
    return {
        "partners": ["claude-haiku-4-5", "gpt-5-mini", name],
        "qwen14": {**route, "base_url": endpoint},
        "keys_exported": False,
    }


GATEWAY = "http://model-compat:8003"
PROVIDERS = {
    # provider: (default upstream base URL, private readout API)
    "google": ("https://generativelanguage.googleapis.com/v1beta/openai", "google-openai-chat"),
    "openai": ("https://api.openai.com/v1", "openai-responses"),
    "anthropic": ("https://api.anthropic.com/v1", "anthropic-messages"),
    "openai-compatible": (None, "openai-compat-chat"),
}


def provider_for(evaluated, environ):
    explicit = environ.get("CI_MODEL_PROVIDER")
    if explicit:
        if explicit not in PROVIDERS:
            raise ValueError(f"CI_MODEL_PROVIDER must be one of {sorted(PROVIDERS)}")
        return explicit
    if evaluated.startswith("gemini-"):
        return "google"
    if evaluated.startswith("claude-"):
        return "anthropic"
    if evaluated.startswith(("gpt-", "o1", "o3", "o4")):
        return "openai"
    return "openai-compatible"


def model_route(config, evaluated, environ):
    """The gateway upstream and private-readout settings for this recipe; no network."""
    from collab_harbor.model_gateway import validate_upstream

    provider = provider_for(evaluated, environ)
    default, readout_api = PROVIDERS[provider]
    upstream = (environ.get("CI_MODEL_UPSTREAM") or default or "").rstrip("/")
    if not upstream:
        raise ValueError("Set CI_MODEL_UPSTREAM to the inference endpoint base URL, including its /v1 prefix")
    validate_upstream(upstream)
    key_env = config.inference.api_key_env
    if key_env and not environ.get(key_env):
        raise ValueError(f"The evaluated model's key variable {key_env} is not set")
    return {
        "provider": provider,
        "upstream": upstream,
        "readout_api": readout_api,
        "effort": config.inference.reasoning_effort or "off",
        "key": environ.get(key_env) if key_env else "EMPTY",
    }


def validate_recipe(config, evaluated, version):
    """The fixed Full Pi protocol; the model and provider are free."""
    from collab_harbor.legion_config import API_FORMATS

    expected_base = GATEWAY if config.inference.api_format == "anthropic_messages" else GATEWAY + "/v1"
    if (
        getattr(config, "success_check", None) is not None
        or len(config.agents.roster()) != 1
        or getattr(config.inference, "endpoints", [expected_base]) != [expected_base]
        or getattr(config.inference, "hf_jobs", None) is not None
        or version != "1.5.0"
        or not evaluated
        or config.limits.agent_max_turns != 256
        or config.limits.run_timeout_seconds != 3600
        or config.limits.agent_timeout_seconds is not None
        or config.inference.api_format not in API_FORMATS
        or config.inference.base_url.rstrip("/") != expected_base
    ):
        raise ValueError(
            "This recipe requires one Pi 1.5.0 agent, no external success check, 256 turns, "
            "the one-hour run guard, no agent deadline, "
            f"and inference.base_url {expected_base} (the task-local model gateway)"
        )


def gateway_routing_headers(route, environ):
    """Non-secret routing headers for the task's model gateway (CI_MODEL_HEADERS).

    The operator's own CI_MODEL_HEADERS are validated and kept exactly (e.g. Hugging Face org billing,
    {"X-HF-Bill-To": "<org>"}); for Anthropic models the workspace header is added when not already set. Only the
    model-compat service reads them, so they apply to the evaluated model's calls (Pi and the private final
    answer) and never to the team's partner, judge or grader routes."""
    from collab_harbor.model_gateway import routing_headers

    headers = routing_headers(environ.get("CI_MODEL_HEADERS"))
    workspace = environ.get("ANTHROPIC_WORKSPACE_ID")
    if route["provider"] == "anthropic" and workspace:
        headers.setdefault("anthropic-workspace-id", workspace)
    return headers


def gateway_request_fields(environ):
    """Operator-chosen provider request options for the evaluated model's calls (CI_MODEL_BODY), validated; e.g.
    {"reasoning": {"enabled": false}} runs a model with thinking off, for Pi and the private final answer alike."""
    from collab_harbor.model_gateway import request_defaults

    return request_defaults(environ.get("CI_MODEL_BODY"))


def main():
    from collab_harbor.legion_config import Config, launcher

    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--config", type=Path, required=True)
    args = parser.parse_args()
    config = Config.load(args.config)
    evaluated, configuration = metadata(config)
    validate_recipe(config, evaluated, configuration["version"])
    configuration["original_roles"] = original_role_configuration(os.environ)
    route = model_route(config, evaluated, os.environ)
    gateway_headers = gateway_routing_headers(route, os.environ)
    gateway_fields = gateway_request_fields(os.environ)
    configuration["model_gateway"] = {
        "routing_headers": gateway_headers,
        "request_fields": gateway_fields,
        "provider": route["provider"],
        "upstream": route["upstream"],
        "private_readout_api": route["readout_api"],
    }
    configuration["task_local_model_compatibility"] = {
        "mode": "provider-neutral gateway; removes top-level store for Google only",
        "source_sha256": hashlib.sha256(
            Path(__file__).with_name("model_gateway.py").read_bytes()
        ).hexdigest(),
        "covers_internal_pi_compaction": True,
    }
    os.environ["CI_EVALUATED_MODEL"] = evaluated
    os.environ["CI_AGENT_CONFIGURATION"] = json.dumps(configuration, allow_nan=False)
    # Read by docker compose interpolation for model-compat (upstream) and team (readout).
    os.environ["CI_MODEL_UPSTREAM"] = route["upstream"]
    os.environ["CI_MODEL_HEADERS"] = json.dumps(gateway_headers)
    os.environ["CI_MODEL_BODY"] = json.dumps(gateway_fields)
    os.environ["CI_PRIVATE_READOUT_API"] = route["readout_api"]
    os.environ["CI_PRIVATE_READOUT_BASE_URL"] = GATEWAY + "/v1"
    os.environ["CI_PRIVATE_READOUT_EFFORT"] = route["effort"]
    os.environ["CI_PRIVATE_READOUT_API_KEY"] = route["key"]
    with launcher(config) as run_experiment:
        directory, exit_code = asyncio.run(run_experiment(config))
    print(f"Run manifest: {directory / 'run.json'}")
    return exit_code


if __name__ == "__main__":
    raise SystemExit(main())