"""A relay for the paid comparison model. It holds the API key in memory, so no harness file or command carries it. It forwards chat completions to OpenRouter, allows only the comparison model, asks OpenRouter for the cost of every call, adds it up, and refuses once the cap is reached. It logs counts and cost, never a prompt or a reply. It listens on 127.0.0.1 only and takes the key on stdin, so the key is never in a file, a command line or a log: printf '%s\n' "$KEY" | python tools/or_proxy.py --key-stdin --daemon --cap-usd 240 --ledger results/or_ledger.jsonl It does not stream: a request with "stream" set gets one whole reply (the agent harness does not stream). """ import argparse import http.client import json import os import ssl import threading import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer HOST = "openrouter.ai" LOCK = threading.Lock() STATE = {"spent": 0.0, "requests": 0, "errors": 0, "in_tok": 0, "out_tok": 0} ARGS = None KEY = None CTX = ssl.create_default_context() def upstream(method, path, body=None, timeout=900): conn = http.client.HTTPSConnection(HOST, timeout=timeout, context=CTX) headers = {"Authorization": f"Bearer {KEY}", "Content-Type": "application/json", "X-Title": "eval"} conn.request(method, path, body=body, headers=headers) r = conn.getresponse() data = r.read() conn.close() return r.status, data def ledger(line): with open(ARGS.ledger, "a", encoding="utf-8") as f: f.write(json.dumps(line) + "\n") class H(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def log_message(self, *a): pass def reply(self, code, obj): b = json.dumps(obj).encode() self.send_response(code) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(b))) self.end_headers() self.wfile.write(b) def do_GET(self): if self.path.rstrip("/") in ("/health", "/v1/health"): with LOCK: return self.reply(200, dict(STATE, cap=ARGS.cap_usd, model=ARGS.model)) if self.path.rstrip("/") == "/v1/models": return self.reply(200, {"object": "list", "data": [{"id": ARGS.model, "object": "model"}]}) self.reply(404, {"error": "not here"}) def do_POST(self): if not self.path.rstrip("/").endswith("/chat/completions"): return self.reply(404, {"error": "only chat completions"}) try: req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", "0")))) except Exception: return self.reply(400, {"error": "bad json"}) with LOCK: if STATE["spent"] >= ARGS.cap_usd: return self.reply(402, {"error": {"message": f"spend cap of USD {ARGS.cap_usd} reached", "type": "cap"}}) req["model"] = ARGS.model # the one comparison model, whatever the caller names req["stream"] = False req["usage"] = {"include": True} # OpenRouter then returns the cost of the call t0 = time.time() try: status, data = upstream("POST", "/api/v1/chat/completions", json.dumps(req).encode()) except Exception as e: with LOCK: STATE["errors"] += 1 ledger({"t": round(t0), "status": "relay_error", "kind": type(e).__name__}) return self.reply(502, {"error": {"message": f"relay: {type(e).__name__}", "type": "relay"}}) cost = in_tok = out_tok = 0 try: u = (json.loads(data).get("usage") or {}) cost, in_tok, out_tok = float(u.get("cost") or 0), int(u.get("prompt_tokens") or 0), int(u.get("completion_tokens") or 0) except Exception: pass with LOCK: STATE["requests"] += 1 STATE["spent"] += cost STATE["in_tok"] += in_tok STATE["out_tok"] += out_tok if status != 200: STATE["errors"] += 1 spent = STATE["spent"] ledger({"t": round(t0), "status": status, "s": round(time.time() - t0, 2), "in": in_tok, "out": out_tok, "cost": cost, "spent": round(spent, 4)}) self.send_response(status) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) def main(): global ARGS, KEY ap = argparse.ArgumentParser() ap.add_argument("--port", type=int, default=18811) ap.add_argument("--cap-usd", type=float, default=300.0) ap.add_argument("--model", default="", help="OpenRouter id; empty = find the Opus 5.5 id in the model list") ap.add_argument("--ledger", default="tmp/or_ledger.jsonl") ap.add_argument("--key-stdin", action="store_true", help="read the key from the first line of stdin: it is then only in this process's memory") ap.add_argument("--daemon", action="store_true") ap.add_argument("--log", default="logs/or_proxy.log") ARGS = ap.parse_args() if ARGS.key_stdin: # the key then exists only in this process's memory: no file, no argv, no env import sys KEY = sys.stdin.readline().strip() if not KEY: raise SystemExit("no key on stdin") else: KEY = os.environ["OPENROUTER_API_KEY"] if ARGS.daemon: # detach, so the SSH session that passed the key can end if os.fork() > 0: os._exit(0) os.setsid() if os.fork() > 0: os._exit(0) fd = os.open(ARGS.log, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) os.dup2(fd, 1) os.dup2(fd, 2) os.dup2(os.open(os.devnull, os.O_RDONLY), 0) os.makedirs(os.path.dirname(ARGS.ledger) or ".", exist_ok=True) # what this key is, without spending: label and limits only st, data = upstream("GET", "/api/v1/key", timeout=60) try: k = json.loads(data).get("data", {}) print("key check:", st, {x: k.get(x) for x in ("label", "limit", "limit_remaining", "usage", "is_free_tier", "is_provisioning_key")}, flush=True) except Exception: print("key check:", st, data[:200], flush=True) st, data = upstream("GET", "/api/v1/models", timeout=60) ids = {m["id"]: m for m in json.loads(data).get("data", [])} if st == 200 else {} if not ARGS.model: cand = sorted(i for i in ids if "opus" in i and ("5.5" in i or "5-5" in i)) print("opus 5.5 candidates:", cand, flush=True) ARGS.model = next((c for c in cand if ":" not in c), cand[0] if cand else "") m = ids.get(ARGS.model) print("model:", ARGS.model, "pricing:", (m or {}).get("pricing"), "context:", (m or {}).get("context_length"), flush=True) if not m: raise SystemExit("the comparison model is not in OpenRouter's list") with open(ARGS.ledger, "r", encoding="utf-8") if os.path.exists(ARGS.ledger) else open(os.devnull) as f: for line in f: try: STATE["spent"] += float(json.loads(line).get("cost") or 0) except Exception: pass print(f"relay on 127.0.0.1:{ARGS.port}, cap USD {ARGS.cap_usd}, already spent {STATE['spent']:.2f}", flush=True) ThreadingHTTPServer(("127.0.0.1", ARGS.port), H).serve_forever() if __name__ == "__main__": main()