Datasets:

Modalities:
Text
Languages:
English
Size:
< 1K
ArXiv:
Libraries:
Datasets
Harbor
License:
File size: 21,935 Bytes
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9653a0f
 
 
5873600
b710f09
 
 
 
a9b5504
 
 
 
5873600
4fea7d1
 
417265e
 
4fea7d1
5873600
 
b710f09
5873600
 
 
 
 
 
 
 
 
4fea7d1
 
5873600
4fea7d1
5873600
 
 
 
 
 
 
 
 
 
b710f09
 
 
 
5873600
 
 
 
 
 
 
 
9653a0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fea7d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5873600
417265e
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a9b5504
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5873600
 
 
 
 
 
 
9653a0f
 
5873600
 
 
 
 
 
 
 
 
 
a9b5504
5873600
 
a9b5504
5873600
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b710f09
 
 
 
 
5873600
 
 
b710f09
5873600
 
 
 
 
 
 
a9b5504
5873600
 
 
 
 
 
 
 
 
 
 
 
b710f09
 
5873600
 
417265e
 
 
 
 
4fea7d1
 
 
 
 
0082d1f
 
 
 
4fea7d1
 
0082d1f
 
 
 
 
b710f09
4fea7d1
 
 
 
 
 
 
0082d1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4fea7d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5873600
4fea7d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
417265e
 
 
 
b710f09
417265e
 
 
 
4fea7d1
 
 
 
 
b710f09
4fea7d1
 
 
0082d1f
5873600
 
 
 
0082d1f
 
5873600
 
0082d1f
4fea7d1
5873600
 
 
 
 
 
 
 
 
 
 
 
 
a9b5504
 
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
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
"""Task-local model gateway: the evaluated agent's only route to its model provider.

The agent container has no internet during its run (Harbor allowlist: team and
model-compat). Pi sends every model request here, and so does the team
service's private final-answer readout. The gateway forwards each request,
unchanged except as noted, to one configured upstream:

* ``CI_MODEL_UPSTREAM`` (default: Google's OpenAI-compatible endpoint), the
  provider base URL including its version prefix, e.g.
  ``https://api.openai.com/v1``, ``https://api.anthropic.com/v1`` or an
  inference endpoint's ``https://.../v1``.
* Paths ``/v1/chat/completions``, ``/v1/responses`` and ``/v1/messages`` map to
  ``<upstream>/chat/completions``, ``/responses`` and ``/messages``.
* The only body change: for Google's endpoint, drop the optional top-level
  ``store`` field (also in Pi's internal compaction calls), which Google rejects.
* ``CI_MODEL_NAME`` pins the evaluated model: any other ``model`` is rejected, so
  the agent cannot use the gateway to reach a different model.
* Only client-executed function tools pass. Provider-side tools (web search, web
  fetch, MCP, code containers) are rejected: they would let the agent reach the
  internet through the provider despite the network allowlist.
* Remote content references are rejected too (``image_url``/``file_url``/... pointing
  anywhere but an inline ``data:`` URI, Anthropic ``source: {type: url}``): the provider
  would fetch them on the agent's behalf. URLs inside plain text are not fetched.
* ``CI_MODEL_HEADERS`` (JSON) may add non-secret routing headers the caller did
  not send; only ``anthropic-workspace-id``, ``openai-organization``,
  ``openai-project`` and ``x-hf-bill-to`` are accepted (an unscoped Anthropic key
  needs the first). ``x-hf-bill-to`` (Hugging Face org billing) is operator-only:
  a caller's own copy is removed and only the configured value is sent.
* ``CI_MODEL_BODY`` (JSON object) adds operator-chosen provider request options to
  every evaluated-model call, Pi's and the private final answer's alike, e.g.
  ``{"reasoning": {"enabled": false}}`` to run a model with thinking off. Operator
  values win; the model, conversation, tools and streaming cannot be set this way.

* A streamed request whose provider is slow (more than 3 s) is answered with a 200 event
  stream and keepalive comments until the provider responds (see ``STREAM_KEEPALIVE``):
  Harbor's agent egress proxy otherwise drops it after ~15 s of silence. The gateway
  always asks the provider for uncompressed bytes (``Accept-Encoding: identity``).

No credentials are owned or stored (the caller's auth headers pass through), no
content is logged, and nothing is retried: an ambiguous upstream attempt stays
ambiguous.
"""

from __future__ import annotations

import argparse
import http.client
import ipaddress
import json
import os
import select
import socket
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlsplit

GOOGLE = "https://generativelanguage.googleapis.com/v1beta/openai"
GOOGLE_HOST = "generativelanguage.googleapis.com"
ROUTES = {
    "/v1/chat/completions": "/chat/completions",
    "/v1/responses": "/responses",
    "/v1/messages": "/messages",
}
ROUTING_HEADERS = {"anthropic-workspace-id", "openai-organization", "openai-project", "x-hf-bill-to"}
# Set only by the operator (CI_MODEL_HEADERS): a caller's own copy is always removed, so the agent cannot choose
# which organization is billed.
OPERATOR_ONLY_HEADERS = {"x-hf-bill-to"}
MAX_BODY = 32 * 1024 * 1024
# Request fields that make the provider fetch or run things server-side.
SERVER_SIDE_FIELDS = {"web_search_options", "mcp_servers", "container", "search_parameters"}
CLIENT_TOOL_TYPES = {
    "/v1/chat/completions": {"function"},
    "/v1/responses": {"function", "custom"},
    "/v1/messages": {None, "custom"},  # Anthropic client tools have no type (or "custom")
}
REMOTE_KEYS = {"image_url", "file_url", "audio_url", "video_url", "document_url"}


def remote_reference(value):
    """True if the request asks the provider to fetch content from a URL."""
    if isinstance(value, dict):
        if value.get("type") == "url" and isinstance(value.get("url"), str):
            return True  # Anthropic image/document source
        for key, item in value.items():
            if key in REMOTE_KEYS:
                url = item.get("url") if isinstance(item, dict) else item
                if isinstance(url, str) and not url.startswith("data:"):
                    return True
            if remote_reference(item):
                return True
    elif isinstance(value, list):
        return any(remote_reference(item) for item in value)
    return False


# Harbor's agent-phase egress proxy (gost, HTTP sniffing) drops a proxied connection that stays
# silent for ~15 s. A streamed request whose provider has not answered after STREAM_COMMIT_AFTER
# seconds gets a 200 event stream at once, then SSE comment lines every STREAM_KEEPALIVE seconds
# until the provider answers; the provider's stream is then relayed unchanged. A late provider
# error becomes the stream error event of that API. Fast answers (and all errors that arrive
# within STREAM_COMMIT_AFTER) are relayed exactly as before, status code included.
STREAM_COMMIT_AFTER = 3.0
STREAM_KEEPALIVE = 5.0
CLIENT_POLL = 0.5  # how often a waiting request checks that its caller is still connected


def client_gone(sock):
    """True once the caller closed its connection (readable with EOF) while we wait for the provider."""
    try:
        readable, _, _ = select.select([sock], [], [], 0)
        return bool(readable) and sock.recv(1, socket.MSG_PEEK) == b""
    except OSError:
        return True


def stream_error(path, message, status=None):
    """One SSE error event in the format the API's official SDK raises on."""
    if path == "/v1/messages":
        body = {"type": "error", "error": {"type": "api_error", "message": message}}
        return b"event: error\ndata: " + json.dumps(body).encode() + b"\n\n"
    if path == "/v1/responses":
        # Official ResponseErrorEvent fields, plus an "error" object: the Python SDK raises only on that key.
        body = {"type": "error", "code": str(status or "upstream_error"), "message": message, "param": None,
                "error": {"type": "upstream_error", "code": str(status or "upstream_error"), "message": message}}
        return b"event: error\ndata: " + json.dumps(body).encode() + b"\n\n"
    body = {"error": {"message": message, "type": "upstream_error", "code": status}}
    return b"data: " + json.dumps(body).encode() + b"\n\n"


HOP_BY_HOP = {
    "host", "content-length", "connection", "transfer-encoding", "keep-alive", "accept-encoding",
    "proxy-authorization", "proxy-connection", "upgrade", "te", "trailer",
}


def validate_upstream(upstream, *, fixture=False):
    """Return the parsed upstream; reject credentials, queries and fixture-only routes."""
    parsed = urlsplit(upstream)
    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("Model upstream must be a plain http(s) base URL without credentials")
    try:
        loopback = ipaddress.ip_address(parsed.hostname).is_loopback
    except ValueError:
        loopback = parsed.hostname.lower() == "localhost"
    if loopback and not fixture:
        raise ValueError("A loopback model upstream is restricted to explicit local fixtures")
    if parsed.hostname == GOOGLE_HOST and parsed.scheme != "https":
        raise ValueError("Google requires TLS")
    return parsed


def routing_headers(value):
    """Parse CI_MODEL_HEADERS: a JSON object of allowlisted, non-secret routing headers."""
    headers = json.loads(value or "{}")
    if (not isinstance(headers, dict)
            or any(not isinstance(k, str) or k.lower() not in ROUTING_HEADERS for k in headers)
            or any(not isinstance(v, str) or not v or any(c in v for c in "\r\n") for v in headers.values())):
        raise ValueError(f"CI_MODEL_HEADERS accepts only {sorted(ROUTING_HEADERS)} with plain string values")
    return {k.lower(): v for k, v in headers.items()}


# Fields a CI_MODEL_BODY default may never set: what the agent sends, what it may call, how the reply is delivered,
# and the output budgets (Pi's and Stanford's private final-answer budgets stay exactly as their callers set them).
PROTECTED_BODY_FIELDS = {"model", "messages", "input", "system", "instructions", "tools", "tool_choice", "functions",
                         "function_call", "stream", "stream_options", "previous_response_id", "conversation",
                         "max_tokens", "max_completion_tokens", "max_output_tokens"}


def request_defaults(value):
    """Parse CI_MODEL_BODY: a JSON object of provider request options the operator adds to every evaluated-model call,
    e.g. {"reasoning": {"enabled": false}} to run a model with thinking off. Operator values win over the caller's;
    the conversation, tools, model and streaming are never touched, and nothing here can make the provider fetch
    remote content or run tools."""
    fields = json.loads(value or "{}")
    if (not isinstance(fields, dict) or any(not isinstance(k, str) or not k for k in fields)
            or PROTECTED_BODY_FIELDS & set(fields) or SERVER_SIDE_FIELDS & set(fields) or remote_reference(fields)):
        raise ValueError("CI_MODEL_BODY must be a JSON object of provider options; it cannot set "
                         f"{sorted(PROTECTED_BODY_FIELDS | SERVER_SIDE_FIELDS)} or remote references")
    return fields


def compatible_body(value, upstream=GOOGLE, *, path="/v1/chat/completions", model=None):
    if not isinstance(value, dict) or not isinstance(value.get("model"), str) or not value["model"]:
        raise ValueError("A JSON request with a model name is required")
    if model and value["model"] != model:
        raise ValueError("The gateway serves only the evaluated model")
    if SERVER_SIDE_FIELDS & set(value):
        raise ValueError("Provider-side search/fetch/execution fields are not allowed")
    if remote_reference({k: v for k, v in value.items() if k != "tools"}):
        raise ValueError("Remote content references (URLs the provider would fetch) are not allowed")
    tools = value.get("tools") or []
    if not isinstance(tools, list) or any(
            not isinstance(tool, dict) or tool.get("type") not in CLIENT_TOOL_TYPES[path] for tool in tools):
        raise ValueError("Only client-executed function tools are allowed")
    if urlsplit(upstream).hostname == GOOGLE_HOST:
        return {key: item for key, item in value.items() if key != "store"}
    return value


def server(upstream=GOOGLE, *, host="0.0.0.0", port=8003, fixture=False, audit=None, extra_headers=None,
           model=None, extra_body=None):
    parsed = validate_upstream(upstream, fixture=fixture)
    extra_headers = routing_headers(json.dumps(extra_headers or {}))
    extra_body = request_defaults(json.dumps(extra_body or {}))
    base_path = parsed.path.rstrip("/")
    lock = threading.Lock()

    class Handler(BaseHTTPRequestHandler):
        def log_message(self, *_args):
            pass

        def do_GET(self):
            if self.path != "/health":
                self.send_error(404)
                return
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(b'{"ok":true}')

        def do_POST(self):
            # Route on the path; a query string (the Anthropic SDK's beta client sends /v1/messages?beta=true)
            # is forwarded to the provider unchanged.
            request_url = urlsplit(self.path)
            route = request_url.path
            target = ROUTES.get(route)
            if target is None:
                self.send_error(404)
                return
            forwarded_path = base_path + target + ("?" + request_url.query if request_url.query else "")
            try:
                if self.headers.get("Transfer-Encoding") or not self.headers.get("Content-Length"):
                    raise ValueError("A complete JSON Content-Length body is required")
                length = int(self.headers["Content-Length"])
                if not 0 < length <= MAX_BODY:
                    raise ValueError("Request body size out of bounds")
                incoming = json.loads(self.rfile.read(length))
                outgoing = {**compatible_body(incoming, upstream, path=route, model=model), **extra_body}
                payload = json.dumps(outgoing, ensure_ascii=False, allow_nan=False).encode()
            except (ValueError, TypeError):
                self.send_error(400, "Unsupported model gateway request")
                return
            if audit is not None:
                if not fixture:
                    raise RuntimeError("Provider body capture is forbidden outside fixtures")
                with lock:
                    audit(incoming, outgoing)
            connection = (
                http.client.HTTPSConnection if parsed.scheme == "https" else http.client.HTTPConnection
            )(parsed.hostname, parsed.port, timeout=None)
            headers = {key: value for key, value in self.headers.items()
                       if key.lower() not in HOP_BY_HOP and key.lower() not in OPERATOR_ONLY_HEADERS}
            sent = {key.lower() for key in headers}
            headers.update({key: value for key, value in extra_headers.items() if key not in sent})
            headers.update({"Content-Length": str(len(payload)), "Content-Type": "application/json",
                            # Plain bytes from the provider (the caller's Accept-Encoding is dropped above): a
                            # slow stream is answered with the gateway's own headers, so a provider
                            # Content-Encoding (Google gzips streams on request) could not be passed on.
                            "Accept-Encoding": "identity"})
            # The upstream call runs in a worker so a slow streamed answer can be kept alive (see
            # STREAM_KEEPALIVE): Harbor's agent egress proxy drops a connection that stays silent ~15 s.
            result = {}
            done = threading.Event()

            abort_lock = threading.Lock()
            provider_sock = {}  # the raw provider socket; http.client hands it to the response when the body has
            # no Content-Length (streams), after which connection.sock is None

            def call():
                try:
                    connection.connect()
                    with abort_lock:
                        provider_sock["sock"] = connection.sock
                        if provider_sock.get("aborted"):
                            raise ConnectionAbortedError("caller disconnected before the request was sent")
                    connection.request("POST", forwarded_path, payload, headers)
                    result["response"] = connection.getresponse()
                except (OSError, http.client.HTTPException) as error:
                    result["error"] = error
                finally:
                    done.set()

            def abort_upstream():
                # Shut the provider socket down (not just close it) so a read blocked in another thread returns
                # and the provider sees the disconnect and can stop a generation nobody will read.
                with abort_lock:
                    provider_sock["aborted"] = True
                    sock = provider_sock.get("sock") or connection.sock
                    if sock is not None:
                        try:
                            sock.shutdown(socket.SHUT_RDWR)
                        except OSError:
                            pass
                    connection.close()

            relay_done = threading.Event()

            def watch_caller():
                # While the provider's body is relayed, a caller hang-up is otherwise noticed only at the next
                # write, which may never come if the provider stalls: check the caller every CLIENT_POLL s.
                while not relay_done.wait(CLIENT_POLL):
                    if client_gone(self.connection):
                        abort_upstream()
                        return

            def wait_upstream(seconds=None):
                """Wait for the provider; False if the caller hung up first (the upstream is then aborted)."""
                deadline = None if seconds is None else time.monotonic() + seconds
                while not done.is_set():
                    step = CLIENT_POLL if deadline is None else min(CLIENT_POLL, deadline - time.monotonic())
                    if step <= 0:
                        return True
                    if done.wait(step):
                        break
                    if client_gone(self.connection):
                        raise ConnectionAbortedError("caller disconnected")
                return True

            threading.Thread(target=call, daemon=True).start()
            try:
                streamed = incoming.get("stream") is True
                wait_upstream(STREAM_COMMIT_AFTER if streamed else None)
                if done.is_set() or not streamed:
                    wait_upstream()
                    if "error" in result:
                        # No retry: an ambiguous upstream attempt stays ambiguous.
                        self.close_connection = True
                        return
                    response = result["response"]
                    self.send_response(response.status, response.reason)
                    for key, value in response.getheaders():
                        if key.lower() not in {"transfer-encoding", "connection", "keep-alive", "content-length"}:
                            self.send_header(key, value)
                    self.send_header("Connection", "close")
                    self.end_headers()
                else:
                    # Slow streamed answer: commit an event stream now and send SSE comments (ignored
                    # by every SSE client) until the provider answers.
                    self.send_response(200)
                    self.send_header("Content-Type", "text/event-stream")
                    self.send_header("Cache-Control", "no-cache")
                    self.send_header("Connection", "close")
                    self.end_headers()
                    self.wfile.flush()
                    while not done.is_set():
                        wait_upstream(STREAM_KEEPALIVE)
                        if not done.is_set():
                            self.wfile.write(b": keepalive\n\n")
                            self.wfile.flush()
                    response = result.get("response")
                    encoding = (response.getheader("Content-Encoding") or "identity").strip().lower() if response else ""
                    if response is not None and response.status == 200 and encoding != "identity":
                        # Our headers are already sent without Content-Encoding: never relay bytes the caller
                        # cannot decode; fail visibly instead.
                        self.wfile.write(stream_error(route, f"Upstream sent Content-Encoding {encoding!r} "
                                                                 "despite Accept-Encoding: identity", 502))
                        self.wfile.flush()
                        self.close_connection = True
                        return
                    if response is None or response.status != 200:
                        status = getattr(response, "status", None)
                        detail = response.read(4096).decode("utf-8", "replace") if response is not None else ""
                        message = (f"Upstream HTTP {status}: {detail}" if response is not None
                                   else f"Upstream connection error: {type(result.get('error')).__name__}")
                        self.wfile.write(stream_error(route, message, status))
                        self.wfile.flush()
                        self.close_connection = True
                        return
                threading.Thread(target=watch_caller, daemon=True).start()
                while data := response.read1(65536):
                    self.wfile.write(data)
                    self.wfile.flush()
                self.close_connection = True
            except (OSError, http.client.HTTPException, ValueError):
                # ValueError: the watchdog closed the upstream response under a blocked read.
                self.close_connection = True
            finally:
                relay_done.set()
                abort_upstream()

    return ThreadingHTTPServer((host, port), Handler)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--host", default="0.0.0.0")
    parser.add_argument("--port", type=int, default=8003)
    parser.add_argument("--fixture-upstream", help="Explicit local mock only")
    args = parser.parse_args()
    upstream = args.fixture_upstream or os.environ.get("CI_MODEL_UPSTREAM") or GOOGLE
    owned = server(upstream, host=args.host, port=args.port, fixture=bool(args.fixture_upstream),
                   extra_headers=routing_headers(os.environ.get("CI_MODEL_HEADERS")),
                   model=os.environ.get("CI_MODEL_NAME") or None,
                   extra_body=request_defaults(os.environ.get("CI_MODEL_BODY")))
    print(json.dumps({"ready": True, "port": owned.server_port, "fixture": bool(args.fixture_upstream),
                      "upstream_host": urlsplit(upstream).hostname}), flush=True)
    owned.serve_forever()


if __name__ == "__main__":
    main()