Files
magpie/internal/provider/zhipu_envelope.go
T
yetone 35aa50cfb3 zhipu: a GLM Coding Plan key refused 200 in the platform's envelope reads as refused, in the test, the gateway and the quota card (@xanahopper on X)
On a Coding Plan with a key Zhipu refuses, Test showed OpenAI 401 and
Anthropic 401 but Responses (https://open.bigmodel.cn/api/v1) a green
check, and the 5h/weekly windows showed only "Allowance unavailable".

Cause: /api/v1 (Zhipu's real Responses endpoint, docs.bigmodel.cn
coding-plan/tool/codex) and /api/monitor answer a refused key HTTP 200
with {"code":1000,"msg":"身份验证失败。","success":false}. probe (endpoint
Test, model tests, Detect) took any 2xx as ok, and the gateway handed
the 200 to Codex as a reply, so no failover and no rest.

- provider.ZhipuEnveloped: a 2xx JSON, non-stream, unencoded reply from
  open.bigmodel.cn or api.z.ai whose body is the envelope with
  success:false becomes {"error":{...}} under the status Zhipu's code
  table gives (1000-1005 401, 1113/13xx 429, 1220 403, 121x/1261/1301
  400, else 502). Anything else passes through unchanged (64KB cap,
  body restored). Applied in probe and in the gateway's forwardOnce.
- planquota: a refused key (envelope 1000-1005 or HTTP 401 from a
  Zhipu/Z.ai host) says "Zhipu didn't take this key (...): it has
  expired, was deleted, or is mistyped; paste a current one from <keys
  page>", and skips the team retry. The card shows it in en, zh, zh-TW,
  ja, de.
- docs: providers-accounts and gateway-routing rows.

Run at this head (before rebase, base 95e7c6bcc):
- go test -timeout 20m ./internal/gateway ./internal/provider: ok
  (343s, 93s). New: TestZhipuResponsesRefusalNotGreen,
  TestZhipuEnveloped, TestZhipuRefusedKeyCard,
  TestZhipuResponsesRefusalIsRefusal (zhipu and zai presets).
- Full go test ./...: every package ok except internal/gateway, which
  hit the default 10m timeout while the full GUI suite and another
  session's GUI tests ran beside it; alone with -timeout 20m it passed.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet on provider and
  gateway clean.
- GUI: glm-quota-error (new) and opencode-go-quota-error 20/20 in
  chromium and webkit, five languages. The full GUI suite ran once (under
  load) and exited 1; each of its 16 red files was rerun alone here and
  on an origin/main 03eb0633a copy of internal/gui: 10 pass on both;
  quota-count-wrap (1), quota-name-translated (1),
  refusal-retries-setting (2), usage-agents-hide (22), usage-fold (2)
  fail the same counts on both; routing-held-member fails 1 here, 2 on
  main. None touches quotaError's GLM line.

Broken by hand: ZhipuEnveloped returning res unchanged, and
zhipuEnvelope returning ok=false, turned the provider tests red;
reverting the gateway line turned TestZhipuResponsesRefusalIsRefusal
red; breaking the GLM regex in app.js turned glm-quota-error 0/5 in
chromium. All restored.

Not tried: no real Zhipu or Z.ai key, valid or expired. The refusal
bytes are from a curl of /api/v1 with a bad key; the reporter's
"令牌已过期或验证不正确" code is unknown (assumed 1000-1005 or HTTP 401,
both handled). A valid key's quota read with a real plan was not run.
2026-10-15 15:55:24 +08:00

113 lines
3.9 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package provider
import (
"bytes"
"encoding/json"
"io"
"net/http"
"strconv"
"strings"
)
// Zhipu's and Z.ai's /api/v1 — the GLM Coding Plan's Responses API, which
// their Codex pages give (docs.bigmodel.cn/cn/coding-plan/tool/codex) — and
// their /api/monitor answer a refusal 200, in the platform's envelope:
//
// {"code":1000,"msg":"身份验证失败。","success":false}
//
// where their OpenAI and Anthropic endpoints answer the same key 401
// {"error":{"code":"1000","message":"身份验证失败。"}}. Taken as it came, a
// key refused everywhere tested green on the Responses row (@xanahopper on
// X), and Codex was handed the envelope as a reply. ZhipuEnveloped turns
// it into the refusal it is, at the status Zhipu's error codes are given
// (docs.bigmodel.cn/cn/faq/api-code).
// zhipuCodeStatus is the HTTP status Zhipu gives a business error code;
// a code it lists none for, or a 500 of the platform's, is a 502.
func zhipuCodeStatus(code int) int {
switch {
case code >= 1000 && code <= 1005:
return http.StatusUnauthorized
case code == 1113, code >= 1302 && code <= 1399:
return http.StatusTooManyRequests
case code == 1220:
return http.StatusForbidden
case code >= 1210 && code <= 1229, code == 1261, code == 1301:
return http.StatusBadRequest
}
return http.StatusBadGateway
}
// zhipuEnvelope reads b as the platform's refusal: its code and message,
// and whether it is one ({"success":false} with a code or a message).
func zhipuEnvelope(b []byte) (code int, msg string, ok bool) {
var v struct {
Success *bool `json:"success"`
Code json.RawMessage `json:"code"`
Msg string `json:"msg"`
}
if json.Unmarshal(b, &v) != nil || v.Success == nil || *v.Success {
return 0, "", false
}
var n json.Number
if json.Unmarshal(v.Code, &n) == nil {
code, _ = strconv.Atoi(n.String())
} else if s := ""; json.Unmarshal(v.Code, &s) == nil {
code, _ = strconv.Atoi(s)
}
msg = strings.TrimSpace(v.Msg)
return code, msg, code != 0 || msg != ""
}
// ZhipuKeyRefused says whether an envelope's code is Zhipu refusing the
// key itself (1000–1005: not taken, missing, expired, needs a second
// factor), not the request.
func ZhipuKeyRefused(code int) bool { return code >= 1000 && code <= 1005 }
// ZhipuEnveloped is res, or — when it is a 2xx from Zhipu or Z.ai holding
// the platform's refusal envelope — the refusal at its status, with the
// body as their OpenAI API words one. A stream, a compressed body and
// every other host's reply pass as they came.
func ZhipuEnveloped(req *http.Request, res *http.Response) *http.Response {
if req == nil || res == nil || res.Body == nil || res.StatusCode < 200 || res.StatusCode >= 300 || !zhipuHost(req.URL.Hostname()) {
return res
}
ct := strings.ToLower(res.Header.Get("Content-Type"))
if !strings.Contains(ct, "json") || strings.Contains(ct, "event-stream") || res.Header.Get("Content-Encoding") != "" {
return res
}
b, err := io.ReadAll(io.LimitReader(res.Body, 64<<10+1))
if err != nil || len(b) > 64<<10 {
// a refusal is small: a body this long is a reply, left to be read
// on as it came, and a read that failed to its reader
res.Body = struct {
io.Reader
io.Closer
}{io.MultiReader(bytes.NewReader(b), res.Body), res.Body}
return res
}
res.Body.Close()
set := func(nb []byte) *http.Response {
res.Body = io.NopCloser(bytes.NewReader(nb))
res.ContentLength = int64(len(nb))
res.Header.Set("Content-Length", strconv.Itoa(len(nb)))
return res
}
code, msg, ok := zhipuEnvelope(b)
if !ok {
res.Body = io.NopCloser(bytes.NewReader(b))
return res
}
if msg == "" {
msg = "request failed"
}
e := map[string]any{"message": msg}
if code != 0 {
e["code"] = strconv.Itoa(code)
}
nb, _ := json.Marshal(map[string]any{"error": e})
res.StatusCode = zhipuCodeStatus(code)
res.Status = strconv.Itoa(res.StatusCode) + " " + http.StatusText(res.StatusCode)
return set(nb)
}