RSIChallenge / auto-impl /scripts /x2p_codex_shim.py
Jerry999's picture
Add files using upload-large-folder tool
158258b verified
Raw History Blame Contribute Delete
3.73 kB
"""Expose the cluster's authenticated Codex gateway on sandbox-local HTTP.
The PostTrainBench sandbox has an empty network namespace. This relay accepts OpenAI Responses
API traffic from the Codex SDK on loopback and sends only that traffic through the bound
x2pagentd unix socket. x2pagentd injects the short-lived cluster credential; no user credential
or general network route enters the benchmark sandbox.
"""
import http.client
import os
import socket
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlsplit
UPSTREAM = os.environ.get(
"X2P_CODEX_UPSTREAM",
"http://azure-codex-gpt-5-6-sol-ptu.ai-gateway.x2p.facebook.net/openai/v1")
UPSTREAM_HOST = urlsplit(UPSTREAM).netloc
PROXY_UDS = os.environ["X2P_UDS"]
CAT_HEADER = os.environ.get(
"X2P_INJECT_CAT", "eyJ2ZXJpZmllciI6ICJtZXRhbWF0ZV9wbGF0Zm9ybS5wbHVnYm9h"
"cmQiLCAidG9rZW5UaW1lb3V0U2Vjb25kcyI6IDMwMCwgImlzTG93Qm94IjogdHJ1ZX0=")
HOP_BY_HOP = {"connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te",
"trailers", "transfer-encoding", "upgrade", "host", "content-length"}
class UnixConnection(http.client.HTTPConnection):
def connect(self) -> None:
self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sock.settimeout(self.timeout)
self.sock.connect(PROXY_UDS)
class Relay(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *args):
pass
def relay(self) -> None:
length = self.headers.get("Content-Length")
body = self.rfile.read(int(length)) if length else None
headers = {key: value for key, value in self.headers.items()
if key.lower() not in HOP_BY_HOP}
# http.client otherwise derives Host from the UnixConnection's synthetic "localhost".
# The forward proxy routes the absolute URI, while the gateway itself also validates Host.
headers["Host"] = UPSTREAM_HOST
headers["x-x2pagentd-inject-cat"] = CAT_HEADER
headers["X-Meta-AI-Gateway-Calling-Product"] = "codex:posttrainbench_sdk"
if body is not None:
headers["Content-Length"] = str(len(body))
upstream = UnixConnection("localhost", timeout=900)
try:
upstream.request(self.command, UPSTREAM + self.path, body=body, headers=headers)
response = upstream.getresponse()
self.send_response(response.status, response.reason)
for key, value in response.getheaders():
if key.lower() not in HOP_BY_HOP:
self.send_header(key, value)
content_length = response.getheader("Content-Length")
if content_length is not None:
self.send_header("Content-Length", content_length)
self.end_headers()
self.wfile.write(response.read())
else:
self.send_header("Transfer-Encoding", "chunked")
self.end_headers()
while chunk := response.read1(65536):
self.wfile.write(b"%x\r\n%s\r\n" % (len(chunk), chunk))
self.wfile.flush()
self.wfile.write(b"0\r\n\r\n")
self.wfile.flush()
except Exception as error:
self.send_error(502, explain=str(error))
finally:
upstream.close()
do_GET = do_POST = do_PUT = do_DELETE = do_PATCH = relay
def main() -> None:
port = int(sys.argv[1]) if len(sys.argv) > 1 else 0
server = ThreadingHTTPServer(("127.0.0.1", port), Relay)
print(server.server_address[1], flush=True)
server.serve_forever()
if __name__ == "__main__":
main()