accounts: a name you gave an account picks it wherever an email does (#4532)

StringKe (#4532): `magpie accounts switch claude work` failed when "work"
was the alias; accountNamed matched the email only.

provider.AccountByName resolves a name (magpie accounts alias) among an
agent's accounts. It refuses a name two accounts share, and a name that
is another account's email or email part, so a name never picks the wrong
account. It is used by:
- accountNamed: accounts switch/on/off/remove/alias/cap and the rest
  that take <email>;
- provider pool --accounts;
- accountRef (GUI and account-cap): the exact email first, then a name,
  so another account's alias never shadows an email;
- account-cap's display, through AccountRefOf (it filtered by email).

Run (mote, at this commit):
- go test -timeout 45m -count=1 ./internal/provider ./internal/cli: ok
  (104.9s, 33.2s).
- TestAccountsAliasPicksTheAccount, new: switch, alias, pool --accounts
  and account-cap by name; a shared name and another account's email
  refused. Red with each part removed by hand: the accountNamed call,
  pool's resolution, the clash check, the shared-name check, accountRef's
  name step.

Not run: the GUI suite (no GUI file changed); real accounts.
This commit is contained in:
yetone
2026-10-31 18:18:37 +08:00
parent 15b83901ac
commit 149e763e9e
9 changed files with 179 additions and 9 deletions
+6 -1
View File
@@ -2438,7 +2438,12 @@ name in its provider's editor, or `magpie accounts alias <agent> <email>
<name>` (`--clear` takes it off). The name is magpie's, kept in
providers.json; the vendor's or plugin's sign-in is never written to. It
shows on the account's Usage card, in the menu bar, in `magpie accounts`,
`magpie quota` and `GET /v1/magpie/quotas` (`alias`). A GLM Coding Plan
`magpie quota` and `GET /v1/magpie/quotas` (`alias`). The name picks the
account wherever its email does: `magpie accounts switch claude Work`,
`forget`, `alias`, `provider pool <id> --accounts` and `provider
account-cap`. magpie refuses a name two accounts have, or one that is
another account's email, rather than pick one by guess; `next` after
`switch` is always the next account (see above). A GLM Coding Plan
seat added both as a key and as a signed-in ZCode account is shown once, on
the account's card (two cards would count its allowance twice); that card
is then named for the key's provider until you name it yourself, and says
+1 -1
View File
@@ -65,7 +65,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
| A lab's models | models.dev keeps two catalogs: `api.json`, each provider's models with that host's prices, and `models.json`, each lab's models with only what is the model's on every host (name, window, reply limit, thinking, inputs, release), no price. `Sync` keeps the second beside the first as `labs.json` (`LabsPath`, `syncLabs`: best effort, through a rename, a failed fetch keeping the last; a catalog with none beside it is `Stale` once a process, so it comes at the next look). A model only a lab lists, no provider (models.dev took the gated Claude Mythos 5.1 out of anthropic's list in #11327 and kept its lab file), is voted into the same tables as a listed one (`loadGen`, `labs`), so `ContextOf`, `OutputOf`, `NameOf`, `Thinks`, `SeesImages` and every entry built on them know it wherever a vendor's or an account's list has it; a thinking one with no levels takes the levels of the newest of its family a provider gives them (`labKinEfforts`: Mythos 5.1 takes Mythos 5's). A model a provider lists keeps what providers say of it. `catalog.Describe` builds a model from these for a list that names an id alone. `TestLabOnlyModelIsKnown`, `TestLabsLeaveListedModels`, `TestSyncKeepsLabs`, `TestAnthropicKeyGatedModelDescribed` (iebb on Discord). | [`labs.go`](../../internal/catalog/labs.go), [`catalog.go`](../../internal/catalog/catalog.go) |
| A Claude account's models | magpie never asks Anthropic with a Claude sign-in, so a Claude account's list is models.dev's anthropic list and what Anthropic told the account's Claude Code beyond it. Claude Code keeps that in its `.claude.json` from its own bootstrap: `additionalModelOptionsCache` (models its /model picker offers beyond its own; a `null` value or a `disabled` one is not a model), `modelAccessCache` (`entitled` per API id) and `additionalModelCostsCache` (Anthropic's prices). `claudeModels` reads the file of Claude Code's own sign-in (`claudeProfilePath`) and of each saved account's directory (`claudeAccountDir`), through `filememo`, and adds each model none of them lists, described by `catalog.Describe` and priced as Anthropic told it. `Account.Lists` for a Claude account goes by its own file (`claudeLists`: the saved directory's, or Claude Code's own when its `oauthAccount` is that account, the one Anthropic answered last): a model it isn't entitled to is out, so routing tries the accounts entitled to a gated model first; with no file, every model is taken to be in, as before. `ListPrice` of a provider whose catalogs include anthropic falls back to that price after every catalog (`claudeCodePrice`). The agent's own Claude Code model picker (`claudeOwn`) offers what `ClaudeCodeModels` gives for the account signed in here; a WSL distro's keeps the catalog's. Not done: a Claude Code that never started on a saved account has no file, so its gated models show only once it has run there. `TestClaudeAccountListsGatedModels`. | [`claude_code_models.go`](../../internal/provider/claude_code_models.go), [`account.go`](../../internal/provider/account.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`claude.go`](../../internal/agent/claude.go) |
| A key's own windows | A sub2api key given a spending limit per 5 hours, day or 7 days answers its `/v1/usage` with `rate_limits` and no `remaining` (`readSub2APIKeyLimits`). With the Balance URL set to it, the key's card shows them as the windows *5 hours*, *1 day*, *7 days*, in USD, beside a balance field the user wrote; *Check balance* and `magpie provider show` give what its fullest window has left (`Balance`). A Balance URL at an account query left without its token (a sub2api panel's `/api/v1/user/profile`, new-api's `/api/user/self`, after the token was removed) asks the same panel's query for the key instead, the saved URL untouched (`keyQueryOf`, `BalanceQuery`), unless the user's Headers carry an Authorization or Cookie of their own. A Balance URL of the user's own is asked with GET, or with POST and no body when the provider's `BalanceMethod` says so (#2368: an endpoint that answers only a POST; the editor's GET/POST beside the URL, `balance.method=` on the command line); any other method is refused before anything is sent (`balanceMethodOf`). `KeyAllowance` gives routing the same windows: never waited for, read in the background at most once a minute, a failed read keeping the last, and seeded from the card's last reading (`quotas.json`) after a restart. A key bought as a plan (Kimi Code, GLM Coding Plan and Z.ai, MiniMax Coding Plan, OpenCode Go, Command Code, Ollama Cloud: `planQuotaSourceOf`) gives routing its card's windows the same way (`planKeyWindows`, Zhipu's team quota behind a key with none of its own); the Usage page's read of its card is taken at once (`noteKeyAllowance`), and a key there that turns out pay-as-you-go, with no windows, is asked again only every 30 minutes (`keyNoWindowsAge`). Kimi Code's `/usages` (`readKimiCode`) is read as kimi-cli and kimi-code read it: the week's `usage` and each `limits[]` window as counts, and the shares in `usages` (`limit_5h`, `limit_7d`, and `limit_month_total` as a *Month* window renewing at its `reset_time`, lidazi2016 on Discord); a window told both ways is the share's, and `limit_month_code`, the part of the month code used, is no window. `TestReadKimiCode`, `TestReadKimiCodeMonth`. A Command Code plan's key has its month of credits as a *Credits* window beside the 5-hour and weekly ones, as the signed-in subscription's card has (`cmdKeyWindows`, #2451): billing/credits leaves the plan out, so it is the key's billing/subscriptions plan, asked at most every ten minutes and the last one kept while it can't be read; the same reply's period end is the Credits window's reset, left off once it has passed (#2454); a key whose plan was never read has its two windows alone. Ollama Cloud's `ollama.com/api/balance` (#1888, `readOllamaPlan`) tells the plan's included allowance as one window in USD, *Month* when its period is a month long, renewing at `period.until`, and Aside while credits bought on top are left; those credits are the key's balance card (`readOllamaCredits`), and a reply that names none has no balance card rather than $0. StepFun's Step Plan is read through a platform sign-in, not the key, and isn't one of them: the sign-in is the provider's own, kept by provider id in `stepfun-auth.json` (two StepFun providers on one site can be two accounts, #2384), one card per signed-in provider; a file from before that, kept by site, is given on read to the StepFun providers on that site (`stepfunBySite`), and copies of one sign-in are renewed together. Nor are Volcengine Ark's Coding Plan and Agent Plan (#1427): their 5-hour, weekly and monthly windows are told only to the account's access key (`AccessKeyID`, `SecretAccessKey`), asked of `open.volcengineapi.com` (`GetCodingPlanUsage`, `GetAFPUsage`) and signed as Volcengine's own SDK signs (`volcSign`), so they are cards on the Usage page (`volcPlanQuotas` in `PlanQuotas`), never routing's windows. Nor is Tencent Cloud's Token Plan 企业版 (#1574): what a team plan has used of its cycle's credits (专业套餐) or tokens (轻享套餐) is told only to the account's SecretId and SecretKey (kept as `AccessKeyID`, `SecretAccessKey`), asked of `tokenhub.tencentcloudapi.com` (`DescribeTokenPlanList`, `DescribeTokenPlan`, version 2026-03-22) and signed TC3-HMAC-SHA256 (`tc3Sign`), one card per team plan (`tencentPlanQuotas`). | [`sub2api_usage.go`](../../internal/provider/sub2api_usage.go), [`key_allowance.go`](../../internal/provider/key_allowance.go), [`volcengine_usage.go`](../../internal/provider/volcengine_usage.go), [`tencent_usage.go`](../../internal/provider/tencent_usage.go) |
| Account names and seats | `AccountNames` (by the account, in lower case, like `AccountCaps`) are names the user gives accounts, set by `SetAccountName` (GUI `provider/accountname`, `magpie accounts alias`); they live in providers.json only, never in a vendor's or plugin's sign-in. A GLM Coding Plan read with a key (`glmPlan`) and a ZCode account (built-in or `zcode-plugin`) whose windows' resets agree are one seat (`seatMatch`, #90/#953), shown once, on the account's card (`seatCards`, used by `quotas`, `Allotted` and `CachedCards`). A match is remembered in `seats.json` beside `quotas.json`: a failed read or a window with no reset yet is unknown and keeps the key's card off while the account is signed in; windows that disagree forget it (#1515). Cards carry `Seat` (the key provider's name, and the key's when it has several) and `Alias` (the user's name, else `Seat`), as `/v1/magpie/quotas`, `magpie quota` and `magpie accounts` do. Records (a trace's `who`, usage's `ProviderAccount`) keep the vendor's name, the key the user's name is kept by, and every list of them looks the name up as it is shown (`AccountShown`, `AccountShownOf`, `AccountRef.Shown`), so a request from before a rename reads by the new name too: the Routing page's accounts and requests (`userShown` in `plugins/routing/client.js`, from `/api/providers`' `accountNames`), its Several accounts pools (`onOf`), the Usage page's Accounts and the request log's Account filter (`usageapi`), `magpie usage`, and a gateway key's accounts (`AccountNames`, `/api/caller-keys`). Before plugins#310 (a renamed Kiro account read by its old name on every request after) those showed the vendor's name. An account with no name of the user's own goes by the name its plugin's `usage()` gives it (`PluginUserOf`, the `user` of its last read: `loginUsageCache`, else `quotas.json`), else by its id: a Huawei Cloud CodeArts account kept by its IAM id `iam::<domain>:user:<name>` reads as the masked phone its card shows (#4416). `AccountShown`, `AccountShownOf` and `AccountLabelOf` (cards' `Alias`, `magpie accounts`, usageapi's Account filter, the quota alert) apply it, and the GUI has it as `/api/providers`' `accountUsers` (`accountShownOf` in app.js: the editor's rows, the per-account proxy lines, Routing's `userShown`, Hide accounts). The id stays the key everything is kept by; nothing stored changes. A read that fails keeps the last good `user`; nothing read yet, or a plugin whose windows are all model pools (not kept in `quotas.json`) after a restart, is its id until the next read. | [`account_names.go`](../../internal/provider/account_names.go), [`account_seats.go`](../../internal/provider/account_seats.go) |
| Account names and seats | `AccountNames` (by the account, in lower case, like `AccountCaps`) are names the user gives accounts, set by `SetAccountName` (GUI `provider/accountname`, `magpie accounts alias`); they live in providers.json only, never in a vendor's or plugin's sign-in. A name picks its account wherever the account's own name does (`AccountByName`): the CLI's `accountNamed` (switch, forget, alias), the pool's `--accounts`, and `accountRef` (caps, models, weights, concurrency) after an exact name. It is refused when two accounts have it or it is another account's email or name, so it never picks by guess; `accountRef` then finds no account, as the GUI passes exact names (StringKe in #4532, `TestAccountsAliasPicksTheAccount`). A GLM Coding Plan read with a key (`glmPlan`) and a ZCode account (built-in or `zcode-plugin`) whose windows' resets agree are one seat (`seatMatch`, #90/#953), shown once, on the account's card (`seatCards`, used by `quotas`, `Allotted` and `CachedCards`). A match is remembered in `seats.json` beside `quotas.json`: a failed read or a window with no reset yet is unknown and keeps the key's card off while the account is signed in; windows that disagree forget it (#1515). Cards carry `Seat` (the key provider's name, and the key's when it has several) and `Alias` (the user's name, else `Seat`), as `/v1/magpie/quotas`, `magpie quota` and `magpie accounts` do. Records (a trace's `who`, usage's `ProviderAccount`) keep the vendor's name, the key the user's name is kept by, and every list of them looks the name up as it is shown (`AccountShown`, `AccountShownOf`, `AccountRef.Shown`), so a request from before a rename reads by the new name too: the Routing page's accounts and requests (`userShown` in `plugins/routing/client.js`, from `/api/providers`' `accountNames`), its Several accounts pools (`onOf`), the Usage page's Accounts and the request log's Account filter (`usageapi`), `magpie usage`, and a gateway key's accounts (`AccountNames`, `/api/caller-keys`). Before plugins#310 (a renamed Kiro account read by its old name on every request after) those showed the vendor's name. An account with no name of the user's own goes by the name its plugin's `usage()` gives it (`PluginUserOf`, the `user` of its last read: `loginUsageCache`, else `quotas.json`), else by its id: a Huawei Cloud CodeArts account kept by its IAM id `iam::<domain>:user:<name>` reads as the masked phone its card shows (#4416). `AccountShown`, `AccountShownOf` and `AccountLabelOf` (cards' `Alias`, `magpie accounts`, usageapi's Account filter, the quota alert) apply it, and the GUI has it as `/api/providers`' `accountUsers` (`accountShownOf` in app.js: the editor's rows, the per-account proxy lines, Routing's `userShown`, Hide accounts). The id stays the key everything is kept by; nothing stored changes. A read that fails keeps the last good `user`; nothing read yet, or a plugin whose windows are all model pools (not kept in `quotas.json`) after a restart, is its id until the next read. | [`account_names.go`](../../internal/provider/account_names.go), [`account_seats.go`](../../internal/provider/account_seats.go) |
| Last served | `served.json` records when each account, plan or key last answered, shown as `lastServedAt` (#570) on `/v1/magpie/quotas` and on the Usage page's own cards (`Quotas` → `cardsServed`, this computer's cards only, the caches left alone). The Usage page and the tray panel show the last-answered account in full, and a menu bar card that follows the account in use (`codex|*`) takes the one that answered within the last hour, else `InUseLogin`'s guess, else the one that answered last at all (a plugin's accounts, #1516) (`trayInUseCard`; okingkee on X: A spent, B answering, the menu bar stayed on A). `NoteServed` calls `OnServedMoved` when a provider's answers move to another account or key, and `SwitchLogin` after a switch, so the menu bar reads its cards again at once. | [`served.go`](../../internal/provider/served.go), [`trayusage.go`](../../internal/gui/trayusage.go) |
| Partners | Services that pay to be listed first in the add sheet, under a heading of their own ("Partners · magpie's sponsors"). The list is `site/partners.js`, served at `usemagpie.ai/api/partners`: a change reaches users with a deploy, not a release. `Partners` never waits: it returns what was fetched last and fetches again behind the call on a process's first ask, whatever the kept list's age, and hourly after (10 minutes after a failure), keeping the list in `partners.json` in the cache folder. The magpie serving the gateway fetches it when it starts and whenever it is due, asked for or not (`KeepPartnersFresh`), so an app left open on another page still learns of a partner added. The file also says when the last fetch started (`tried`) and, when it failed, why (`error`, logged once until a fetch gets the list again), so a list that stops changing tells a fetch that fails from one that never came back (`tried` after `at`, no error) and from none asked (#3362). Each entry is checked again on every read (`validPartners`): its own id, never a built-in preset's, a name, an endpoint, https only, at most 12; what only magpie's presets may set (a decision API, no key, a user endpoint) is cleared. Its logo is fetched through `FetchIcon` and kept as an uploaded icon, used as it is while its `iconUrl` stays the same; the prune after a save of `providers.json` (`pruneIcons`) leaves the logos of the partners listed now (`keptPartnerIcons`), as it leaves a plugin's. A partner is a preset to the rest of magpie (`Preset`, `FromPreset`, the editor), and one no longer listed still is to the providers added from it (`Seen`), without the sponsored mark. The window lists a partner in the languages it names (`langs`) only and shows its tagline in the page's language (`notes`, else `en`). `MAGPIE_PARTNERS` points it elsewhere, `off` lists none; tests list none unless they name a list. How often each listed partner was shown, opened (its row, its key page) and added is counted per UTC day (`CountPartner`, capped at 20 of each and 5 adds, kept in `partner-counts.json` in the cache folder) and sent with the next day's stats event as `magpie partner` events (`internal/stats`); nothing is counted with the stats or their usage part off. A listed partner the add sheet (or the TUI's, or `magpie providers presets`) hasn't shown yet is new (`NoticePartners` keeps those shown, as `noticed` in `partners.json`, whatever the stats); the window's add button carries a small dot for it, with its name in the title, until the sheet shows it. | [`partners.go`](../../internal/provider/partners.go), [`partner_events.go`](../../internal/provider/partner_events.go), [`site/partners.js`](../../site/partners.js) |
| Local servers | A preset of `KindLocal` (Ollama, LM Studio, oMLX, MLX-Serve) is at its server's default port on this machine. Another address — a port, or another computer — is given in the window's editor, in its Server address field, shown first above the key and never folded (a folded one read as an LM Studio whose base URL can't be changed, mengxiangziyou on X), or in the TUI (asked on adding, `w` after); on the command line with `address=` (`atAddress` in `providers_cli.go`: every URL moves, from the preset's when the provider was saved with none, and `address=` alone puts a local server back at its preset's), or the URLs themselves (`url=`, `anthropic=`, `responses=`). `AtAddress` replaces only each URL's scheme, host and port, each API keeping its path; `AddressOf` is the address an editor starts from. The window sends the URLs moved only when the address was changed, so a Save doesn't move URLs set apart (another app's import). A provider of the user's own (no preset) has `w` in the TUI too: each base URL it has is asked in turn, typed in as it is, Enter alone keeping one (`customURLsAsk`). | [`local_address.go`](../../internal/provider/local_address.go), [`providers_cli.go`](../../internal/cli/providers_cli.go) |
@@ -0,0 +1,106 @@
package cli
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/provider"
)
// StringKe (#4532): the name the user gave an account picks it wherever
// its email does — switch, forget, alias, the pool's --accounts, a cap —
// and is refused when it names two accounts or is another account's
// email, rather than picking one of them by guess.
func TestAccountsAliasPicksTheAccount(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
t.Setenv("CLAUDE_CONFIG_DIR", filepath.Join(home, ".claude"))
t.Setenv("COPILOT_HOME", filepath.Join(home, ".copilot"))
logins := filepath.Join(filepath.Dir(provider.Path()), "logins.json")
if err := os.MkdirAll(filepath.Dir(logins), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(logins, []byte(`[
{"agent": "copilot", "user": "mona", "seen": "2026-10-05T10:00:00Z", "on": true, "auth": {"oauth_token": "gho_m"}},
{"agent": "copilot", "user": "hubot", "seen": "2026-10-06T10:00:00Z", "on": true, "auth": {"oauth_token": "gho_h"}},
{"agent": "copilot", "user": "octo", "seen": "2026-10-06T10:00:00Z", "on": true, "auth": {"oauth_token": "gho_o"}}
]`), 0o600); err != nil {
t.Fatal(err)
}
provider.ForgetAccounts()
t.Cleanup(provider.ForgetAccounts)
t.Cleanup(agent.SyncCatalogSettled) // the pool's save syncs the agents' files behind it
run := func(args ...string) (string, error) {
t.Helper()
return said(t, func() error { return accountsCmd(append([]string{"accounts"}, args...)) })
}
first := func() string {
t.Helper()
for _, l := range provider.Logins("copilot") {
if l.Active {
return l.User
}
}
return ""
}
for _, a := range [][]string{{"hubot", "Work"}, {"octo", "Spare"}, {"mona", "Spare2"}} {
if _, err := run("alias", "copilot", a[0], a[1]); err != nil {
t.Fatal(err)
}
}
if _, err := run("switch", "copilot", "work"); err != nil || first() != "hubot" {
t.Fatalf("switch by its name: %v, first %s", err, first())
}
if out, err := run("alias", "copilot", "Work"); err != nil || !strings.Contains(out, "Work") {
t.Fatalf("alias by its name: %v %q", err, out)
}
// a name two accounts have
if _, err := run("alias", "copilot", "Spare2", "Spare"); err != nil {
t.Fatal(err)
}
if _, err := run("switch", "copilot", "spare"); err == nil || !strings.Contains(err.Error(), "2 accounts") || first() != "hubot" {
t.Fatalf("a name of two accounts was taken: %v, first %s", err, first())
}
// a name that is another account's own
if _, err := run("alias", "copilot", "octo", "mona"); err != nil {
t.Fatal(err)
}
if _, err := run("switch", "copilot", "mona"); err == nil || !strings.Contains(err.Error(), "the email of mona") || first() != "hubot" {
t.Fatalf("a name that is another account's was taken: %v, first %s", err, first())
}
if _, err := run("alias", "copilot", "octo", "Third"); err != nil {
t.Fatal(err)
}
if _, err := run("switch", "copilot", "THIRD"); err != nil || first() != "octo" {
t.Fatalf("switch by its new name: %v, first %s", err, first())
}
// the pool's --accounts takes the name too
if _, err := said(t, func() error { return poolCmd([]string{"copilot", "--accounts", "third,Work"}) }); err != nil {
t.Fatalf("pool --accounts by names: %v", err)
}
var on []string
for _, l := range provider.Logins("copilot") {
if l.On {
on = append(on, l.User)
}
}
if strings.Join(on, ",") != "octo,hubot" {
t.Fatalf("pool by names: on %v", on)
}
// and a cap, as every account setting by a ref does (accountRef)
if _, err := said(t, func() error { return accountCapCmd([]string{"copilot", "work", "50"}) }); err != nil {
t.Fatalf("account-cap by its name: %v", err)
}
if got := provider.AccountCapsOf("copilot", "hubot").All; got != 50 {
t.Fatalf("account-cap by its name: hubot's cap is %d", got)
}
if _, err := said(t, func() error { return poolCmd([]string{"copilot", "--accounts", "spare"}) }); err == nil {
t.Fatal("pool --accounts took a name of two accounts")
}
}
+10 -2
View File
@@ -859,8 +859,9 @@ func checkinWhy(msg string) string {
}
// accountNamed is the saved account of agent that user names: its name as
// magpie lists it ("a@b.com · Team"), or the email alone when only one of
// the agent's accounts has it.
// magpie lists it ("a@b.com · Team"), the email alone when only one of the
// agent's accounts has it, or the name the user gave it (alias), when that
// is one account's and no other's email (provider.AccountByName).
func accountNamed(agent, user string) (string, error) {
user = strings.TrimSpace(user)
if agent == "copilot" {
@@ -872,6 +873,13 @@ func accountNamed(agent, user string) (string, error) {
}
}
ls := provider.Logins(agent)
users := make([]string, 0, len(ls))
for _, l := range ls {
users = append(users, l.User)
}
if u, err := provider.AccountByName(agent, users, user); err != nil || u != "" {
return u, err
}
var names, same []string
for _, l := range ls {
if strings.EqualFold(l.User, user) {
+1 -1
View File
@@ -96,7 +96,7 @@ const usage = `magpie — one place to pick every agent's model
magpie accounts add copilot [--host <name>.ghe.com] one more Copilot account, on github.com or an enterprise's GHE.com
magpie accounts discovery [on|off] read agents' sign-ins (default on; MAGPIE_NO_ACCOUNTS=1 disables too)
magpie accounts import <codex|claude|antigravity|factory> <file>... [--yes] bring in accounts from other tools' files (Codex's auth.json, Cockpit Tools, CLIProxyAPI, Sub2API); the tool a ChatGPT or Claude file came from is signed out of it
magpie accounts switch <agent> <email> sign the agent in to another of them
magpie accounts switch <agent> <email|name> sign the agent in to another of them, by its email or the name you gave it
magpie accounts switch <claude|codex> next to the next account in order with room, or the one with the most left
magpie accounts refresh renew the saved ChatGPT and Claude sign-ins now (the gateway does it every 8 days)
magpie accounts checkin WorkBuddy's daily check-in (签到) for each WorkBuddy account, now (Settings can do it daily)
+10 -1
View File
@@ -101,8 +101,17 @@ func poolCmd(rest []string) error {
ls := provider.Logins(agentID)
if accountsSet {
// every one named is known before anything changes
var order []string
var order, users []string
for _, l := range ls {
users = append(users, l.User)
}
for _, u := range accounts {
// an account by its name or the name the user gave it (#4532)
if n, err := provider.AccountByName(p.ID, users, u); err != nil {
return err
} else if n != "" {
u = n
}
i := slices.IndexFunc(ls, func(l provider.Login) bool { return strings.EqualFold(l.User, u) })
if i < 0 {
return fmt.Errorf("%s has no account %q", p.Name, u)
+4 -2
View File
@@ -1601,10 +1601,12 @@ func accountCapCmd(rest []string) error {
}
refs := p.AccountRefs()
if len(rest) > 1 {
refs = slices.DeleteFunc(refs, func(r string) bool { return !strings.EqualFold(r, strings.TrimSpace(rest[1])) })
if len(refs) == 0 {
// by its name or the name the user gave it, as the caps are set
r, ok := p.AccountRefOf(rest[1])
if !ok {
return fmt.Errorf("%s has no account %q", p.Name, rest[1])
}
refs = []string{r}
}
if len(refs) == 0 {
fmt.Println(muted.Render(p.Name + " has no account"))
+9 -1
View File
@@ -136,7 +136,10 @@ func (a AccountRef) Shown(p Provider) string {
}
// accountRef is the account or key of p that ref names: a signed-in
// account by its name, a key by its KeyID or its name, in any case.
// account by its name, else by the name the user gave it when that is one
// account's and no other's email (AccountByName; #4532), a key by its
// KeyID or its name, in any case. An account's own name goes first: the
// GUI passes it, and a name given to another account never takes it.
func (p Provider) accountRef(ref string) (string, bool) {
ref = strings.TrimSpace(ref)
for _, r := range p.AccountRefs() {
@@ -144,6 +147,11 @@ func (p Provider) accountRef(ref string) (string, bool) {
return r, true
}
}
if p.Account != nil {
if u, err := AccountByName(p.ID, p.AccountRefs(), ref); err == nil && u != "" {
return u, true
}
}
if p.Account == nil {
for _, k := range p.KeyList() {
if k.Name != "" && strings.EqualFold(k.Name, ref) {
+32
View File
@@ -64,6 +64,38 @@ func (p Provider) AccountName(user string) string {
return names[accountKey(user)]
}
// AccountByName is the one of users, accounts of the subscription id, that
// the user named ref (AccountNameOf, compared without case), "" when none
// is: an alias picks an account wherever its email does (#4532). It is an
// error when the name is two accounts', or another account's email or
// name as magpie lists it, which would then pick one of them by guess.
func AccountByName(id string, users []string, ref string) (string, error) {
ref = cleanAccountName(ref)
if ref == "" {
return "", nil
}
var named []string
for _, u := range users {
if strings.EqualFold(AccountNameOf(id, u), ref) {
named = append(named, u)
}
}
switch len(named) {
case 0:
return "", nil
case 1:
default:
return "", fmt.Errorf("%q is the name of %d accounts, %q: name one by its email, or give them names apart (magpie accounts alias)", ref, len(named), named)
}
for _, u := range users {
email, _, _ := strings.Cut(u, " · ")
if !strings.EqualFold(u, named[0]) && (strings.EqualFold(u, ref) || strings.EqualFold(strings.TrimSpace(email), ref)) {
return "", fmt.Errorf("%q is the name of %s and the email of %s: name it by its email, or give %s another name (magpie accounts alias)", ref, named[0], u, named[0])
}
}
return named[0], nil
}
// AccountNameOf is the name the user gave the account user of the
// subscription id, "" when none.
func AccountNameOf(id, user string) string {