Files
magpie/internal/provider/keepalive.go
T
yetone e698e7dddd claude: adding a Claude account is Claude Code's own claude auth login, and magpie never refreshes a Claude sign-in nor asks Anthropic anything with one (the user: 把 magpie 自己的 Claude 登录改成直接用 claude /login,只要体验上没什么差别就改) — magpie traded the sign-in page's code for tokens with Claude Code's OAuth client, asked Anthropic's profile and model list with them, refreshed saved accounts itself (daily keepalive included) and handed a saved account to Claude Code as CLAUDE_CODE_OAUTH_TOKEN. Now Add account runs claude auth login --claudeai in a config directory of magpie's own: the page Claude Code would open comes to magpie's window (Claude Code is given magpie as its BROWSER, which writes the page down and exits), the browser comes back to Claude Code's own listener, and when the browser can't reach this machine the address it ended on, or the code Claude's page shows, is pasted as before and handed to Claude Code. Who signed in is what Claude Code kept (.claude.json, auth status). A saved account in use beside the signed-in one runs Claude Code with CLAUDE_CONFIG_DIR set to its own directory (claude-accounts/ beside magpie's config), its sign-in put there once from logins.json and read back as Claude Code refreshes it; switching to it moves it into Claude Code's own store and removes the directory, as forgetting it does. Claude's models are the catalog's (models.dev), not asked of Anthropic; an imported Claude login is kept as the file has it, and Claude Code refreshes it on first use. Claude Code is required to add a Claude account. TestClaudeSignInByPaste, TestClaudeSignInByPastedAddress, TestClaudeSavedAccountDir (a fake claude CLI, and a server standing in for Anthropic that fails the test if asked) and the reworked sign-in, import and gateway tests fail without the change. With the real Claude Code 2.1.286 in a sandbox directory, its sign-in page (localhost callback) reached magpie's binary and the sign-in waited for the browser; nothing was left behind once it was canceled. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass; claude-risk, plugin-signin, signin-callback, signin-link, signin-paste-codex, routing-signin, own-signin-remove, click-scroll, old-webkit pass.
2026-10-01 16:37:07 +08:00

112 lines
3.4 KiB
Go

package provider
// Keeping saved accounts signed in. A ChatGPT account saved in magpie but
// not the one Codex is signed in to is refreshed only when it is used or
// its allowance looked at — and one waiting its turn (smart
// routing leaves the accounts whose week resets later for days) could sit
// unused past its refresh token's life, and be found signed out just when
// it's needed. So whichever magpie runs the gateway renews each such
// sign-in about once a day. The account the agent is signed in to is the
// agent's own to refresh, and is left to it. A Claude account is never
// refreshed by magpie: Claude Code refreshes it, whenever it runs on it
// (claude_dirs.go).
import (
"context"
"encoding/json"
"errors"
"log"
"strings"
"time"
)
// keepAliveEvery is how long a saved sign-in goes before it is renewed.
const keepAliveEvery = 24 * time.Hour
// Renewal is what came of renewing one saved account.
type Renewal struct {
Agent string `json:"agent"`
User string `json:"user"`
// Renewed is false when it wasn't due; Err is why it failed, and Lapsed
// whether the sign-in is gone (the vendor refused it) or may yet renew.
Renewed bool `json:"renewed"`
Err string `json:"error,omitempty"`
Lapsed bool `json:"lapsed,omitempty"`
}
// RenewLogins renews the saved ChatGPT sign-ins not in the
// agent's hands that have gone every or longer without it; every 0 renews
// all of them.
func RenewLogins(ctx context.Context, every time.Duration) []Renewal {
rememberLogins(false)
loginsMu.Lock()
active := map[string]string{}
for _, a := range loginAgents {
if l, ok := liveLogin(a); ok {
active[a] = l.User
}
}
ls := readLogins()
loginsMu.Unlock()
out := []Renewal{}
for _, l := range ls {
if l.Agent != "codex" || strings.EqualFold(active[l.Agent], l.User) || accountRemoved(l.Agent) {
continue
}
r := Renewal{Agent: l.Agent, User: l.User}
if every > 0 && !renewalDue(l, every, time.Now()) {
out = append(out, r)
continue
}
if _, _, err := renewSavedLogin(ctx, l.Agent, l.User, true); err != nil {
r.Err = err.Error()
var refused refreshRefused
r.Lapsed = errors.As(err, &refused)
} else {
r.Renewed = true
}
out = append(out, r)
}
return out
}
// renewalDue says whether a saved sign-in has gone every without being
// renewed — since magpie last renewed it, or since it was last seen in the
// agent's hands, which kept it fresh — or its refresh token is near its end.
func renewalDue(l savedLogin, every time.Duration, now time.Time) bool {
last := l.Renewed
if l.Seen.After(last) {
last = l.Seen
}
var a struct {
LastRefresh time.Time `json:"last_refresh"`
}
if json.Unmarshal(l.Auth, &a) == nil && a.LastRefresh.After(last) {
last = a.LastRefresh
}
return now.Sub(last) >= every
}
// KeepLoginsAlive renews the saved sign-ins that are due, a minute after it
// starts and every hour after that — a computer that slept through a day
// catches up within the hour of waking — until ctx ends.
func KeepLoginsAlive(ctx context.Context) {
t := time.NewTimer(time.Minute)
defer t.Stop()
for {
select {
case <-ctx.Done():
return
case <-t.C:
}
c, cancel := context.WithTimeout(ctx, 2*time.Minute)
for _, r := range RenewLogins(c, keepAliveEvery) {
if r.Err != "" {
log.Printf("keeping %s account %s signed in: %s", r.Agent, r.User, r.Err)
}
}
cancel()
t.Reset(time.Hour)
}
}