Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

provider: a plugin's 401 about the model keeps the account's sign-in (plugins#468)

yetone3ec25523cbd5
diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go
index 7b05fdff6..3ad2aad64 100644
--- a/internal/gateway/fallback.go
+++ b/internal/gateway/fallback.go
@@ -1188,7 +1188,9 @@ func quotaSaid(msg string) bool {
// unservedWords are how a vendor says the model isn't one it serves this
// key, or this way — words another provider, or key, may not answer with.
-var unservedWords = regexp.MustCompile(`(?i)model.{0,80}(not (supported|accessible|available|found|enabled|allowed)|unsupported|does ?n[o']t exist|unknown|invalid)|(no such|unknown|invalid|unsupported) model|model_not_found|模型.{0,12}(不存在|不支持|无权|未开通)`)
+// provider.ModelUnserved owns them: a plugin's 401 that says them doesn't
+// mark the account's sign-in either.
+var unservedWords = provider.ModelUnserved
// modelRefused says the vendor turned the request away over its model
// alone — not one this key's plan, or this key, may use: SenseNova's 403
diff --git a/internal/provider/plugin_signin_model_test.go b/internal/provider/plugin_signin_model_test.go
new file mode 100644
index 000000000..fbe3b16e6
--- /dev/null
+++ b/internal/provider/plugin_signin_model_test.go
@@ -0,0 +1,100 @@
+package provider
+
+import (
+ "context"
+ "io"
+ "net/http"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/plugin"
+ "github.com/yetone/magpie/internal/testenv"
+)
+
+// A plugin answering 401 for a model the account may not use, and saying
+// nothing of the sign-in, leaves the account's sign-in as it is: the
+// gateway fails the request over to every account, and each was marked
+// as needing a new sign-in for a credential that was fine (plugins#468).
+// A 401 about the sign-in still marks it, one naming a model beside its
+// token words included, and the body reaches the gateway whole.
+func TestPluginModel401KeepsSignIn(t *testing.T) {
+ bun := testenv.Bun(t)
+ claudeHome(t)
+ t.Setenv("MAGPIE_BUN", bun)
+ t.Cleanup(plugin.Settle)
+ ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
+ defer cancel()
+ abs, _ := filepath.Abs("../plugin/testdata/fake/index.js")
+ if _, err := plugin.Add(ctx, abs); err != nil {
+ t.Fatal(err)
+ }
+ key, err := plugin.Import(ctx, "fakeco", map[string]any{"type": "oauth", "refresh": "r-ok", "access": "a", "expires": 9e15, "accountId": "ok@fake"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ saveLogins(t, savedLogin{Agent: "plugin:fakeco", User: "ok@fake", Home: key, On: true})
+ if _, err := plugin.Providers(ctx); err != nil {
+ t.Fatal(err)
+ }
+ pp := mustPlugin(t)
+ lapsed := func() bool {
+ for _, l := range pluginLogins(mustPlugin(t)) {
+ return l.Lapsed != ""
+ }
+ t.Fatal("no account")
+ return false
+ }
+ answer := func(status int, body string) {
+ t.Helper()
+ resp := &http.Response{StatusCode: status, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(body))}
+ notePluginSignIn(pp, key, resp)
+ got, err := io.ReadAll(resp.Body)
+ if err != nil || string(got) != body {
+ t.Fatalf("the body after the check: %q, %v; want %q", got, err, body)
+ }
+ }
+ for _, body := range []string{
+ `{"error":{"message":"The model claude-opus-5 is not available on your plan"}}`,
+ `{"error":{"code":"model_not_found","message":"unknown model"}}`,
+ `{"error":{"message":"模型不支持"}}`, // 模型不支持, escaped as a vendor sends it
+ } {
+ answer(http.StatusUnauthorized, body)
+ if lapsed() {
+ t.Fatalf("a 401 about the model marked the sign-in: %s", body)
+ }
+ }
+ // and every 401 body the community plugins' tests hold for a sign-in
+ // that is gone (magpie-community/plugins at 95fa761): each one marks
+ for _, body := range []string{
+ `{"error":{"message":"invalid token"}}`,
+ `{"error":{"message":"model gpt-x: invalid api key"}}`,
+ ``,
+ `{"code":"unauthenticated","message":"invalid api key"}`, // devin
+ `{"code":"unauthenticated","message":"bad key"}`, // devin
+ `{"code":"upstream","message":"bad key","upstream_status":401}`, // zed
+ `unauthorized`, // zed, raccoon
+ `{"error":{"message":"nope"}}`, // cline
+ `{"success":false,"error":"unauthorized"}`, // cline
+ `{"message":"expired"}`, // cline, search1api
+ `the sign-in lapsed — sign in again`, // cline
+ `{"code":200003,"message":"authorization_verify_error"}`, // raccoon
+ `{"code":401,"data":null,"msg":"登录票据已失效"}`, // joycode
+ `private-marker`, // joycode
+ `{"code":1001,"msg":"Authorization Token非法"}`, // zcode
+ `{"error":{"message":"token expired or incorrect"}}`, // zcode
+ `{"code":401}`, // mimo
+ `{"error":{"message":"stale"}}`, // mimo
+ `{"error":{"message":"Invalid API Key"}}`, // mimo
+ `no`, // cursor
+ `Unauthorized — sign in to Cursor again in magpie`, // cursor
+ `{"code":"unauthenticated","message":"Error","details":[{"debug":{"error":"ERROR_NOT_LOGGED_IN","details":{"title":"Authentication error","detail":"If you are logged in, try logging out and back in."}}}]}`, // cursor
+ } {
+ answer(http.StatusOK, "{}")
+ answer(http.StatusUnauthorized, body)
+ if !lapsed() {
+ t.Fatalf("a 401 about the sign-in didn't mark it: %q", body)
+ }
+ }
+}
diff --git a/internal/provider/plugins.go b/internal/provider/plugins.go
index 4583823ea..354d2de13 100644
--- a/internal/provider/plugins.go
+++ b/internal/provider/plugins.go
@@ -6,6 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
+ "io"
"net/http"
"regexp"
"slices"
@@ -644,11 +645,48 @@ func pluginFetch(pp plugin.Provider, account string, req *http.Request) (*http.R
// clears the mark.
const SignInHeader = "X-Magpie-Sign-In"
+// ModelUnserved are how a vendor says the model isn't one it serves this
+// key, or this way — words another provider, or key, may not answer with
+// (the gateway's unservedWords, read decoded: catalog.Words).
+var ModelUnserved = regexp.MustCompile(`(?i)model.{0,80}(not (supported|accessible|available|found|enabled|allowed)|unsupported|does ?n[o']t exist|unknown|invalid)|(no such|unknown|invalid|unsupported) model|model_not_found|模型.{0,12}(不存在|不支持|无权|未开通)`)
+
+// signInWords are words of a refusal about the sign-in itself, which a
+// model named beside them doesn't make the model's: "model gpt-x: invalid
+// token" is the token.
+var signInWords = regexp.MustCompile(`(?i)token|api.?key|credential|sign.?in|log.?in|expired|session|令牌|密钥|登录|过期`)
+
+// modelOnly401 says a 401 a plugin answered without SignInHeader is about
+// the model, not the account's sign-in: its body says the model isn't
+// served (ModelUnserved) and nothing of the sign-in. A plugin answering
+// "this model isn't available to you" with 401 marked every account the
+// request failed over to as needing a new sign-in (plugins#468), for a
+// credential that was fine. Only the start of the body is read, and given
+// back whole for the gateway to read as before.
+func modelOnly401(resp *http.Response) bool {
+ if resp.StatusCode != http.StatusUnauthorized || resp.Body == nil {
+ return false
+ }
+ head, err := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
+ resp.Body = struct {
+ io.Reader
+ io.Closer
+ }{io.MultiReader(bytes.NewReader(head), resp.Body), resp.Body}
+ if err != nil || len(head) == 0 {
+ return false
+ }
+ words := catalog.Words(head)
+ return ModelUnserved.Match(words) && !signInWords.Match(words)
+}
+
// notePluginSignIn marks or clears an account's lapse as the plugin's
-// answer says, and takes SignInHeader off it.
+// answer says, and takes SignInHeader off it. A 401 it says nothing of
+// that is about the model alone leaves the account as it is (kept).
func notePluginSignIn(pp plugin.Provider, account string, resp *http.Response) {
said := strings.ToLower(strings.TrimSpace(resp.Header.Get(SignInHeader)))
resp.Header.Del(SignInHeader)
+ if said == "" && modelOnly401(resp) {
+ said = "kept"
+ }
notePluginSaid(pp, account, said, resp.StatusCode)
}