From 3c694d1d0459c34a3a6a9e6a1edf9d2e263708e7 Mon Sep 17 00:00:00 2001 From: NEXT579 Date: Tue, 20 Oct 2026 10:49:40 +0300 Subject: [PATCH] =?UTF-8?q?Z.ai:=20=D0=BB=D0=BE=D0=BA=D0=B0=D0=BB=D1=8C?= =?UTF-8?q?=D0=BD=D1=8B=D0=B9=20=D0=BF=D1=80=D0=BE=D0=BA=D1=81=D0=B8=20?= =?UTF-8?q?=D0=BF=D1=80=D0=BE=D1=82=D0=B8=D0=B2=20=D1=81=D0=BA=D1=80=D1=8B?= =?UTF-8?q?=D1=82=D0=BE=D0=B9=20=D0=BF=D0=BE=D0=B4=D0=BC=D0=B5=D0=BD=D1=8B?= =?UTF-8?q?=20GLM-5.3=20=D0=BD=D0=B0=20Flash?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Сервер Z.ai маппит любые claude-имена на GLM-5.3-Flash, даже на подписке с полным GLM-5.3; профиль при этом обязан использовать claude-имена, иначе приложение их не принимает. Решение: локальный прокси 127.0.0.1:8287 переписывает модель перед отправкой (sonnet/opus -> glm-5.3, haiku -> glm-5.3-flash, [1m] срезается). - setup.sh: мак — python3-прокси + LaunchAgent, вин (Git Bash) — PowerShell-прокси + задача планировщика; порт занят = пропускаем - setup.ps1: то же для вин нативно (HttpListener + schtasks ONLOGON) - профиль zai-glm ведёт на http://127.0.0.1:8287/api/anthropic; существующий профиль с ключом апгрейдится с сохранением ключа - restore снимает автостарт и глушит прокси - zai-proxy.py / zai-proxy.ps1 в репе — каноничные копии кода --- setup.ps1 | 139 +++++++++++++++++++++++++- setup.sh | 262 +++++++++++++++++++++++++++++++++++++++++++++++++- zai-proxy.ps1 | 108 +++++++++++++++++++++ zai-proxy.py | 131 +++++++++++++++++++++++++ 4 files changed, 632 insertions(+), 8 deletions(-) create mode 100644 zai-proxy.ps1 create mode 100644 zai-proxy.py diff --git a/setup.ps1 b/setup.ps1 index 8581c11..914f2cc 100644 --- a/setup.ps1 +++ b/setup.ps1 @@ -294,11 +294,129 @@ function Restart-Claude { } } +# ---------- Локальный прокси Z.ai ---------- +# Зачем: приложение пускает в профиле только имена claude-*, а сервер Z.ai +# маппит ЛЮБОЕ claude-имя на лёгкую GLM-5.3-Flash, даже на подписке с полным +# GLM-5.3. Прокси на 127.0.0.1:8287 переписывает модель перед отправкой: +# claude-* (не haiku) -> glm-5.3, claude-*-haiku* -> glm-5.3-flash, [1m] срезается. +# Ключ прокси не хранит: заголовки авторизации проходят из приложения насквозь. +# Код прокси продублирован файлом zai-proxy.ps1 в репозитории; здесь он встроен, +# потому что скрипт запускают через irm | iex. + +$ProxyPort = 8287 +$ProxyDir = Join-Path $env:LOCALAPPDATA "claude-brains" +$ProxyTask = "claude-brains-zai-proxy" + +function Test-ProxyUp { + try { (Invoke-WebRequest -UseBasicParsing -TimeoutSec 3 "http://127.0.0.1:$ProxyPort/health").StatusCode -eq 200 } + catch { $false } +} + +function Install-ZaiProxy { + if (Test-ProxyUp) { Ok "Локальный прокси Z.ai уже работает на :$ProxyPort."; return } + New-Item -ItemType Directory -Force -Path $ProxyDir | Out-Null + Write-Utf8 (Join-Path $ProxyDir "zai-proxy.ps1") @' +# zai-proxy (Windows) - локальный мост Claude Desktop -> Z.ai. +# Слушает только 127.0.0.1. Ключ не хранит: заголовки проходят насквозь. +# claude-* (не haiku) -> glm-5.3, claude-*-haiku* -> glm-5.3-flash, [1m] срезается. +$ErrorActionPreference = "Stop" +$Port = 8287 +$Upstream = "https://api.z.ai" +$LogFile = Join-Path $PSScriptRoot "zai-proxy.log" +function Write-Log($line) { try { Add-Content -Path $LogFile -Value "$(Get-Date -Format o) $line" -Encoding UTF8 } catch { } } +function Map-Model([string]$name) { + $bare = $name -replace '\[1m\]$','' + if ($bare -match '^claude-(haiku|3-5-haiku|3-haiku)') { return "glm-5.3-flash" } + if ($bare -like 'claude-*') { return "glm-5.3" } + return $null +} +Add-Type -AssemblyName System.Net.Http +$listener = New-Object System.Net.HttpListener +$listener.Prefixes.Add("http://127.0.0.1:${Port}/") +$listener.Start() +Write-Log "listening on 127.0.0.1:$Port -> $Upstream" +$client = New-Object System.Net.Http.HttpClient +$client.Timeout = [TimeSpan]::FromMinutes(10) +while ($listener.IsListening) { + $ctx = $listener.GetContext() + try { + $req = $ctx.Request; $res = $ctx.Response + if ($req.Url.AbsolutePath -eq "/health") { + $b = [Text.Encoding]::UTF8.GetBytes("ok") + $res.ContentType = "text/plain"; $res.ContentLength64 = $b.Length + $res.OutputStream.Write($b, 0, $b.Length); $res.Close(); continue + } + $bodyBytes = $null + if ($req.HasEntityBody) { + $ms = New-Object IO.MemoryStream + $req.InputStream.CopyTo($ms); $bodyBytes = $ms.ToArray() + } + $note = "(passthrough)" + if ($bodyBytes -and $req.ContentType -and $req.ContentType -match 'json') { + $text = [Text.Encoding]::UTF8.GetString($bodyBytes) + $m = [regex]::Match($text, '"model"\s*:\s*"([^"]+)"') + if ($m.Success) { + $to = Map-Model $m.Groups[1].Value + if ($to) { + $note = "$($m.Groups[1].Value) -> $to" + $text = $text.Substring(0, $m.Index) + '"model": "' + $to + '"' + $text.Substring($m.Index + $m.Length) + $bodyBytes = [Text.Encoding]::UTF8.GetBytes($text) + } + } + } + $up = New-Object System.Net.Http.HttpRequestMessage([System.Net.Http.HttpMethod]::new($req.HttpMethod), ($Upstream + $req.Url.PathAndQuery)) + if ($bodyBytes) { + $up.Content = New-Object System.Net.Http.ByteArrayContent(,$bodyBytes) + $up.Content.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse($req.ContentType) + } + foreach ($h in $req.Headers) { + if ($h.Key -in @("Host","Content-Length","Transfer-Encoding","Connection","Content-Type","Accept-Encoding")) { continue } + try { $up.Headers.TryAddWithoutValidation($h.Key, $h.Value) | Out-Null } catch { } + } + $urs = $client.SendAsync($up, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead).GetAwaiter().GetResult() + Write-Log "$($req.HttpMethod) $($req.Url.PathAndQuery) $note -> $([int]$urs.StatusCode)" + $res.StatusCode = [int]$urs.StatusCode + $res.ContentType = if ($urs.Content.Headers.ContentType) { $urs.Content.Headers.ContentType.ToString() } else { "application/octet-stream" } + $res.SendChunked = $true + $stream = $urs.Content.ReadAsStreamAsync().GetAwaiter().GetResult() + $buf = New-Object byte[] 8192 + while (($n = $stream.Read($buf, 0, $buf.Length)) -gt 0) { + $res.OutputStream.Write($buf, 0, $n); $res.OutputStream.Flush() + } + $res.Close() + } catch { + Write-Log "ERROR $($_.Exception.Message)" + try { $ctx.Response.Close() } catch { } + } +} +'@ + $proxyPath = Join-Path $ProxyDir "zai-proxy.ps1" + $rc = Invoke-Quiet schtasks /Create /F /TN $ProxyTask /TR "powershell.exe -NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$proxyPath`"" /SC ONLOGON + if ($rc -ne 0) { Warn "Не смог создать задачу автозапуска прокси."; return } + $rc = Invoke-Quiet schtasks /Run /TN $ProxyTask + $i = 0 + while (-not (Test-ProxyUp) -and $i -lt 10) { Start-Sleep 1; $i++ } + if (Test-ProxyUp) { + Ok "Локальный прокси Z.ai запущен на :$ProxyPort (полный GLM-5.3, автостарт прописан)." + } else { + Warn "Прокси не поднялся за 10 секунд. Профиль указывает на 127.0.0.1:$ProxyPort." + Write-Host " Проверь лог $ProxyDir\zai-proxy.log и задачу $ProxyTask в планировщике." + } +} + +function Remove-ZaiProxy { + $null = Invoke-Quiet schtasks /Delete /F /TN $ProxyTask + Get-CimInstance Win32_Process -Filter "Name='powershell.exe'" -ErrorAction SilentlyContinue | + Where-Object { $_.CommandLine -like "*zai-proxy.ps1*" } | + ForEach-Object { Invoke-Quiet taskkill /PID $_.ProcessId /F | Out-Null } +} + # ---------- ОТКАТ ---------- if ($Mode -eq "restore") { Say "Откат на родного Claude..." if (-not (Test-Path (Join-Path $LIB "_meta.json"))) { Ok "Конфигов нет, откатывать нечего."; return } Merge-Meta "default" "none" + Remove-ZaiProxy Repair-JsonBom Ok "Применён пустой профиль Default." Write-Host " Если приложение всё равно открывается на чужом мозге: меню аккаунта внизу слева -> Sign out," @@ -440,22 +558,33 @@ if ($brain -eq "ollama" -or $brain -eq "both") { } if ($brain -eq "zai" -or $brain -eq "both") { + Install-ZaiProxy $zaiPath = Join-Path $LIB "$ID_ZAI.json" $zaiHasKey = (Test-Path $zaiPath) -and -not ((Get-Content $zaiPath -Raw -Encoding UTF8) -match $ZAI_PLACEHOLDER) if ($zaiHasKey) { - Ok "Конфиг zai-glm уже настроен, ключ не трогаю." + # Конфиг уже с ключом: переводим его на локальный прокси, ключ сохраняем. + # Без прокси Z.ai маппит claude-имена на лёгкую модель (GLM-5.3-Flash) + # даже на подписке с полным GLM-5.3. + $zai = Read-Json $zaiPath + if ($zai.inferenceGatewayBaseUrl -ne "http://127.0.0.1:8287/api/anthropic") { + $zai.inferenceGatewayBaseUrl = "http://127.0.0.1:8287/api/anthropic" + Write-Utf8 $zaiPath ($zai | ConvertTo-Json -Depth 6) + Ok "Конфиг zai-glm переведён на локальный прокси, ключ сохранён." + } else { + Ok "Конфиг zai-glm уже настроен, ключ не трогаю." + } } else { Write-Utf8 $zaiPath @" { "inferenceProvider": "gateway", - "inferenceGatewayBaseUrl": "https://api.z.ai/api/anthropic", + "inferenceGatewayBaseUrl": "http://127.0.0.1:8287/api/anthropic", "inferenceGatewayApiKey": "$ZAI_PLACEHOLDER", "inferenceGatewayAuthScheme": "bearer", "inferenceCredentialKind": "static", "modelDiscoveryEnabled": false, "inferenceModels": [ - { "name": "claude-sonnet-4-6", "labelOverride": "GLM-5.3 (Z.ai Coding Plan)", "anthropicFamilyTier": "sonnet", "isFamilyDefault": true }, - { "name": "claude-haiku-4-5", "labelOverride": "GLM-5.3 Flash (Z.ai)", "anthropicFamilyTier": "haiku", "isFamilyDefault": true } + { "name": "claude-sonnet-4-6", "labelOverride": "GLM-5.3 (Z.ai Coding Plan)", "supports1m": true, "prefer1m": true, "anthropicFamilyTier": "sonnet", "isFamilyDefault": true }, + { "name": "claude-haiku-4-5", "labelOverride": "GLM-5.3 Flash (Z.ai)", "supports1m": true, "prefer1m": true, "anthropicFamilyTier": "haiku", "isFamilyDefault": true } ] } "@ @@ -487,6 +616,8 @@ if ($haveOllama) { Write-Host " · Программа Ollama должна быть запущена: закрыл её, мост отвалился." } if ($brain -eq "zai" -or $brain -eq "both") { + Write-Host " · Z.ai идёт через локальный прокси (127.0.0.1:8287): без него Z.ai молча" + Write-Host " подменяет полный GLM-5.3 на Flash-вариант. Прокси стартует сам, лог: $ProxyDir\zai-proxy.log." Write-Host " · Z.ai: возьми ключ на z.ai/manage-apikey/apikey-list, затем в приложении" Write-Host " Developer -> Configure Third-Party Inference -> конфигурация zai-glm ->" Write-Host " вставь ключ в Gateway API key -> Apply Changes -> перезапусти Claude." diff --git a/setup.sh b/setup.sh index b848e52..6365aa1 100644 --- a/setup.sh +++ b/setup.sh @@ -399,11 +399,246 @@ else: PY } +# ---------- Локальный прокси Z.ai ---------- +# Зачем: приложение пускает в профиле только имена claude-*, а сервер Z.ai +# маппит ЛЮБОЕ claude-имя на лёгкую GLM-5.3-Flash, даже на подписке с полным +# GLM-5.3. Прокси на 127.0.0.1:8287 переписывает модель перед отправкой: +# claude-* (не haiku) -> glm-5.3, claude-*-haiku* -> glm-5.3-flash, [1m] срезается. +# Ключ прокси не хранит: заголовки авторизации проходят из приложения насквозь. +# Код прокси продублирован файлами zai-proxy.py / zai-proxy.ps1 в репозитории; +# здесь он встроен, потому что скрипт запускают через curl | bash. + +PROXY_PORT=8287 +PROXY_DIR_MAC="$HOME/.claude-brains" +PROXY_AGENT_LABEL="ru.akdevs.claude-brains.zai-proxy" +PROXY_TASK_WIN="claude-brains-zai-proxy" + +proxy_up() { + curl -sf --max-time 3 "http://127.0.0.1:$PROXY_PORT/health" >/dev/null 2>&1 +} + +install_zai_proxy() { + if proxy_up; then + ok "Локальный прокси Z.ai уже работает на :$PROXY_PORT." + return 0 + fi + if [ "$OS" = "mac" ]; then + [ -n "$PY" ] || { warn "Нет python3, прокси Z.ai не поставить: полный GLM-5.3 будет Flash-вариантом."; return 0; } + command -v python3 >/dev/null 2>&1 || { warn "python3 не найден в PATH для автозапуска прокси."; return 0; } + mkdir -p "$PROXY_DIR_MAC" + cat > "$PROXY_DIR_MAC/zai-proxy.py" <<'PROXYPY' +#!/usr/bin/env python3 +# zai-proxy — локальный мост Claude Desktop -> Z.ai (macOS). +# Слушает только 127.0.0.1. Ключ не хранит: заголовки проходят насквозь. +# claude-* (не haiku) -> glm-5.3, claude-*-haiku* -> glm-5.3-flash, [1m] срезается. +import json, re, sys +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib import request as urlreq, error as urlerr + +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": + self.send_response(200); self.send_header("Content-Type","text/plain") + self.send_header("Content-Length","2"); self.end_headers() + self.wfile.write(b"ok"); return + length = int(self.headers.get("Content-Length") or 0) + body = self.rfile.read(length) if length else b"" + note = "(passthrough)" + if body and "json" in (self.headers.get("Content-Type") or ""): + 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 urlerr.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() + 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 + code = getattr(resp, "status", None) or resp.code + self._log("%s %s %s -> %s" % (self.command, self.path, note, code)) + self.send_response(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 + +if __name__ == "__main__": + print("zai-proxy: listening on 127.0.0.1:%d -> https://%s" % (PORT, UPSTREAM_HOST), file=sys.stderr) + ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever() +PROXYPY + PYPATH="$(command -v python3)" + cat > "$HOME/Library/LaunchAgents/$PROXY_AGENT_LABEL.plist" < + + + + Label$PROXY_AGENT_LABEL + ProgramArguments + $PYPATH$PROXY_DIR_MAC/zai-proxy.py + RunAtLoad + KeepAlive + StandardOutPath$PROXY_DIR_MAC/zai-proxy.out.log + StandardErrorPath$PROXY_DIR_MAC/zai-proxy.err.log + + +PLIST + launchctl bootout "gui/$(id -u)/$PROXY_AGENT_LABEL" 2>/dev/null || true + launchctl bootstrap "gui/$(id -u)" "$HOME/Library/LaunchAgents/$PROXY_AGENT_LABEL.plist" 2>/dev/null \ + || { warn "Не смог зарегистрировать автозапуск прокси."; return 0; } + else + # Windows (Git Bash): прокси на PowerShell, автостарт через планировщик. + local pdir; pdir="$(cygpath -u "$LOCALAPPDATA")/claude-brains" + mkdir -p "$pdir" + cat > "$pdir/zai-proxy.ps1" <<'PROXYPS1' +# zai-proxy (Windows) - see zai-proxy.py for docs. Listens 127.0.0.1:8287 only. +$ErrorActionPreference = "Stop" +$Port = 8287 +$Upstream = "https://api.z.ai" +$LogFile = Join-Path $PSScriptRoot "zai-proxy.log" +function Write-Log($line) { try { Add-Content -Path $LogFile -Value "$(Get-Date -Format o) $line" -Encoding UTF8 } catch { } } +function Map-Model([string]$name) { + $bare = $name -replace '\[1m\]$','' + if ($bare -match '^claude-(haiku|3-5-haiku|3-haiku)') { return "glm-5.3-flash" } + if ($bare -like 'claude-*') { return "glm-5.3" } + return $null +} +Add-Type -AssemblyName System.Net.Http +$listener = New-Object System.Net.HttpListener +$listener.Prefixes.Add("http://127.0.0.1:${Port}/") +$listener.Start() +Write-Log "listening on 127.0.0.1:$Port -> $Upstream" +$client = New-Object System.Net.Http.HttpClient +$client.Timeout = [TimeSpan]::FromMinutes(10) +while ($listener.IsListening) { + $ctx = $listener.GetContext() + try { + $req = $ctx.Request; $res = $ctx.Response + if ($req.Url.AbsolutePath -eq "/health") { + $b = [Text.Encoding]::UTF8.GetBytes("ok") + $res.ContentType = "text/plain"; $res.ContentLength64 = $b.Length + $res.OutputStream.Write($b, 0, $b.Length); $res.Close(); continue + } + $bodyBytes = $null + if ($req.HasEntityBody) { + $ms = New-Object IO.MemoryStream + $req.InputStream.CopyTo($ms); $bodyBytes = $ms.ToArray() + } + $note = "(passthrough)" + if ($bodyBytes -and $req.ContentType -and $req.ContentType -match 'json') { + $text = [Text.Encoding]::UTF8.GetString($bodyBytes) + $m = [regex]::Match($text, '"model"\s*:\s*"([^"]+)"') + if ($m.Success) { + $to = Map-Model $m.Groups[1].Value + if ($to) { + $note = "$($m.Groups[1].Value) -> $to" + $text = $text.Substring(0, $m.Index) + '"model": "' + $to + '"' + $text.Substring($m.Index + $m.Length) + $bodyBytes = [Text.Encoding]::UTF8.GetBytes($text) + } + } + } + $up = New-Object System.Net.Http.HttpRequestMessage([System.Net.Http.HttpMethod]::new($req.HttpMethod), ($Upstream + $req.Url.PathAndQuery)) + if ($bodyBytes) { + $up.Content = New-Object System.Net.Http.ByteArrayContent(,$bodyBytes) + $up.Content.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse($req.ContentType) + } + foreach ($h in $req.Headers) { + if ($h.Key -in @("Host","Content-Length","Transfer-Encoding","Connection","Content-Type","Accept-Encoding")) { continue } + try { $up.Headers.TryAddWithoutValidation($h.Key, $h.Value) | Out-Null } catch { } + } + $urs = $client.SendAsync($up, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead).GetAwaiter().GetResult() + Write-Log "$($req.HttpMethod) $($req.Url.PathAndQuery) $note -> $([int]$urs.StatusCode)" + $res.StatusCode = [int]$urs.StatusCode + $res.ContentType = if ($urs.Content.Headers.ContentType) { $urs.Content.Headers.ContentType.ToString() } else { "application/octet-stream" } + $res.SendChunked = $true + $stream = $urs.Content.ReadAsStreamAsync().GetAwaiter().GetResult() + $buf = New-Object byte[] 8192 + while (($n = $stream.Read($buf, 0, $buf.Length)) -gt 0) { + $res.OutputStream.Write($buf, 0, $n); $res.OutputStream.Flush() + } + $res.Close() + } catch { + Write-Log "ERROR $($_.Exception.Message)" + try { $ctx.Response.Close() } catch { } + } +} +PROXYPS1 + PDIR_W="$(cygpath -w "$pdir")" + powershell.exe -NoProfile -ExecutionPolicy Bypass -Command \ + "schtasks /Create /F /TN $PROXY_TASK_WIN /TR \"powershell.exe -NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File '$PDIR_W\zai-proxy.ps1'\" /SC ONLOGON" >/dev/null 2>&1 \ + || { warn "Не смог создать задачу автозапуска прокси."; return 0; } + powershell.exe -NoProfile -Command "schtasks /Run /TN $PROXY_TASK_WIN" >/dev/null 2>&1 || true + fi + local i=0 + while ! proxy_up && [ "$i" -lt 10 ]; do sleep 1; i=$((i+1)); done + if proxy_up; then + ok "Локальный прокси Z.ai запущен на :$PROXY_PORT (полный GLM-5.3, автостарт прописан)." + else + warn "Прокси не поднялся за 10 секунд. Профиль указывает на 127.0.0.1:$PROXY_PORT:" + echo " проверь лог $PROXY_DIR_MAC/zai-proxy.err.log (мак) или задачу $PROXY_TASK_WIN (вин)." + fi +} + +remove_zai_proxy() { + if [ "$OS" = "mac" ]; then + launchctl bootout "gui/$(id -u)/$PROXY_AGENT_LABEL" 2>/dev/null || true + rm -f "$HOME/Library/LaunchAgents/$PROXY_AGENT_LABEL.plist" + else + powershell.exe -NoProfile -Command "schtasks /Delete /F /TN $PROXY_TASK_WIN" >/dev/null 2>&1 || true + powershell.exe -NoProfile -Command "Get-Process powershell -ErrorAction SilentlyContinue | Where-Object { \$_.CommandLine -like '*zai-proxy.ps1*' } | Stop-Process -Force" 2>/dev/null || true + fi +} + # ---------- ОТКАТ ---------- if [ "$MODE" = "restore" ]; then say "Откат на родного Claude..." if [ ! -f "$LIB/_meta.json" ]; then ok "Конфигов нет, откатывать нечего."; exit 0; fi merge_meta default none + remove_zai_proxy repair_json_bom >/dev/null 2>&1 || true ok "Применён пустой профиль Default." echo " Если приложение всё равно открывается на чужом мозге: меню аккаунта внизу слева -> Sign out," @@ -553,20 +788,37 @@ ok "Конфиг ollama-cloud на месте." fi if [ "$BRAIN" = "zai" ] || [ "$BRAIN" = "both" ]; then + install_zai_proxy if [ -f "$LIB/$ID_ZAI.json" ] && ! grep -q "$ZAI_PLACEHOLDER" "$LIB/$ID_ZAI.json"; then - ok "Конфиг zai-glm уже настроен, ключ не трогаю." + # Конфиг уже с ключом: переводим его на локальный прокси, ключ сохраняем. + # Без прокси Z.ai маппит claude-имена на лёгкую модель (GLM-5.3-Flash) + # даже на подписке с полным GLM-5.3. + if [ -n "$PY" ]; then + upgraded="$("$PY" - "$LIB/$ID_ZAI.json" <<'PY' +import json, sys +p = sys.argv[1] +d = json.load(open(p, encoding="utf-8")) +d["inferenceGatewayBaseUrl"] = "http://127.0.0.1:8287/api/anthropic" +json.dump(d, open(p, "w", encoding="utf-8"), indent=2, ensure_ascii=False) +print("переведён на локальный прокси, ключ сохранён") +PY +)" + ok "Конфиг zai-glm: $upgraded." + else + ok "Конфиг zai-glm уже настроен, ключ не трогаю." + fi else cat > "$LIB/$ID_ZAI.json" < Configure Third-Party Inference -> конфигурация zai-glm ->" echo " вставь ключ в Gateway API key -> Apply Changes -> перезапусти Claude." diff --git a/zai-proxy.ps1 b/zai-proxy.ps1 new file mode 100644 index 0000000..bc21f67 --- /dev/null +++ b/zai-proxy.ps1 @@ -0,0 +1,108 @@ +# zai-proxy — локальный мост Claude Desktop -> Z.ai (Windows). +# +# Зачем: приложение пускает в профиле только имена 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-именами. +# +# Запуск вручную: powershell -NoProfile -ExecutionPolicy Bypass -File zai-proxy.ps1 +# Автозапуск ставит setup.ps1 (планировщик задач, задача claude-brains-zai-proxy). + +$ErrorActionPreference = "Stop" +$Port = 8287 +$Upstream = "https://api.z.ai" +$LogFile = Join-Path $PSScriptRoot "zai-proxy.log" + +function Write-Log($line) { + try { Add-Content -Path $LogFile -Value "$(Get-Date -Format o) $line" -Encoding UTF8 } catch { } +} + +function Map-Model([string]$name) { + $bare = $name -replace '\[1m\]$', '' + if ($bare -match '^claude-(haiku|3-5-haiku|3-haiku)') { return "glm-5.3-flash" } + if ($bare -like 'claude-*') { return "glm-5.3" } + return $null +} + +Add-Type -AssemblyName System.Net.Http + +$listener = New-Object System.Net.HttpListener +$listener.Prefixes.Add("http://127.0.0.1:${Port}/") +$listener.Start() +Write-Log "listening on 127.0.0.1:$Port -> $Upstream" + +$client = New-Object System.Net.Http.HttpClient +$client.Timeout = [TimeSpan]::FromMinutes(10) + +while ($listener.IsListening) { + $ctx = $listener.GetContext() + try { + $req = $ctx.Request + $res = $ctx.Response + + if ($req.Url.AbsolutePath -eq "/health") { + $b = [Text.Encoding]::UTF8.GetBytes("ok") + $res.ContentType = "text/plain" + $res.ContentLength64 = $b.Length + $res.OutputStream.Write($b, 0, $b.Length) + $res.Close() + continue + } + + $bodyBytes = $null + if ($req.HasEntityBody) { + $ms = New-Object IO.MemoryStream + $req.InputStream.CopyTo($ms) + $bodyBytes = $ms.ToArray() + } + + $note = "(passthrough)" + if ($bodyBytes -and $req.ContentType -and $req.ContentType -match 'json') { + $text = [Text.Encoding]::UTF8.GetString($bodyBytes) + $m = [regex]::Match($text, '"model"\s*:\s*"([^"]+)"') + if ($m.Success) { + $to = Map-Model $m.Groups[1].Value + if ($to) { + $note = "$($m.Groups[1].Value) -> $to" + $text = $text.Substring(0, $m.Index) + '"model": "' + $to + '"' + $text.Substring($m.Index + $m.Length) + $bodyBytes = [Text.Encoding]::UTF8.GetBytes($text) + } + } + } + + $up = New-Object System.Net.Http.HttpRequestMessage([System.Net.Http.HttpMethod]::new($req.HttpMethod), ($Upstream + $req.Url.PathAndQuery)) + if ($bodyBytes) { + $up.Content = New-Object System.Net.Http.ByteArrayContent(,$bodyBytes) + $up.Content.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse($req.ContentType) + } + foreach ($h in $req.Headers) { + if ($h.Key -in @("Host", "Content-Length", "Transfer-Encoding", "Connection", "Content-Type", "Accept-Encoding")) { continue } + try { $up.Headers.TryAddWithoutValidation($h.Key, $h.Value) | Out-Null } catch { } + } + + $urs = $client.SendAsync($up, [System.Net.Http.HttpCompletionOption]::ResponseHeadersRead).GetAwaiter().GetResult() + Write-Log "$($req.HttpMethod) $($req.Url.PathAndQuery) $note -> $([int]$urs.StatusCode)" + + $res.StatusCode = [int]$urs.StatusCode + $res.ContentType = if ($urs.Content.Headers.ContentType) { $urs.Content.Headers.ContentType.ToString() } else { "application/octet-stream" } + $res.SendChunked = $true + + $stream = $urs.Content.ReadAsStreamAsync().GetAwaiter().GetResult() + $buf = New-Object byte[] 8192 + while (($n = $stream.Read($buf, 0, $buf.Length)) -gt 0) { + $res.OutputStream.Write($buf, 0, $n) + $res.OutputStream.Flush() + } + $res.Close() + } catch { + Write-Log "ERROR $($_.Exception.Message)" + try { $ctx.Response.Close() } catch { } + } +} diff --git a/zai-proxy.py b/zai-proxy.py new file mode 100644 index 0000000..66bd44c --- /dev/null +++ b/zai-proxy.py @@ -0,0 +1,131 @@ +#!/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()