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.
This commit is contained in:
yetone
2026-10-15 15:55:24 +08:00
parent 03eb0633af
commit 35aa50cfb3
11 changed files with 513 additions and 3 deletions
File diff suppressed because one or more lines are too long
+1
View File
@@ -20,6 +20,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
| Provider | `Provider` holds the endpoint bases for each `Protocol` (Chat, Responses, Anthropic, Gemini), the keys, `Fallback`, `Routing`, `Sink`, `Affinity`, concurrency and queue limits, `Headers`, `Proxy`, models, and balance settings. `BaseAPI` is the API a custom provider's editor shows its Base URL as: the one the user picked and saved, while it has a URL, so a provider with a chat URL beside its Responses one isn't shown as OpenAI compatible after Responses was picked. Requests go by which URLs are set. A custom provider's `Gemini` URL is the base of Google's Gemini API, or of one that answers as it does (#1346): `GeminiBase` keeps it as the base (…/v1beta added to a bare host, a pasted endpoint or model list cut back), requests go to `models/{model}:streamGenerateContent?alt=sse` under it (`GeminiPath`) signed with `x-goog-api-key` (`AuthHeaders`), and its models are listed by `catalog.FetchGemini` (paged, only those serving generateContent). Factory's sign-in alone keeps its own `/generate` route and token (`FactoryGemini`). `Account` is set only for a subscription and is never saved (`json:"-"`). | [`provider.go`](../../internal/provider/provider.go) |
| Anthropic key header | A provider of the user's own on a third-party Anthropic API is sent its key as both `x-api-key` and `Authorization: Bearer` (`AuthHeaders`); Anthropic's own API, Bedrock, Azure, Vertex and every subscription account have their own and never this choice (`BothAuth` is false). Some services refuse the two together with a 401 (Aloha on Discord: "鉴权 header, x-api-key 和 Authorization 不可以同时存在"), so `Provider.AuthHeader` (`authHeader`: empty for both, `x-api-key` or `bearer`; anything else is read as empty) sends one alone, picked in the editor's Key header row (shown while `bothAuth` is true, or a custom provider's Anthropic URL is a third party's). Left at both, a 401 whose body `catalog.BothAuthRefused` tells as that refusal (it names both headers and says they can't be together, in Chinese or English) is asked once more with x-api-key alone, then Bearer alone (`RetryOneAuth`, in the gateway's `forwardOnce` and the provider test's `probe`; `catalog.fetchOne` for the model list through `listAuth`); the first not answered 401 or 403 is kept with `LearnAuthHeader`, which never changes a pick the user made. A request carrying the user's own `Authorization` or `x-api-key` header is never retried. | [`authheader.go`](../../internal/provider/authheader.go), [`test.go`](../../internal/provider/test.go), [`catalog/authheader.go`](../../internal/catalog/authheader.go), [`catalog/live.go`](../../internal/catalog/live.go) |
| GLM Coding Plan key at pay as you go | Zhipu's and Z.ai's presets offer Pay as you go first (`/api/paas/v4`) and the Coding Plan (`/api/coding/paas/v4`, Responses at `/api/v1`); both share `/api/anthropic`, which bills the plan, so a plan's key left at Pay as you go worked in Claude Code and was refused 429 code 1113 "余额不足或无可用资源包" in Codex (@cleverpigo on X). Nothing in the key tells the two apart, so a Chat request to `open.bigmodel.cn` or `api.z.ai` at `/api/paas/v4` refused 1113 is asked once more at `/api/coding/paas/v4` (`RetryZhipuCoding`, in the gateway's `forwardOnce` and the provider test's `probe`). Served there, `LearnZhipuCoding` moves a saved provider with that one key, still at that URL, to the plan's OpenAI URL (and the preset's plan Responses URL when it has none); one with other keys stays and is asked again each time. Refused there too, the 1113 body keeps its code and gets both URLs and what to change in its message (`ZhipuNoBalanceHint`). A pay-as-you-go key with a balance is never answered 1113 and never sent to the plan's endpoint. | [`zhipu_coding.go`](../../internal/provider/zhipu_coding.go), [`test.go`](../../internal/provider/test.go) |
| Zhipu's 200 refusals | Zhipu's and Z.ai's `/api/v1` (the GLM Coding Plan's Responses API, from their Codex pages) and `/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 (@xanahopper on X: a refused key tested green on the Responses row only). `ZhipuEnveloped` turns a 2xx JSON body from `open.bigmodel.cn` or `api.z.ai` with `success: false` into `{"error":{"code","message"}}` at the status Zhipu's error-code table gives (1000–1005 → 401, 1113 and 1302–1399 → 429, 1220 → 403, 1210–1229, 1261 and 1301 → 400, anything else → 502), in the provider test's `probe` (endpoint tests, model tests, Detect APIs) and the gateway's `forwardOnce`. A stream, a compressed body, a body over 64 KB and every other host pass as they came. The plan's quota card for a key refused there (1000–1005, or a 401) says `<Zhipu or Z.ai> didn't take this key (<their words>): …` with the vendor's API-keys page (`zhipuRefused`), not asked again as a team's key, and the GUI shows it as that (`quotaError`) rather than "Allowance unavailable". | [`zhipu_envelope.go`](../../internal/provider/zhipu_envelope.go), [`planquota.go`](../../internal/provider/planquota.go), [`test.go`](../../internal/provider/test.go) |
| Extra body | `ExtraBody` (`extraBody` in providers.json, the editor's *Extra body*, #1604) is a JSON object whose fields `WithExtraBody` adds at the top level of every JSON body sent to the provider: Messages, Chat, Responses and Gemini, relayed as they came or translated, in the gateway's `forwardOnce` and in Test and Detect (`tested`). A field the body has already is kept; a name written `"!name"` replaces it. Values are put in as written, objects whole, not merged. `${sessionId}` in any string, at any depth, becomes the request's session: the agent's session header (`sessionOf`), else the id `conversationID` derives from the first user message (`magpie-` and its hash), so it stays the same through one conversation; Test and Detect send `magpie-test-` and 12 random letters, a new one each time. `model`, `stream` and the conversation (`messages`, `input`, `contents`, `system`, `systemInstruction`, `system_instruction`, `instructions`, `tools`, `ExtraBodyReserved`) are magpie's: Save refuses them with or without `!` (`ExtraBodyOK`), the editor says so as they are typed, and one written into providers.json by hand is dropped on read (`cleanExtraBody`). Not sent with it: `count_tokens`, embeddings, images, video and System One's decision model (other APIs), and a signed-in account's requests. One object goes to every API; fields for one API alone are not a thing yet. | [`extrabody.go`](../../internal/provider/extrabody.go), [`gateway.go`](../../internal/gateway/gateway.go) |
| Native compaction | `NativeCompaction` (`nativeCompaction` in providers.json, the editor's *Compaction* row, `magpie provider set <id> compaction=native\|magpie`; #1099) has Codex's compaction asked of the provider as Codex sent it and its sealed item returned unchanged. Off by default. Only a provider whose wire carries it can be set so (`CarriesCompaction`: a Responses API, a ChatGPT account, GitHub Copilot; not another agent's sign-in or a plugin's), and `CompactsOn(model)` also needs the model asked on Responses. `SetNativeCompaction`, the CLI and the GUI's save refuse it elsewhere. An account keeps it through `Save`'s picks (`withPicks`), and `AddCopy` carries it. The gateway's half is in [gateway-routing](gateway-routing.md). | [`native_compaction.go`](../../internal/provider/native_compaction.go) |
| providers.json | `Path` is `providers.json` in magpie's config folder. A read that fails returns `ErrUnreadable` and is never treated as empty. `store` writes atomically through a rename and drops the cached catalog (`catalog.Touched`). | [`provider.go`](../../internal/provider/provider.go) |
+4 -1
View File
@@ -3699,7 +3699,10 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid
}
// Cline's whole replies come in {success, data}; a web page or
// nothing at all, served 200, is the 502 it stands for (#1012)
res = notAnAPIReply(clineUnwrapped(p, res), "")
// Zhipu's and Z.ai's Responses API refuses a key 200 in the platform's
// envelope: the 401 (or 429 …) it stands for, so the next key or
// member is asked and the agent told why (@xanahopper on X)
res = notAnAPIReply(clineUnwrapped(p, provider.ZhipuEnveloped(req, res)), "")
if p.Account != nil && p.Account.Agent == "codex" {
// a large request ChatGPT closed the connection on: asked again,
// nobody resting for it, and said what may help (#1628)
+68
View File
@@ -0,0 +1,68 @@
package gateway
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// zhipuResponses plays the GLM Coding Plan's Responses API at /api/v1: a
// key it refuses is answered 200 in the platform's envelope, as
// open.bigmodel.cn answered one on 2026-10-15.
type zhipuResponses struct{}
func (zhipuResponses) RoundTrip(r *http.Request) (*http.Response, error) {
if r.Body != nil {
io.Copy(io.Discard, r.Body)
}
body := `{"code":1000,"msg":"身份验证失败。","success":false}`
if r.Header.Get("Authorization") == "Bearer good" {
body = `{"id":"resp_1","object":"response","status":"completed","model":"glm-5.1","output":[{"type":"message","id":"m1","role":"assistant","content":[{"type":"output_text","text":"pong"}]}],"usage":{"input_tokens":3,"output_tokens":1,"total_tokens":4}}`
}
return &http.Response{StatusCode: 200, Status: "200 OK", Header: http.Header{"Content-Type": {"application/json"}},
Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
}
// Codex on a GLM Coding Plan whose key Zhipu refuses (@xanahopper on X)
// is told the key was refused, 401 with Zhipu's words, not handed the
// envelope as a 200 reply; a key Zhipu takes is answered as before.
func TestZhipuResponsesRefusalIsRefusal(t *testing.T) {
for _, tc := range []struct{ preset, host string }{
{"zhipu", "open.bigmodel.cn"},
{"zai", "api.z.ai"},
} {
t.Run(tc.preset, func(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
for _, id := range []string{"bad", "good"} {
p, err := provider.FromPreset(tc.preset)
if err != nil {
t.Fatal(err)
}
p.ID, p.Name, p.Key, p.Models = tc.preset+"-"+id, id, id, []string{"glm-5.1"}
p.Chat, p.Anthropic, p.Responses = "", "", "https://"+tc.host+"/api/v1"
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
s := New()
s.client = &http.Client{Transport: zhipuResponses{}}
codex := func(id string) *httptest.ResponseRecorder {
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses",
strings.NewReader(`{"model":"`+tc.preset+"-"+id+`/glm-5.1","input":"Say pong","stream":false}`)))
return rec
}
if rec := codex("bad"); rec.Code != http.StatusUnauthorized || !strings.Contains(rec.Body.String(), "身份验证失败") {
t.Errorf("refused key: %d %s", rec.Code, rec.Body)
}
if rec := codex("good"); rec.Code != 200 || !strings.Contains(rec.Body.String(), "pong") {
t.Errorf("a key Zhipu takes: %d %s", rec.Code, rec.Body)
}
})
}
}
+4
View File
@@ -12616,6 +12616,10 @@ function quotaError(err) {
// reads none — said with the way out, as a phone can't hover for it
if (/^this key has no OpenCode Go subscription/.test(err)) return t("No OpenCode Go on this key — use a key made by the member who subscribed, in that workspace");
if (/^OpenCode didn't take this key/.test(err)) return t("OpenCode didn't take this key — paste a current one in the provider's settings");
// a GLM key Zhipu or Z.ai refused (zhipuRefused, planquota.go): the key
// is what to change, not a reading that failed (@xanahopper on X)
const glm = /^(Zhipu|Z\.ai) didn't take this key/.exec(err);
if (glm) return t("{vendor} didn't take this key — it expired, was deleted or is mistyped; paste a current one in the provider's settings", { vendor: glm[1] });
if (/^OpenCode Go's reply has no rolling/.test(err)) return t("OpenCode Go answered in a form magpie doesn't read — hover for what it sent");
// a remote magpie's card (remote_quotas.go)
if (/^nothing read on that magpie yet/.test(err)) return t("Nothing read on that computer yet — refresh this card to have it read");
+4
View File
@@ -2624,6 +2624,7 @@ const I18N = {
"MCP · Month": "MCP · 本月",
"No OpenCode Go on this key — use a key made by the member who subscribed, in that workspace": "这个 Key 没有 OpenCode Go — 请用订阅者本人在该工作区创建的 Key",
"OpenCode didn't take this key — paste a current one in the provider's settings": "OpenCode 不认这个 Key — 请在提供商设置里换一个有效的 Key",
"{vendor} didn't take this key — it expired, was deleted or is mistyped; paste a current one in the provider's settings": "{vendor} 不认这个 Key — 它已过期、被删除或填错了;请在提供商设置里换一个有效的 Key",
"OpenCode Go answered in a form magpie doesn't read — hover for what it sent": "OpenCode Go 返回的格式 magpie 读不懂 — 悬停查看它返回了什么",
"7 days · Opus": "7 天 · Opus",
"7 days · Sonnet": "7 天 · Sonnet",
@@ -6180,6 +6181,7 @@ const I18N = {
"MCP · Month": "MCP · 本月",
"No OpenCode Go on this key — use a key made by the member who subscribed, in that workspace": "這個 Key 沒有 OpenCode Go — 請用訂閱者本人在該工作區建立的 Key",
"OpenCode didn't take this key — paste a current one in the provider's settings": "OpenCode 不認這個 Key — 請在供應商設定裡換一個有效的 Key",
"{vendor} didn't take this key — it expired, was deleted or is mistyped; paste a current one in the provider's settings": "{vendor} 不認這個 Key — 它已過期、被刪除或填錯了;請在供應商設定裡換一個有效的 Key",
"OpenCode Go answered in a form magpie doesn't read — hover for what it sent": "OpenCode Go 回傳的格式 magpie 讀不懂 — 懸停查看它回傳了什麼",
"7 days · Opus": "7 天 · Opus",
"7 days · Sonnet": "7 天 · Sonnet",
@@ -9743,6 +9745,7 @@ const I18N = {
"MCP · Month": "MCP · 月",
"No OpenCode Go on this key — use a key made by the member who subscribed, in that workspace": "このキーには OpenCode Go がありません — 契約したメンバー本人がそのワークスペースで作ったキーを使ってください",
"OpenCode didn't take this key — paste a current one in the provider's settings": "OpenCode がこのキーを受け付けませんでした — プロバイダ設定で有効なキーを貼り付けてください",
"{vendor} didn't take this key — it expired, was deleted or is mistyped; paste a current one in the provider's settings": "{vendor} がこのキーを受け付けませんでした — 期限切れ、削除済み、または入力ミスです。プロバイダ設定で有効なキーを貼り付けてください",
"OpenCode Go answered in a form magpie doesn't read — hover for what it sent": "OpenCode Go の応答は magpie が読めない形式です — ホバーで内容を表示",
"7 days · Opus": "7 日 · Opus",
"7 days · Sonnet": "7 日 · Sonnet",
@@ -13312,6 +13315,7 @@ const I18N = {
"MCP · Month": "MCP · Monat",
"No OpenCode Go on this key — use a key made by the member who subscribed, in that workspace": "Kein OpenCode Go auf diesem Schlüssel — nimm einen Schlüssel, den das abonnierende Mitglied in diesem Workspace erstellt hat",
"OpenCode didn't take this key — paste a current one in the provider's settings": "OpenCode hat diesen Schlüssel nicht angenommen — füge in den Anbieter-Einstellungen einen gültigen ein",
"{vendor} didn't take this key — it expired, was deleted or is mistyped; paste a current one in the provider's settings": "{vendor} hat diesen Schlüssel nicht angenommen — er ist abgelaufen, gelöscht oder vertippt; füge in den Anbieter-Einstellungen einen gültigen ein",
"OpenCode Go answered in a form magpie doesn't read — hover for what it sent": "OpenCode Go hat in einer Form geantwortet, die magpie nicht liest — für den Inhalt darüberfahren",
"7 days · Opus": "7 Tage · Opus",
"7 days · Sonnet": "7 Tage · Sonnet",
@@ -0,0 +1,63 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A GLM Coding Plan key Zhipu or Z.ai refuses says so on its card, in every
// language, naming the vendor and what to do, rather than "Allowance
// unavailable" (@xanahopper on X; zhipuRefused, planquota.go).
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
function server(lang) {
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = ${JSON.stringify({ lang, theme: "light", web: true })};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
// the errors planWindows gives for a refused key, as built from Zhipu's
// real reply ({"code":1000,"msg":"身份验证失败。","success":false})
const errs = [
["Zhipu", "Zhipu didn't take this key (身份验证失败。): it has expired, was deleted, or is mistyped; paste a current one from https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys in the provider's settings"],
["Z.ai", "Z.ai didn't take this key (401 Unauthorized: 令牌已过期或验证不正确): it has expired, was deleted, or is mistyped; paste a current one from https://z.ai/manage-apikey/apikey-list in the provider's settings"],
];
const key = "{vendor} didn't take this key — it expired, was deleted or is mistyped; paste a current one in the provider's settings";
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
test(`${engine}: a refused GLM key's card says the key was refused (${lang})`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width: 440, height: 760 } })).newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang));
await page.goto("http://magpie.test/?view=providers");
await page.waitForFunction(() => typeof quotaError === "function");
const generic = await page.evaluate(() => t("Allowance unavailable"));
for (const [vendor, err] of errs) {
const said = await page.evaluate((e) => quotaError(e), err);
const want = await page.evaluate(([k, v]) => t(k, { vendor: v }), [key, vendor]);
assert.equal(said, want, err);
assert.notEqual(said, generic);
assert.ok(said.startsWith(vendor), `${said} names ${vendor}`);
if (lang !== "en") assert.notEqual(said, key.replace("{vendor}", vendor), `${lang} has its own words`);
}
// the vendor's words alone, from before, are still the generic line
assert.equal(await page.evaluate(() => quotaError("身份验证失败。")), generic);
assert.deepEqual(errors, []);
});
}
}
+44 -2
View File
@@ -96,6 +96,10 @@ func readZhipuPlan(b []byte) (string, []QuotaWindow, error) {
if err := json.Unmarshal(b, &r); err != nil {
return "", nil, err
}
if code, msg, ok := zhipuEnvelope(b); ok && ZhipuKeyRefused(code) {
// the key itself refused, which no plan can be read past
return "", nil, zhipuKeyRefusal{msg}
}
if r.Success != nil && !*r.Success || r.Data == nil {
if r.Msg != "" {
return "", nil, fmt.Errorf("%s", r.Msg)
@@ -510,10 +514,47 @@ func planWindows(ctx context.Context, src planQuotaSource, key string) (plan str
return "", nil, fmt.Errorf("this key has no OpenCode Go subscription: Go belongs to the member who subscribed, in that workspace, so use a key that member made there (opencode.ai, the workspace's API Keys)")
case res.StatusCode == http.StatusUnauthorized && openCode:
return "", nil, fmt.Errorf("OpenCode didn't take this key (%s): it was deleted, or is mistyped", vendorSaid(b, res.Status))
case res.StatusCode == http.StatusUnauthorized && zhipuHost(hostOf(src.url)):
return "", nil, zhipuRefused(src.url, zhipuKeyRefusal{vendorSaid(b, res.Status)})
case res.StatusCode >= 300:
return "", nil, fmt.Errorf("%s", vendorSaid(b, res.Status))
}
return src.read(b)
plan, ws, err = src.read(b)
if r, ok := err.(zhipuKeyRefusal); ok {
err = zhipuRefused(src.url, r)
}
return plan, ws, err
}
// zhipuKeyRefusal is Zhipu or Z.ai refusing a key itself (codes
// 1000–1005: not taken, expired), in their words.
type zhipuKeyRefusal struct{ said string }
func (e zhipuKeyRefusal) Error() string { return e.said }
// zhipuRefused says a refused key's card in words that name the key and
// what to do (@xanahopper on X: a GLM Coding Plan key Zhipu refused showed
// only "Allowance unavailable"), keeping the vendor's own words.
func zhipuRefused(quotaURL string, r zhipuKeyRefusal) error {
vendor, keys := "Zhipu", "https://open.bigmodel.cn/usercenter/proj-mgmt/apikeys"
if hostOf(quotaURL) == "api.z.ai" {
vendor, keys = "Z.ai", "https://z.ai/manage-apikey/apikey-list"
}
said := strings.TrimSpace(r.said)
if said == "" {
said = "key refused"
}
return refusedKeyErr{fmt.Sprintf("%s didn't take this key (%s): it has expired, was deleted, or is mistyped; paste a current one from %s in the provider's settings", vendor, said, keys)}
}
// refusedKeyErr is a card's error for a key Zhipu or Z.ai refused.
type refusedKeyErr struct{ msg string }
func (e refusedKeyErr) Error() string { return e.msg }
func zhipuKeyRefusedErr(err error) bool {
_, ok := err.(refusedKeyErr)
return ok
}
// vendorSaid is the status, and the reason in a vendor's error body
@@ -550,7 +591,8 @@ func vendorSaid(b []byte, status string) string {
// are asked with type=2 (zcode_team.go), and team says so.
func planKeyWindows(ctx context.Context, p Provider, src planQuotaSource, key string) (plan string, ws []QuotaWindow, team bool, err error) {
plan, ws, err = planWindows(ctx, src, key)
if zhipu := strings.HasSuffix(src.url, "/api/monitor/usage/quota/limit"); zhipu && (err != nil || len(ws) == 0) {
// a key refused is refused as a team's too
if zhipu := strings.HasSuffix(src.url, "/api/monitor/usage/quota/limit"); zhipu && (err != nil || len(ws) == 0) && !zhipuKeyRefusedErr(err) {
if tplan, tws, terr := zhipuKeyTeamWindows(ctx, src.url, key, p.ZhipuTeam); terr == nil && len(tws) > 0 {
return tplan, tws, true, nil
}
+5
View File
@@ -486,6 +486,11 @@ func probe(ctx context.Context, p Provider, proto Protocol, url string, body []b
// a GLM Coding Plan's key at Zhipu's pay-as-you-go endpoint
res, err = RetryZhipuCoding(p, req, res, func(r *http.Request) (*http.Response, error) { return p.Do(http.DefaultClient, r) })
}
if err == nil {
// Zhipu's Responses API refuses a key 200, in an envelope: the
// refusal it is, not a green check (@xanahopper on X)
res = ZhipuEnveloped(req, res)
}
r.Millis = time.Since(start).Milliseconds()
if err != nil {
r.Error = strings.TrimPrefix(err.Error(), "Post \""+url+"\": ")
+112
View File
@@ -0,0 +1,112 @@
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)
}
+207
View File
@@ -0,0 +1,207 @@
package provider
import (
"context"
"io"
"net/http"
"strings"
"sync"
"testing"
)
// Zhipu's replies to a key it refuses, byte for byte as open.bigmodel.cn
// answered them on 2026-10-15: 401 at the OpenAI and Anthropic endpoints,
// 200 in the platform's envelope at /api/v1 (the Responses API) and at
// /api/monitor (the plan's quota).
const (
zhipuChat401 = `{"error":{"code":"1000","message":"身份验证失败。"}}`
zhipuAnthropic401 = `{"error":{"message":"身份验证失败。","type":"1000"}}`
zhipuEnvelope1000 = `{"code":1000,"msg":"身份验证失败。","success":false}`
)
// zhipuRefuses plays the GLM Coding Plan's endpoints: "good" is served on
// each, any other key refused as Zhipu refuses it. asked is each path.
type zhipuRefuses struct {
mu sync.Mutex
asked []string
}
func (z *zhipuRefuses) RoundTrip(r *http.Request) (*http.Response, error) {
if r.Body != nil {
io.Copy(io.Discard, r.Body)
}
z.mu.Lock()
z.asked = append(z.asked, r.URL.Host+r.URL.Path)
z.mu.Unlock()
reply := func(status int, body string) (*http.Response, error) {
return &http.Response{StatusCode: status, Status: http.StatusText(status), Header: http.Header{"Content-Type": {"application/json"}},
Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
}
key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
if key == "" {
key = r.Header.Get("x-api-key")
}
good := key == "good"
switch {
case strings.HasSuffix(r.URL.Path, "/models"):
return reply(200, `{"data":[{"id":"glm-5.1"}]}`)
case r.URL.Path == "/api/v1/responses":
if !good {
return reply(200, zhipuEnvelope1000)
}
return reply(200, `{"id":"resp_1","object":"response","status":"completed","output":[{"type":"message","role":"assistant","content":[{"type":"output_text","text":"hi"}]}]}`)
case r.URL.Path == "/api/coding/paas/v4/chat/completions":
if !good {
return reply(401, zhipuChat401)
}
return reply(200, `{"id":"c","choices":[{"index":0,"message":{"role":"assistant","content":"hi"}}]}`)
case r.URL.Path == "/api/anthropic/v1/messages":
if !good {
return reply(401, zhipuAnthropic401)
}
return reply(200, `{"id":"m","type":"message","role":"assistant","content":[{"type":"text","text":"hi"}]}`)
case strings.HasPrefix(r.URL.Path, "/api/monitor/usage/quota/limit"):
if !good {
return reply(200, zhipuEnvelope1000)
}
return reply(200, `{"success":true,"data":{"level":"pro","limits":[{"type":"TOKENS_LIMIT","unit":3,"number":5,"percentage":12}]}}`)
}
return reply(200, `{"code":500,"msg":"404 NOT_FOUND","success":false}`)
}
// zhipuCodingPlan is the zhipu preset on its Coding Plan endpoints.
func zhipuCodingPlan(t *testing.T, key string) Provider {
t.Helper()
p, err := FromPreset("zhipu")
if err != nil {
t.Fatal(err)
}
for _, r := range Preset("zhipu").Regions {
if r.ID == "coding" {
p.Chat, p.Responses, p.Anthropic = r.Chat, r.Responses, r.Anthropic
}
}
if p.Responses != "https://open.bigmodel.cn/api/v1" {
t.Fatalf("coding plan's Responses: %q", p.Responses)
}
p.ID, p.Name, p.Key, p.Models = "glm", "GLM", key, []string{"glm-5.1"}
return p
}
// @xanahopper on X: the editor's Test on a GLM Coding Plan showed OpenAI and
// Anthropic "401 · 令牌已过期或验证不正确" beside a green Responses "25 ms".
// Zhipu's /api/v1 answers a refused key 200 in its envelope; that is the
// refusal it is, on every path that tests an endpoint, and a key Zhipu
// takes is still green there.
func TestZhipuResponsesRefusalNotGreen(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
fake := &zhipuRefuses{}
was := http.DefaultClient.Transport
http.DefaultClient.Transport = fake
t.Cleanup(func() { http.DefaultClient.Transport = was })
bad := zhipuCodingPlan(t, "expired")
res := bad.Test(context.Background())
seen := map[Protocol]bool{}
for _, r := range res {
seen[r.Protocol] = true
if r.OK || r.Status != http.StatusUnauthorized || !strings.Contains(r.Error, "身份验证失败") {
t.Errorf("refused key on %s: %+v", r.Protocol, r)
}
}
if !seen[Responses] || !seen[Chat] || !seen[Anthropic] {
t.Fatalf("endpoints tested: %+v", res)
}
// a model's own test, and Detect APIs, on the Responses API
if r := (Provider{ID: "glm-r", Responses: bad.Responses, Key: "expired", Models: []string{"glm-5.1"}}).TestModels(context.Background(), []string{"glm-5.1"}); r[0].OK || r[0].Status != 401 {
t.Errorf("model test on the Responses API: %+v", r[0])
}
if r := probe(context.Background(), bad, Responses, bad.Responses+"/responses", []byte(`{"model":"glm-5.1","input":"hi"}`), "glm-5.1", testWait); r.OK {
t.Errorf("detect's probe: %+v", r)
}
good := zhipuCodingPlan(t, "good")
for _, r := range good.Test(context.Background()) {
if !r.OK {
t.Errorf("a key Zhipu takes on %s: %+v", r.Protocol, r)
}
}
}
// What ZhipuEnveloped turns into a refusal, and what it leaves alone.
func TestZhipuEnveloped(t *testing.T) {
mk := func(host, ct, body string) (*http.Request, *http.Response) {
req, _ := http.NewRequest("POST", "https://"+host+"/api/v1/responses", nil)
return req, &http.Response{StatusCode: 200, Status: "200 OK", Header: http.Header{"Content-Type": {ct}}, Body: io.NopCloser(strings.NewReader(body))}
}
read := func(res *http.Response) string {
b, _ := io.ReadAll(res.Body)
return string(b)
}
for _, c := range []struct {
body string
status int
}{
{zhipuEnvelope1000, 401},
{`{"code":1001,"msg":"Header中未收到Authorization参数,无法进行身份验证。","success":false}`, 401},
{`{"code":1003,"msg":"Authentication Token 已过期,请重新生成/获取","success":false}`, 401},
{`{"code":1113,"msg":"余额不足","success":false}`, 429},
{`{"code":1310,"msg":"已达到每周使用上限","success":false}`, 429},
{`{"code":1211,"msg":"模型不存在","success":false}`, 400},
{`{"code":1220,"msg":"无权访问","success":false}`, 403},
{`{"code":500,"msg":"404 NOT_FOUND","success":false}`, 502},
{`{"code":"1000","msg":"身份验证失败。","success":false}`, 401},
} {
for _, host := range []string{"open.bigmodel.cn", "api.z.ai"} {
req, res := mk(host, "application/json", c.body)
res = ZhipuEnveloped(req, res)
if b := read(res); res.StatusCode != c.status || !strings.Contains(b, `"error":{`) || !strings.Contains(b, `"message"`) {
t.Errorf("%s %s: %d %s", host, c.body, res.StatusCode, b)
}
}
}
// a reply, another host's envelope, a stream and a long body pass as
// they came
long := `{"id":"r","output":[{"text":"` + strings.Repeat("x", 70<<10) + `"}],"success":false}`
for _, c := range []struct{ host, ct, body string }{
{"open.bigmodel.cn", "application/json", `{"id":"resp_1","object":"response","output":[]}`},
{"open.bigmodel.cn", "application/json", `{"success":true,"data":{}}`},
{"api.example.com", "application/json", zhipuEnvelope1000},
{"open.bigmodel.cn", "text/event-stream", "data: " + zhipuEnvelope1000 + "\n\n"},
{"open.bigmodel.cn", "application/json", long},
} {
req, res := mk(c.host, c.ct, c.body)
res = ZhipuEnveloped(req, res)
if b := read(res); res.StatusCode != 200 || b != c.body {
t.Errorf("%s %s: changed to %d %.80s", c.host, c.ct, res.StatusCode, b)
}
}
}
// The plan's card for a key Zhipu refuses says the key was refused, and
// what to do, with Zhipu's words; it isn't asked again as a team's key.
func TestZhipuRefusedKeyCard(t *testing.T) {
fake := &zhipuRefuses{}
was := http.DefaultClient.Transport
http.DefaultClient.Transport = fake
t.Cleanup(func() { http.DefaultClient.Transport = was })
src, ok := planQuotaSourceOf(zhipuCodingPlan(t, "expired"))
if !ok || !src.sure {
t.Fatalf("coding plan's quota source: %+v %v", src, ok)
}
_, _, _, err := planKeyWindows(context.Background(), Provider{ID: "glm"}, src, "expired")
if err == nil || !strings.HasPrefix(err.Error(), "Zhipu didn't take this key (身份验证失败。)") || !strings.Contains(err.Error(), "open.bigmodel.cn/usercenter/proj-mgmt/apikeys") {
t.Errorf("refused key's card: %v", err)
}
if len(fake.asked) != 1 {
t.Errorf("asked %v, want the plan's quota alone", fake.asked)
}
zai := planQuotaSource{url: "https://api.z.ai/api/monitor/usage/quota/limit", read: readZhipuPlan, sure: true}
if _, _, err := planWindows(context.Background(), zai, "expired"); err == nil || !strings.HasPrefix(err.Error(), "Z.ai didn't take this key") {
t.Errorf("Z.ai's refused key: %v", err)
}
if _, ws, err := planWindows(context.Background(), src, "good"); err != nil || len(ws) != 1 {
t.Errorf("a key Zhipu takes: %v %+v", err, ws)
}
}