#!/usr/bin/env python3 # zai-proxy — локальный мост Claude Desktop -> Z.ai. # # Зачем: приложение пускает в профиле только имена claude-*, а сервер Z.ai # по умолчанию маппит ЛЮБОЕ claude-имя на лёгкую модель (GLM-5.3-Flash), # даже если в подписке положен полный GLM-5.3. Прокси принимает запросы # приложения с claude-именами, переписывает модель и отправляет в Z.ai. # Слушает только 127.0.0.1. Ключ не хранит: заголовки авторизации проходят # насквозь из приложения. # # Маппинг: # claude-*-haiku* -> glm-5.3-flash # claude-* (прочие) -> glm-5.3 # Суффикс [1m] (1M-контекст) срезается: Z.ai не принимает его с glm-именами. import json import re import sys from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib import request as urlreq PORT = 8287 UPSTREAM_HOST = "api.z.ai" LOG_FILE = __file__ + ".log" def map_model(name): bare = re.sub(r"\[1m\]$", "", str(name or ""), flags=re.I) if re.match(r"^claude-(haiku|3-5-haiku|3-haiku)", bare): return "glm-5.3-flash" if bare.startswith("claude-"): return "glm-5.3" return None class Handler(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def log_message(self, *a): pass def _log(self, line): try: with open(LOG_FILE, "a", encoding="utf-8") as f: f.write(line + "\n") except Exception: pass def _handle(self): if self.path == "/health": body = b"ok" self.send_response(200) self.send_header("Content-Type", "text/plain") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) return length = int(self.headers.get("Content-Length") or 0) body = self.rfile.read(length) if length else b"" note = "(passthrough)" ctype = self.headers.get("Content-Type") or "" if body and "json" in ctype: try: j = json.loads(body.decode("utf-8")) if isinstance(j, dict) and isinstance(j.get("model"), str): to = map_model(j["model"]) if to: note = "%s -> %s" % (j["model"], to) j["model"] = to body = json.dumps(j, ensure_ascii=False).encode("utf-8") except Exception: pass headers = {k: v for k, v in self.headers.items() if k.lower() not in ("host", "content-length", "transfer-encoding", "connection")} req = urlreq.Request("https://%s%s" % (UPSTREAM_HOST, self.path), data=body or None, headers=headers, method=self.command) try: resp = urlreq.urlopen(req, timeout=600) except urlreq.HTTPError as e: resp = e except Exception as e: self._log("%s %s %s -> UPSTREAM ERROR %s" % (self.command, self.path, note, e)) payload = json.dumps({"type": "error", "error": {"type": "proxy_error", "message": str(e)}}).encode("utf-8") self.send_response(502) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(payload))) self.end_headers() self.wfile.write(payload) return self._log("%s %s %s -> %s" % (self.command, self.path, note, resp.status if hasattr(resp, "status") else resp.code)) self.send_response(resp.status if hasattr(resp, "status") else resp.code) chunked = False for k, v in resp.headers.items(): if k.lower() in ("transfer-encoding", "content-length", "connection"): if k.lower() == "transfer-encoding" and "chunked" in v.lower(): chunked = True continue self.send_header(k, v) if chunked: self.send_header("Transfer-Encoding", "chunked") self.end_headers() try: while True: chunk = resp.read(8192) if not chunk: break if chunked: self.wfile.write(("%x\r\n" % len(chunk)).encode() + chunk + b"\r\n") self.wfile.flush() else: self.wfile.write(chunk) self.wfile.flush() if chunked: self.wfile.write(b"0\r\n\r\n") except Exception: pass do_GET = do_POST = do_PUT = do_DELETE = do_OPTIONS = _handle def main(): srv = ThreadingHTTPServer(("127.0.0.1", PORT), Handler) print("zai-proxy: listening on 127.0.0.1:%d -> https://%s" % (PORT, UPSTREAM_HOST), file=sys.stderr) srv.serve_forever() if __name__ == "__main__": main()