From 35aa50cfb33a427681841ca2eb366b0cda5ebdc7 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 15 Oct 2026 15:55:16 +0800 Subject: [PATCH] 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) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 ", 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. --- docs/subsystems/gateway-routing.md | 1 + docs/subsystems/providers-accounts.md | 1 + internal/gateway/gateway.go | 5 +- internal/gateway/zhipu_envelope_test.go | 68 +++++++ internal/gui/assets/app.js | 4 + internal/gui/assets/i18n.js | 4 + internal/gui/tests/glm-quota-error.test.cjs | 63 ++++++ internal/provider/planquota.go | 46 ++++- internal/provider/test.go | 5 + internal/provider/zhipu_envelope.go | 112 +++++++++++ internal/provider/zhipu_envelope_test.go | 207 ++++++++++++++++++++ 11 files changed, 513 insertions(+), 3 deletions(-) create mode 100644 internal/gateway/zhipu_envelope_test.go create mode 100644 internal/gui/tests/glm-quota-error.test.cjs create mode 100644 internal/provider/zhipu_envelope.go create mode 100644 internal/provider/zhipu_envelope_test.go diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index ad2bc2c98..e26e2fbaf 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -103,6 +103,7 @@ recorded as a prediction failure (`noPrediction`). - A usage record carries its prompt's cache beside `in` and `out` (#1839): `cache_read` (tokens read from the vendor's cache) and `cache_write` (cache creation, Anthropic's `cache_creation_input_tokens`; `cache_write_1h` the part written for an hour). `in` holds neither. Both are written on every record, 0 too, so a prompt that missed the cache reads as that. A record from before then has neither and reads as 0. Every route fills them: Anthropic's messages, Chat (OpenAI's `prompt_tokens_details.cached_tokens`, DeepSeek's `prompt_cache_hit_tokens`), Responses (`input_tokens_details.cached_tokens`) and Gemini (`cachedContentTokenCount`), passed through or translated, whole or streamed, a plugin's fetch, and the Claude subscription bridge. System One's decision calls report no cache. `TestUsageRecordsCacheTokensOnEveryRoute`, `TestPluginUsageRecordsCacheTokens`, `TestClaudeSubscriptionUsageKeepsCacheTokens`, `TestRecordAlwaysCarriesCacheTokens`. - A request whose key is a Claude sign-in (`claudeSignIn`: `Authorization: Bearer sk-ant-oat…`, Claude Code signed in to claude.ai with magpie as its base URL) is never told a 401, nor a 403 saying "OAuth token has been revoked". magpie never passes that sign-in on, so such an answer is a provider refusing magpie's credential, or one of magpie's own Claude accounts lapsing; told it, Claude Code renews its own sign-in before each of its retries (ten for one request) and then asks to `/login`. Any error whose message mentions x-api-key, whatever its status, Claude Code tells as "Not logged in · Please run /login" too. It is told as a 502 in magpie's words, an `api_error` saying " refused magpie's credential (HTTP 401): …" with x-api-key said as "API key", and any other error such a request is told keeps its status with x-api-key said as "API key", as does a stream's error after its 200 (`keepsSignIn`, `claude_signin.go`). Recent calls and the usage log keep the provider's status and message. Any other 403, and a request with magpie's key or an API key, is answered as before. The sign-in's beta (`oauth-…` in `anthropic-beta`) isn't passed on either (`askedBetas`), so a provider gets the request as Claude Code with magpie's key sends it; a provider's own `header.anthropic-beta` still goes. - A 2xx that can't be an API's answer is the 502 it stands for (`notAnAPIReply`, #1012): a web page (`text/html`, or a body that begins as one: a sign-in page, Cloudflare's challenge), a body with nothing in it, or one sent as JSON that doesn't begin as JSON. Every upstream request goes through it (`forwardOnce`, and the built-in clients' own: the ChatGPT backend's `/responses`, Kiro, Zed, Qoder, Devin, Cursor, Command Code), so it fails over, rests and is logged as a 502 does, its reason naming the page's title. Only the first bytes are peeked, which a stream waits for anyway, and a compressed body is left as it came. +- A 2xx from Zhipu or Z.ai holding the platform's refusal envelope (`{"code":1000,"msg":…,"success":false}`, which their Responses API at `/api/v1` answers a refused key) is the refusal it stands for (`provider.ZhipuEnveloped` in `forwardOnce`): 401 for a key refused, 429 for a limit or no balance, as Zhipu's error codes give, so it fails over and rests as those do and the agent is told why. `TestZhipuResponsesRefusalIsRefusal`. - A streamed request is never left silent while its vendor says nothing. `holdWriter.watch` runs beside each try: past `keepHeldAfter` (15s) it sends a held try's agent the stream's 200 and SSE comments (`keepAlive`), none of the try, so another candidate may still answer in the same stream; once the reply passes, it puts a comment between two of its lines after `keepaliveEvery` of quiet. It stops after `keepaliveLongest` (5 minutes) with nothing from the vendor. A try waiting for its key's or account's slot or for room in its minute (`lanes.take`, `rpms.wait`) is kept alive the same way (`keepQueued`), for as long as it waits; once the 200 is out, the try is held, and its failure or its queue turning it away reaches the agent as the stream's error (`failTo`), not a status (coeo91 on Discord). A wait shorter than `keepHeldAfter` sends nothing, so its 429 keeps its `Retry-After`. A proxy in front such as Cloudflare (125s) otherwise ends the request (#947). Gemini streams get no comments (#934). A vendor that then ignores `stream:true` and answers 200 with its reply whole has it sent as the agent's stream (`wholeAsStream`: Chat, Responses, Anthropic), not as the stream's error, while a reply under a type that says neither JSON nor a stream is held as a stream when its first bytes are one (`sseStart`), read event by event like one that says so, so an error among its frames still goes to the next candidate (#1418: it went through at once); a 200 that is no reply of the protocol's fails as a translated reply that didn't stream does (502, "… did not stream"), for the next candidate to answer, and the last one's reaches the agent as the stream's error. A held stream that has sent nothing but the frames before a reply (`response.created`, `response.in_progress`, `codex.rate_limits`, pings, an empty part begun, and any event `streamEvent` doesn't know to carry text, reasoning, a call or a reply's end (`replyEvent`), or an item not known that isn't a call or a tool's (`streamPart.said`): `eventLead`; Aliceonly on #1418: an unknown event was taken for content and let a frames-only 200 through, and its `server_is_overloaded` reached Codex with five candidates left) stays held as long as its agent is kept alive, up to `holdLead` (4 minutes, under the 300s Codex waits for an event; `keptQuiet`), so a `server_is_overloaded` that comes after it is a failure the next candidate answers (#1418: let through at 15s, the ChatGPT backend's failure 36s in ended Codex's turn with sub2api, next in the group, never asked). A stream whose agent can't be kept alive (Gemini's) is let through after `holdLongest` (15s), as before. Codex counts only events toward that 300s, not comments, so the bound is the request's, not each try's: once Codex on Responses has heard no event for `agentQuietMost` (4 minutes) since the request began or its last event (`keptAlive.tooQuiet`), the try in hand is let through (`scan`, `keepQuiet`), and no group replan or same-one retry is taken whose pause would end past it (fadenoob on Discord: held tries and replan pauses added up past 300s and Codex reconnected on "idle timeout waiting for SSE"). A translated reply whose upstream stream stops before it said its reply had — an Anthropic one with no stop_reason and no message_stop, a Responses one with no `response.completed`, the same two a relayed one is told by (`sniff.whole`; a Chat stream may end without `[DONE]` and be whole), a Gemini or Code Assist one whose last chunk has no candidate's `finishReason` (`geminiEnds`, #1643: `usageMetadata` is no end, Vertex AI sends it on every chunk; a chunk with no candidate at all is the empty reply's to answer, #667), and a relayed Gemini one told the same way (#1644; it ends in Gemini's own `{"error":{"code":502,…,"status":"UNAVAILABLE"}}` data line from `streamFailure`, `TestGeminiRelayEndedShort`) — ends the turn with "the reply ended before it was complete" (`errEndedShort`, `TestResponsesUpstreamEndedShort`, `TestGeminiUpstreamEndedShort`), asked again in place where the upstream goes on from a prefill (`continuation.go`). A client that asked for no stream is told the same 502 of such a cut (`translate`, `TestNonStreamEndedShort`, `TestGeminiNonStreamEndedShort`), rather than handed what came as its whole reply. A translated reply from an Anthropic or Responses upstream that ended but said nothing (no text, call, search or image) and counted no token at all is no reply either, whatever its end says (`repliesCounted`, #2086: an Anthropic-compatible proxy's 200 ended a Codex turn as `response.completed` with no output, no usage and no served model, and Codex didn't ask again). It is the empty reply's to answer (#667): asked again in place, then failed with "an empty reply", streamed or not, for every client (`TestUncountedEmptyReplyFails`, `TestUncountedEmptyReplyFailsEveryClient`). Claude's own empty `end_turn` counts its prompt and stays a whole reply (`TestWellFormedStreamsStillComplete`). A reply passed through in its own protocol isn't read this way. - Claude's, GPT's and Gemini's reasoning is held (`refusesAfterThinking`, up to `holdThinking`, 4 minutes) so that a refusal after it goes to the next candidate unseen (#248). It is held only while one could: on the last candidate a refusal isn't asked again, so Claude's and GPT's reasoning streams as it comes there, and a refusal after it reaches the agent as the vendor's own. Held there, a lone relay's Claude or GPT showed Claude Code its thinking all at once with the text, and Codex none until then (iTianbao on X). Gemini's stays held on the last candidate too, for a reply that only reasoned to be asked again (#667). Any other model's reasoning is never held. - A streamed reply stuck in a loop is ended, not let run to its output limit (#1359, Moody-Sin: WorkBuddy's DeepSeek v4.1 flash reasoned round "Now." "Writing." "Go." "Let me write." "OK." until max tokens while dsh and Pi waited). `holdWriter.Write` feeds every streamed try, passed through or translated, a key's, a built-in subscription's or a plugin's (a moved WorkBuddy's fetch in the plugin host, `TestLoopEndsWorkBuddysReply`), in each of the agent's protocols, to a `loopGuard` ([`loop_guard.go`](../../internal/gateway/loop_guard.go)). It cuts the reasoning and the text, each apart, into units, its lines and sentences (a list's `1.` or a decimal is no sentence's end), compared without case or a closing stop. A unit with no word in it (a letter run with no digit: not a brace, a rule, `0x00`, a hash or a row of numbers) isn't counted. When the last `loopWindow` (256) counted units of either are among no more than `loopDistinct` (24) different ones, the try is cut (`cutLoop`): what came with that write goes out, then the protocol's stream error (`streamError`, 502) naming the loop and quoting its units, and the vendor's request is cancelled. It falls back to nobody and rests nobody (`failLoop`); its usage record's error type is `reply_loop` (`usage.LoopErrType`), and Usage counts them per model (`Totals.Loops`), as "{n} looped" beside the model's failures in the Overview's rows and the Requests ranking (#1858, `TestLoopsCountedPerModel`, `usage-loops.test.cjs`). A reply magpie translates into the agent's protocol (`streamTranslated`) whose *reasoning* loops before it has said a text or a call, and isn't a continuation, is asked again once in place instead (`loopReasks`, through `holdWriter.onLoop`; cdredfox on X, WorkBuddy AI's DeepSeek v4 flash): the agent keeps the reasoning it has, the next try's follows it in the same stream, as an empty reply's re-ask does (#667), and only a loop on that try ends the reply with the error (`TestReasoningLoopIsAskedAgain`). A loop in the text, or after a text or call, is ended at once (`TestLoopAfterTextIsNotAskedAgain`), and so is a Chat stream passed through as it comes, whose bytes aren't magpie's to splice. A cycle need not be exact. Code, tables, lists, logs, CSV and base64 differ line to line or have no words, and don't trip it (`TestLoopGuardLeavesOrdinaryRepliesAlone` feeds magpie's own sources and docs through it). A reply sent whole (no stream, or Gemini without `alt=sse`) isn't read. Settings › Models › Replies › *Stop looping replies* (`noLoopGuard`) turns it off. diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index ab0260f00..c1f0bfcd2 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -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 ` didn't take this key (): …` 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 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) | diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index cb4619a02..d25674944 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -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) diff --git a/internal/gateway/zhipu_envelope_test.go b/internal/gateway/zhipu_envelope_test.go new file mode 100644 index 000000000..05e4238e7 --- /dev/null +++ b/internal/gateway/zhipu_envelope_test.go @@ -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) + } + }) + } +} diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index ed0f1fa71..5894b91f6 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -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"); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index a062373aa..9e1c85ba8 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -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", diff --git a/internal/gui/tests/glm-quota-error.test.cjs b/internal/gui/tests/glm-quota-error.test.cjs new file mode 100644 index 000000000..b2590749f --- /dev/null +++ b/internal/gui/tests/glm-quota-error.test.cjs @@ -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, []); + }); + } +} diff --git a/internal/provider/planquota.go b/internal/provider/planquota.go index 09d1f83cc..404f12edf 100644 --- a/internal/provider/planquota.go +++ b/internal/provider/planquota.go @@ -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 } diff --git a/internal/provider/test.go b/internal/provider/test.go index 364c16f57..fad0f9144 100644 --- a/internal/provider/test.go +++ b/internal/provider/test.go @@ -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+"\": ") diff --git a/internal/provider/zhipu_envelope.go b/internal/provider/zhipu_envelope.go new file mode 100644 index 000000000..81af6f73c --- /dev/null +++ b/internal/provider/zhipu_envelope.go @@ -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) +} diff --git a/internal/provider/zhipu_envelope_test.go b/internal/provider/zhipu_envelope_test.go new file mode 100644 index 000000000..cc4a579a0 --- /dev/null +++ b/internal/provider/zhipu_envelope_test.go @@ -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) + } +}