provider, agent, gui: subscription accounts can be turned off, and then no agent's sign-in is read (#1535, MaxHaiCom)
What changed: Settings → Privacy → Subscription accounts (On/Off), `magpie accounts discovery [on|off]` and MAGPIE_NO_ACCOUNTS=1 turn off account discovery. It stays on by default. While it is off, magpie reads none of the agents' sign-ins: ~/.claude/.credentials.json, .claude.json's account, ~/.codex/auth.json, Copilot's, Cursor's, Devin's, Kiro's, Gemini's, ZCode's, Command Code's and OpenCode's files. It runs no `security` / `secret-tool` for the Keychain or Secret Service, and asks no agent CLI who is signed in. It serves no subscription. API-key providers, middleware plugins and Pi extensions work as before. Why: the reporter runs magpie on machines where reading other tools' credentials isn't wanted. The owner delegated the call. How: settings.NoAccountDiscovery (kept per computer by KeepOwn) and settings.AccountDiscoveryOff(). The variable only ever turns discovery off. The gates sit at every reader (readAccountFile, discoveryOff) and at every route that reads or writes a sign-in, so a route that skips Accounts still reads nothing: - Accounts, All, Logins, usage, renewal, warm-up, session identities, check-ins; - switching, forgetting, SetLoginOn, StartSignIn, the imports; - moves onto plugins. The ones that write refuse with an error that names how to turn it back on. On the agent side, Agent.Source and OpenCode's auth.json are gated, and Codex wiring goes by magpie's stash instead of auth.json, so a toggle never rewires Codex. logins.json and plugin-auth.json are left untouched and serve again when discovery is turned back on. A change applies at once (ForgetAccounts). Docs: providers-accounts.md, README (en, zh-CN), and the site's CLI table (en, zh, ja). Run: - TestAccountDiscoveryOffReadsNoSignIn (provider) and TestAccountDiscoveryOffAgentsReadNoSignIn (agent). Every credential path is a FIFO that records each open, and security, secret-tool, claude, codex, cursor-agent, devin, kiro-cli, copilot and grok are fakes on PATH. Both fail with the gate removed: they show the opens and `security find-generic-password -s Claude Code-credentials`, among others. Both pass with the gate in place. - TestAccountDiscoverySetting and TestAccountsDiscoveryCmd. - account-discovery.test.cjs: chromium and webkit, 900 and 360 wide, en/zh/zh-TW/ja/de, 32/32. The neighbouring privacy, redact, settings-sections and i18n-keys GUI tests: 49/49. - The full `go test -tags nogui ./...`, gofmt -l, and go vet for darwin, linux and windows on the touched packages. Not tried: a real machine under fs_usage, and Linux and Windows at runtime. The FIFO tests are !windows.
This commit is contained in:
@@ -65,6 +65,8 @@ magpie quota # what's left on every plan
|
||||
magpie tui # the whole thing, in a terminal
|
||||
```
|
||||
|
||||
magpie finds the subscriptions your agents are signed in to by reading their sign-ins (Claude Code's and Codex's files, the Keychain). To keep it from reading them, turn off Settings → Privacy → *Subscription accounts*, or run `magpie accounts discovery off` (`on` turns it back on). `MAGPIE_NO_ACCOUNTS=1` turns it off for one run without changing the saved setting. API-key providers work either way.
|
||||
|
||||
## Supported agents
|
||||
|
||||
<table>
|
||||
|
||||
@@ -65,6 +65,8 @@ magpie quota # 每个套餐还剩多少
|
||||
magpie tui # 全部功能,在终端里
|
||||
```
|
||||
|
||||
magpie 通过读取智能体的登录信息(Claude Code 和 Codex 的文件、钥匙串)找到它们登录的订阅。不想让它读取,可以在 设置 → 隐私 里关闭「订阅账号」,或运行 `magpie accounts discovery off`(`on` 重新开启)。`MAGPIE_NO_ACCOUNTS=1` 只对这一次运行关闭,不改动保存的设置。API Key 服务商不受影响。
|
||||
|
||||
## 支持的 Agent
|
||||
|
||||
<table>
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// accountsDiscoveryCmd is `magpie accounts discovery [on|off]` (#1535):
|
||||
// whether magpie reads the agents' own sign-ins (their credential files,
|
||||
// the Keychain) and serves them as subscriptions; Settings → Privacy's
|
||||
// Subscription accounts. With no argument it says which is in effect.
|
||||
func accountsDiscoveryCmd(args []string) error {
|
||||
if len(args) > 1 || len(args) == 1 && args[0] != "on" && args[0] != "off" {
|
||||
return fmt.Errorf("usage: magpie accounts discovery [on|off]")
|
||||
}
|
||||
if len(args) == 1 {
|
||||
s := settings.Load()
|
||||
s.NoAccountDiscovery = args[0] == "off"
|
||||
if err := settings.Save(s); err != nil {
|
||||
return err
|
||||
}
|
||||
provider.ForgetAccounts()
|
||||
}
|
||||
switch {
|
||||
case !settings.AccountDiscoveryOff():
|
||||
fmt.Println("account discovery is on: magpie reads your agents' sign-ins and serves them as subscriptions")
|
||||
case settings.Load().NoAccountDiscovery:
|
||||
fmt.Println("account discovery is off: magpie reads none of your agents' sign-ins and serves no subscription; API-key providers work as before")
|
||||
default:
|
||||
fmt.Println("account discovery is off for this run: MAGPIE_NO_ACCOUNTS is set (saved: on)")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// discoveryOut runs `magpie accounts discovery` with args and returns what
|
||||
// it printed.
|
||||
func discoveryOut(t *testing.T, args ...string) string {
|
||||
t.Helper()
|
||||
r, w, err := os.Pipe()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old := os.Stdout
|
||||
os.Stdout = w
|
||||
done := make(chan string)
|
||||
go func() { b, _ := io.ReadAll(r); done <- string(b) }()
|
||||
err = run(append([]string{"accounts", "discovery"}, args...))
|
||||
w.Close()
|
||||
os.Stdout = old
|
||||
out := <-done
|
||||
r.Close()
|
||||
if err != nil {
|
||||
t.Fatalf("accounts discovery %v: %v", args, err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// `magpie accounts discovery off` saves the opt-out (#1535), `on` takes it
|
||||
// back, and with no argument it says which is in effect; it leaves every
|
||||
// other setting as it was.
|
||||
func TestAccountsDiscoveryCmd(t *testing.T) {
|
||||
t.Setenv("MAGPIE_NO_ACCOUNTS", "")
|
||||
if err := settings.Save(settings.Settings{Currency: "cny"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if out := discoveryOut(t); !strings.Contains(out, "is on") {
|
||||
t.Errorf("default: %q", out)
|
||||
}
|
||||
if out := discoveryOut(t, "off"); !strings.Contains(out, "is off:") {
|
||||
t.Errorf("off: %q", out)
|
||||
}
|
||||
if s := settings.Load(); !s.NoAccountDiscovery || s.Currency != "cny" {
|
||||
t.Errorf("saved %+v", s)
|
||||
}
|
||||
discoveryOut(t, "on")
|
||||
if settings.Load().NoAccountDiscovery {
|
||||
t.Error("on left it off")
|
||||
}
|
||||
t.Setenv("MAGPIE_NO_ACCOUNTS", "1")
|
||||
if out := discoveryOut(t); !strings.Contains(out, "MAGPIE_NO_ACCOUNTS") {
|
||||
t.Errorf("under the variable: %q", out)
|
||||
}
|
||||
if err := run([]string{"accounts", "discovery", "maybe"}); err == nil {
|
||||
t.Error("a word other than on or off taken")
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,9 @@ import (
|
||||
// — the subscriptions magpie remembers, how much of each one's allowance is
|
||||
// used, and switching the agent between them.
|
||||
func accountsCmd(args []string) error {
|
||||
if len(args) > 1 && args[1] == "discovery" {
|
||||
return accountsDiscoveryCmd(args[2:])
|
||||
}
|
||||
const usage = "usage: magpie accounts [claude|codex|grok|copilot|gemini|antigravity|zed|factory|mimo|<plugin>] [--json] | magpie accounts add <claude|codex|gemini|antigravity|zed|factory|mimo|<plugin>> | magpie accounts add copilot [--host <name>.ghe.com] | magpie accounts import <codex|claude|antigravity|factory> <file>... [--yes] | magpie accounts refresh [--json] | magpie accounts checkin [--json] | magpie accounts switch|forget <claude|codex|gemini|antigravity|zed|factory|mimo|<plugin>> <email> | magpie accounts switch|forget copilot <login>[@<name>.ghe.com] [--host <name>.ghe.com] | magpie accounts project <gemini|antigravity> <email> <gcp-project-id> | magpie accounts alias <agent|<plugin>> <email> [<name>|--clear]"
|
||||
agentID := func(s string) (string, error) {
|
||||
switch strings.ToLower(s) {
|
||||
|
||||
@@ -24,7 +24,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
|
||||
| Keys | Several keys per provider. Requests go to the first key that is on; the gateway moves on when it is out or rate limited. `Key` stays the first, so other code reads it as before. A key can be made for one protocol (`KeyProtocol`). | [`keys.go`](../../internal/provider/keys.go) |
|
||||
| Google Vertex AI | `google-vertex` (`VertexPreset`, `IsVertex`) is a provider of the user's own with no key. `Provider.Vertex` holds `project`, `location` (`global`, `us`, `eu` or a region; `global` when empty), `credentials` (a file; empty for Application Default Credentials) and `impersonate` (a service account's email). Save refuses a key given it, then normalizes them (`Normal`) and checks each (`check`); `normalize` clears the four URLs and any key put in `providers.json` by hand, which stands in for neither a token nor a project and leaves the provider as found savable, so the provider's one address is `vertexBase`, `https://<host>/v1/projects/<project>/locations/<location>`, its host following the location (`vertexHost`). It speaks Gemini alone (`Speaks`, `Base`). It is `Ready` once that address can be made, never from a key or an account; until then the app, `magpie providers` and the TUI say it needs a project, and `magpie provider <id>` says how to give it one. `hasEndpoint` counts it as a provider of the user's own, not a subscription's picks. An import link naming it is refused (`ParseImport`): its project and credentials are the user's own, which no link hands over. `Sign` refuses any other address and sets the bearer token before the user's `Headers`; `AuthHeaders` gives it no key header. Its models are its location's (`vertexModels`, in `planModels`): the preset has `NoList`, because Vertex AI has no list that says what a location serves. The lists are in the [reference](../reference.md#google-vertex-ai). | [`vertex.go`](../../internal/provider/vertex.go), [`provider.go`](../../internal/provider/provider.go), [`account.go`](../../internal/provider/account.go), [`rename.go`](../../internal/provider/rename.go), [`models.go`](../../internal/provider/models.go), [`importurl.go`](../../internal/provider/importurl.go) |
|
||||
| Vertex AI tokens | `vertexCredentialsFile` finds the credentials as Google's libraries find Application Default Credentials: the provider's `credentials`, else the file `GOOGLE_APPLICATION_CREDENTIALS` names, else `application_default_credentials.json` in gcloud's folder (`CLOUDSDK_CONFIG`, else `~/.config/gcloud`, `%APPDATA%\gcloud` on Windows); a `~/` that starts any of them is the home. `mint` reads three kinds: `authorized_user` (a refresh-token grant), `service_account` (an RS256 JWT, RFC 7523: `signed`) and gcloud's `impersonated_service_account`, whose `source_credentials` are minted and traded at IAM Credentials, along its `delegates`, for the account its `service_account_impersonation_url` names (`impersonationURL`: the token never goes to that URL's host). With `impersonate` set, the token those give is traded at IAM Credentials' `generateAccessToken` for a `cloud-platform` token of that account's, as gcloud's `--impersonate-service-account` does (`impersonateFor`); the credentials' account needs `roles/iam.serviceAccountTokenCreator` on it, which the 403 names. `vertexTokens` keeps one token per file and impersonated account, in memory only; requests made together mint it once, and those that waited through a mint that failed are given its error rather than each minting in turn (`mints`, `failed`). A mint cut short because its own request was given up on fails none of them: the next one mints. It is minted again within `vertexRefreshLead` (5 minutes) of expiry, or when the file's size or modification time has changed (gcloud signed in again). One mint, every exchange included, gets `vertexMintWait` (30 seconds). The file is only read. | [`vertex.go`](../../internal/provider/vertex.go), [`signin.go`](../../internal/provider/signin.go) |
|
||||
| Subscription accounts | `Accounts` reads the credentials each agent keeps on disk or in the macOS Keychain; nothing is stored twice. A built-in that has moved to its plugin is dropped (`Moved`), and plugin accounts are placed in its slot (`placeMoved`). `Sign` adds the account's own auth, then the user's `Headers`. | [`account.go`](../../internal/provider/account.go) |
|
||||
| Subscription accounts | `Accounts` reads the credentials each agent keeps on disk or in the macOS Keychain; nothing is stored twice. With account discovery off (#1535, below) none of them is read. A built-in that has moved to its plugin is dropped (`Moved`), and plugin accounts are placed in its slot (`placeMoved`). `Sign` adds the account's own auth, then the user's `Headers`. | [`account.go`](../../internal/provider/account.go) |
|
||||
| Token refresh | Each account refreshes through its vendor. For example, `codexToken` refreshes within 5 minutes of expiry and writes the rotated tokens back into `~/.codex/auth.json` for Codex CLI. A 400 or 401 from the vendor's refresh endpoint means it was refused (`refreshFailed`). | [`account.go`](../../internal/provider/account.go) |
|
||||
| Saved accounts | `logins.json` remembers every Codex and Claude Code account seen signed in. A switch moves the credentials into the agent's own store and saves the ones it replaces. A saved account that is on (`SetLoginOn`) stands behind the agent's own. Its tokens stay in `logins.json`. | [`logins.go`](../../internal/provider/logins.go), [`logins_on.go`](../../internal/provider/logins_on.go) |
|
||||
| Sign-in in magpie | `StartSignIn` runs the vendor's own browser OAuth with its client and takes the tokens at a callback on this machine. A browser that can't reach that callback (magpie on a server or in Docker) ends on a page that won't load; its address, pasted (`SubmitSignInCallback`), goes through the same callback handler (`pastedCallback`). A plugin's browser sign-in (`auto`) whose page names a port on this machine to come back to takes its pasted address too: magpie opens it there on 127.0.0.1, for the plugin's own listener (`pluginCallback`, `loopbackPorts`); Command Code's page posts its key from script, so it offers the API key way instead. A Claude account is signed in by Claude Code itself. Signing in brings back an account removed from magpie (`ShowAccount`). A sign-in started in magpie (`StartSignIn`, `StartPluginSignIn`) reads as done (`SignInStatus`, `WaitSignIn`) only after `finish` has run `ShowAccount` for its account, so the window, which opens the account as soon as it sees done, finds it listed. If providers.json can't be written then, the account stays hidden and the sign-in still ends done. Signing in to a plugin's provider from the command line (`pluginLogin`, with a key or the browser) brings it back too. It also takes off the mark a sign-in its vendor turned away left on the account (`Lapsed`) and shows again the agent's own account removed in magpie (`clearPluginLapse`). The window's plugin sign-in does the same with the browser (`pluginDone`, then `finish`) or with a key (`PluginAPIKey`); a key and the command line share these steps in `PluginSignedIn`. | [`signin.go`](../../internal/provider/signin.go), [`claude_signin.go`](../../internal/provider/claude_signin.go), [`pluginsignin.go`](../../internal/provider/pluginsignin.go), [`pluginsignin_paste.go`](../../internal/provider/pluginsignin_paste.go), [`plugins_cli.go`](../../plugins_cli.go) |
|
||||
@@ -82,6 +82,8 @@ successful model discovery for its decision result, and reports none when
|
||||
no decision model was discovered (`Test` in
|
||||
[`test.go`](../../internal/provider/test.go)).
|
||||
|
||||
Account discovery can be turned off (#1535): Settings → Privacy → *Subscription accounts*, `magpie accounts discovery off`, or `MAGPIE_NO_ACCOUNTS=1` for one process. The first two save `noAccountDiscovery: true`, which this computer keeps through a sync or a restored backup (`KeepOwn`); the variable only ever turns discovery off, never on what the user saved off (`settings.AccountDiscoveryOff`). It is on by default. While it is off, magpie reads no agent's sign-in: no credential file (`~/.claude/.credentials.json`, `~/.claude.json`'s account, `~/.codex/auth.json`, Copilot's, Cursor's, Devin's, Kiro's, Gemini's, ZCode's, Command Code's, OpenCode's `auth.json`), no Keychain or Secret Service item (`security`, `secret-tool`), and no agent CLI asked who is signed in. The gates sit at each reader (`readAccountFile`, `discoveryOff` in [`discovery.go`](../../internal/provider/discovery.go)) and at each route that would read or write a sign-in: `Accounts` and `All`, `Logins`, usage, renewal, warm-up, session identities, check-ins, switching, forgetting, `SetLoginOn`, `StartSignIn`, the imports, and moves onto plugins (`MoveCandidates`, `HandOver`, `KeepRetiringMoved`). Those that write refuse with `errAccountDiscoveryOff`, which says how to turn it back on. The agents' side is gated too: the Agents page's *runs on* line (`Agent.Source`), OpenCode's own providers (`readOwnAuth`), and wiring Codex, which goes by magpie's stash instead of `auth.json` (`chatGPT` in [`codex.go`](../../internal/agent/codex.go)). Subscriptions aren't served; API-key providers, middleware plugins and Pi extensions run as before. What magpie kept of its own (`logins.json`, `plugin-auth.json`, `migrations.json`) is left as it is, unread for accounts, and serves again once discovery is on. A change takes effect at once (`ForgetAccounts`); no restart is needed.
|
||||
|
||||
## Runtime path
|
||||
|
||||
1. **Add.** The Providers page adds a key provider through `Add` or `Save`, or an account through `StartSignIn`. An agent signed in on its own is found by `Accounts` with no step from the user.
|
||||
@@ -136,6 +138,8 @@ go test -tags nogui ./internal/provider -run 'TestGeminiBase|TestCustomGeminiPro
|
||||
node --test internal/gui/tests/partners.test.cjs site/worker.test.mjs
|
||||
go test -tags nogui ./internal/provider
|
||||
go test -tags nogui -run 'Vertex' .
|
||||
go test -tags nogui ./internal/provider ./internal/agent -run 'TestAccountDiscovery'
|
||||
node --test internal/gui/tests/account-discovery.test.cjs
|
||||
```
|
||||
|
||||
The package's tests use a home of their own (`testenv`). Never point them at
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/sessions"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
@@ -285,7 +286,7 @@ func ownOptionsFrom(native func(p string) []catalog.Model, authFile string, cur
|
||||
if p, _, ok := strings.Cut(cur, "/"); ok && p != magpieID {
|
||||
set[p] = true
|
||||
}
|
||||
if b, err := os.ReadFile(authFile); err == nil {
|
||||
if b, err := readOwnAuth(authFile); err == nil {
|
||||
var m map[string]json.RawMessage
|
||||
if json.Unmarshal(b, &m) == nil {
|
||||
for k := range m {
|
||||
@@ -1367,3 +1368,12 @@ func crushAt(at place, path, data string) *Agent {
|
||||
var (
|
||||
noticeGoose = newNotice("Goose loads its providers at start-up — quit and reopen Goose (and open goose sessions) to use magpie's models.")
|
||||
)
|
||||
|
||||
// readOwnAuth is os.ReadFile for an agent's own sign-ins (OpenCode's
|
||||
// auth.json and its kin), left unread with account discovery off (#1535).
|
||||
func readOwnAuth(path string) ([]byte, error) {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return nil, os.ErrNotExist
|
||||
}
|
||||
return os.ReadFile(path)
|
||||
}
|
||||
|
||||
+19
-5
@@ -23,6 +23,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/sessions"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// Codex talks the OpenAI Responses API. Signed in to ChatGPT, it is
|
||||
@@ -164,6 +165,16 @@ func codexIn(at place) *Agent {
|
||||
// (#940: it read as not connected), the change told as drift. One
|
||||
// picked on the Agents page still takes magpie out (set).
|
||||
beside := func() bool { return viaBase() && stashLoad()[at.key("codex.beside")] == "1" }
|
||||
// chatGPT is whether Codex is signed in to ChatGPT. With account
|
||||
// discovery off (#1535) auth.json stays unread, and Codex is taken to be
|
||||
// as magpie last wired it, beside a ChatGPT sign-in or not, so turning
|
||||
// discovery off never rewires Codex by itself.
|
||||
chatGPT := func() bool {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return joined() || beside()
|
||||
}
|
||||
return codexChatGPT(dir)
|
||||
}
|
||||
// magpie is in Codex's config: on one of magpie's models, or joined;
|
||||
// or, routed, on the model of the group magpie set it to as Codex
|
||||
// spells it (gpt-6.1-sol for group/auto-gpt-6-1-sol, #750), which the
|
||||
@@ -689,7 +700,7 @@ func codexIn(at place) *Agent {
|
||||
// that. Wired so for that alone, it is marked (codex.out), for
|
||||
// Sync to put it back beside the sign-in once the account has
|
||||
// room again.
|
||||
chatgpt := !api() && codexChatGPT(dir)
|
||||
chatgpt := !api() && chatGPT()
|
||||
if chatgpt && !out() {
|
||||
forget(at.key("codex.out"))
|
||||
if err := dropProvider(); err != nil {
|
||||
@@ -752,7 +763,7 @@ func codexIn(at place) *Agent {
|
||||
}
|
||||
// joined, a model of Codex's own is picked beside magpie's, as in
|
||||
// Codex's /model: it stays connected
|
||||
if joined() && !api() && codexChatGPT(dir) {
|
||||
if joined() && !api() && chatGPT() {
|
||||
if err := edit.SetTOMLTop(path, edit.KV{Path: "model", Value: v}); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -806,7 +817,7 @@ func codexIn(at place) *Agent {
|
||||
// was on, the one last picked in its /model (the owner: 让 Codex 记住
|
||||
// 上次的选择), and magpie's models join its list
|
||||
Join: func() (bool, error) {
|
||||
if api() || !codexChatGPT(dir) || out() || isMagpie(get("model")) {
|
||||
if api() || !chatGPT() || out() || isMagpie(get("model")) {
|
||||
return false, nil
|
||||
}
|
||||
if p := get("model_provider"); p != "" && p != "openai" && !isCCSwitchMirror(p) {
|
||||
@@ -869,7 +880,7 @@ func codexIn(at place) *Agent {
|
||||
// on a magpie model by the base URL alone with no ChatGPT
|
||||
// sign-in, as an older magpie left a Codex signed in with an
|
||||
// API key: its picker never had magpie's models (#322)
|
||||
if m := get("model"); isMagpie(m) && viaBase() && get("model_provider") == "" && !codexChatGPT(dir) {
|
||||
if m := get("model"); isMagpie(m) && viaBase() && get("model_provider") == "" && !chatGPT() {
|
||||
return set(m)
|
||||
}
|
||||
// the ChatGPT account ran out (of its allowance and its
|
||||
@@ -879,7 +890,7 @@ func codexIn(at place) *Agent {
|
||||
// becomes Codex's provider as set does for an account already
|
||||
// out; and once the account has room again (or Codex is on
|
||||
// one with room), Codex's own models join magpie's again
|
||||
if m := get("model"); isMagpie(m) && !api() && codexChatGPT(dir) {
|
||||
if m := get("model"); isMagpie(m) && !api() && chatGPT() {
|
||||
switch {
|
||||
case viaBase() && !asProvider() && out():
|
||||
return set(m)
|
||||
@@ -1453,6 +1464,9 @@ func CodexOwnOnly() bool {
|
||||
// its built-in provider then runs and asks for the model list at
|
||||
// openai_base_url. Signed in with an API key alone, it asks for none.
|
||||
func codexChatGPT(dir string) bool {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return false
|
||||
}
|
||||
var a struct {
|
||||
Tokens struct {
|
||||
Access string `json:"access_token"`
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// What the Agents page says beside an agent's 「接入」 switch (the owner's
|
||||
@@ -25,16 +26,24 @@ import (
|
||||
// Source is what an agent not connected to magpie runs on now: "sub" (a
|
||||
// Claude subscription), "chatgpt" (a ChatGPT sign-in), "key" (an API key
|
||||
// of its own), "providers:N" (N providers of its own); "" when unknown.
|
||||
//
|
||||
// With account discovery off (#1535) no sign-in is read for it: Claude
|
||||
// Code's account in .claude.json, Codex's auth.json and OpenCode's are
|
||||
// left alone, and only what the agent's own settings say is told.
|
||||
func (a *Agent) Source() string {
|
||||
if a.WSL != "" || a.Path == "" {
|
||||
return ""
|
||||
}
|
||||
dir := filepath.Dir(a.Path)
|
||||
signIns := !settings.AccountDiscoveryOff()
|
||||
switch a.ID {
|
||||
case "claude":
|
||||
// signed in to claude.ai: ~/.claude.json (or the one in
|
||||
// CLAUDE_CONFIG_DIR) has the account
|
||||
for _, p := range []string{filepath.Join(dir, ".claude.json"), filepath.Join(filepath.Dir(dir), ".claude.json")} {
|
||||
if !signIns {
|
||||
break
|
||||
}
|
||||
if v, _ := edit.GetJSON(p, "oauthAccount.accountUuid"); v != "" {
|
||||
return "sub"
|
||||
}
|
||||
@@ -46,6 +55,9 @@ func (a *Agent) Source() string {
|
||||
return "key"
|
||||
}
|
||||
case "codex":
|
||||
if !signIns {
|
||||
break
|
||||
}
|
||||
if codexChatGPT(dir) {
|
||||
return "chatgpt"
|
||||
}
|
||||
@@ -63,7 +75,7 @@ func (a *Agent) Source() string {
|
||||
}
|
||||
home, _ := os.UserHomeDir()
|
||||
var auth map[string]json.RawMessage
|
||||
if b, err := os.ReadFile(filepath.Join(home, ".local", "share", a.ID, "auth.json")); err == nil && json.Unmarshal(b, &auth) == nil {
|
||||
if b, err := readOwnAuth(filepath.Join(home, ".local", "share", a.ID, "auth.json")); err == nil && json.Unmarshal(b, &auth) == nil {
|
||||
for k := range auth {
|
||||
n[k] = true
|
||||
}
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
//go:build !windows
|
||||
|
||||
package agent
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// fifoWatch turns each path into a FIFO and notes every open of one for
|
||||
// reading: a non-blocking open for writing succeeds only while a reader
|
||||
// waits in its open, which is handed "{}" and an end of file.
|
||||
func fifoWatch(t *testing.T, paths []string) func() []string {
|
||||
t.Helper()
|
||||
for _, p := range paths {
|
||||
os.Remove(p)
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := syscall.Mkfifo(p, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var (
|
||||
mu sync.Mutex
|
||||
opened []string
|
||||
)
|
||||
stop, done := make(chan struct{}), make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
}
|
||||
for _, p := range paths {
|
||||
fd, err := syscall.Open(p, syscall.O_WRONLY|syscall.O_NONBLOCK, 0)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
mu.Lock()
|
||||
opened = append(opened, p)
|
||||
mu.Unlock()
|
||||
_, _ = syscall.Write(fd, []byte("{}"))
|
||||
_ = syscall.Close(fd)
|
||||
}
|
||||
time.Sleep(200 * time.Microsecond)
|
||||
}
|
||||
}()
|
||||
// a FIFO left behind blocks the next reader for good
|
||||
t.Cleanup(func() {
|
||||
close(stop)
|
||||
<-done
|
||||
for _, p := range paths {
|
||||
os.Remove(p)
|
||||
}
|
||||
})
|
||||
return func() []string {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return slices.Clone(opened)
|
||||
}
|
||||
}
|
||||
|
||||
// With account discovery off (#1535, MaxHaiCom), the Agents page's "runs
|
||||
// on" line, OpenCode's own providers and wiring Codex read no agent's
|
||||
// sign-in: not Claude Code's account in .claude.json, not Codex's
|
||||
// auth.json, not OpenCode's auth.json.
|
||||
func TestAccountDiscoveryOffAgentsReadNoSignIn(t *testing.T) {
|
||||
home, _ := codexHome(t, "", "")
|
||||
if err := settings.Save(settings.Settings{NoAccountDiscovery: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
claudeDir := filepath.Join(home, ".claude")
|
||||
ocAuth := filepath.Join(home, ".local", "share", "opencode", "auth.json")
|
||||
files := []string{
|
||||
filepath.Join(home, ".codex", "auth.json"),
|
||||
filepath.Join(home, ".claude.json"),
|
||||
filepath.Join(claudeDir, ".claude.json"),
|
||||
ocAuth,
|
||||
}
|
||||
opened := fifoWatch(t, files)
|
||||
if b, err := os.ReadFile(files[0]); err != nil || string(b) != "{}" {
|
||||
t.Fatalf("the watch didn't answer a read: %q %v", b, err)
|
||||
}
|
||||
|
||||
cfgDir := filepath.Join(home, ".config", "opencode")
|
||||
os.MkdirAll(cfgDir, 0o755)
|
||||
os.WriteFile(filepath.Join(cfgDir, "opencode.json"), []byte(`{"provider":{"mine":{}}}`), 0o644)
|
||||
os.WriteFile(filepath.Join(claudeDir, "settings.json"), []byte(`{}`), 0o644)
|
||||
|
||||
if s := (&Agent{ID: "claude", Path: filepath.Join(claudeDir, "settings.json")}).Source(); s != "" {
|
||||
t.Errorf("Claude Code runs on %q", s)
|
||||
}
|
||||
if s := (&Agent{ID: "codex", Path: filepath.Join(home, ".codex", "config.toml")}).Source(); s != "" {
|
||||
t.Errorf("Codex runs on %q", s)
|
||||
}
|
||||
// its own config still counts
|
||||
if s := (&Agent{ID: "opencode", Path: filepath.Join(cfgDir, "opencode.json")}).Source(); s != "providers:1" {
|
||||
t.Errorf("OpenCode runs on %q, want its config's one provider", s)
|
||||
}
|
||||
ownOptions(ocAuth, "")
|
||||
cx := codex(home)
|
||||
if _, err := cx.Join(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := cx.Fields[0].Set("fake/m1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
if got := opened(); len(got) != 1 {
|
||||
t.Errorf("with discovery off, reads of sign-ins: %s", strings.Join(got[1:], " "))
|
||||
}
|
||||
}
|
||||
@@ -343,6 +343,9 @@ type settingsJSON struct {
|
||||
TerminalApps []terminalChoice `json:"terminalApps,omitempty"`
|
||||
TerminalDefault string `json:"terminalDefault,omitempty"`
|
||||
OTelEnv bool `json:"otelEnv,omitempty"`
|
||||
// NoAccountsEnv is MAGPIE_NO_ACCOUNTS set, which keeps account
|
||||
// discovery off for this run whatever Settings has (#1535)
|
||||
NoAccountsEnv bool `json:"noAccountsEnv,omitempty"`
|
||||
// whether the page is in gateway mode and why (gatewayMode); Web says
|
||||
// it is served by magpie web, where the mode can be set
|
||||
GatewayOn bool `json:"gatewayOn,omitempty"`
|
||||
@@ -518,6 +521,7 @@ func settingsState() settingsJSON {
|
||||
s.NotifyProblem = notifyProblem()
|
||||
}
|
||||
s.ProxyNow, s.ProxySource = netproxy.Describe()
|
||||
s.NoAccountsEnv = settings.AccountDiscoveryOff() && !s.NoAccountDiscovery
|
||||
for _, name := range []string{"MAGPIE_OTEL_ENABLED", "MAGPIE_OTEL_ENDPOINT", "MAGPIE_OTEL_HEADERS", "MAGPIE_OTEL_METRICS", "MAGPIE_OTEL_BODIES", "MAGPIE_OTEL_BODIES_WHOLE", "MAGPIE_OTEL_SESSIONS"} {
|
||||
if _, ok := os.LookupEnv(name); ok {
|
||||
s.OTelEnv = true
|
||||
@@ -1085,6 +1089,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
in.UpdateMirror = cur.UpdateMirror
|
||||
// gateway mode, set on its own (gateway-mode)
|
||||
in.GatewayMode = cur.GatewayMode
|
||||
in.NoAccountDiscovery = cur.NoAccountDiscovery // set on its own (account-discovery below, or the CLI)
|
||||
if v := strings.TrimSpace(in.Vision); v != "" && v != "off" && v != cur.Vision {
|
||||
if _, _, ok := provider.Resolve(v); !ok {
|
||||
fail(rw, fmt.Errorf("no model %s to describe images", v))
|
||||
@@ -1180,6 +1185,25 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
|
||||
}
|
||||
writeJSON(rw, settingsState())
|
||||
})
|
||||
// whether agents' sign-ins are read and served as subscriptions
|
||||
// (#1535): saved, the accounts read before are forgotten at once
|
||||
mux.HandleFunc("POST /api/settings/account-discovery", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
Off bool `json:"off"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
s := settings.Load()
|
||||
s.NoAccountDiscovery = in.Off
|
||||
if err := settings.Save(s); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
provider.ForgetAccounts()
|
||||
writeJSON(rw, settingsState())
|
||||
})
|
||||
// the version the header's Update pill is hidden for, until a newer one
|
||||
// is out: set from the pill, cleared ("") from Settings
|
||||
mux.HandleFunc("POST /api/settings/update-skip", func(rw http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -19368,6 +19368,7 @@ function renderSettings() {
|
||||
renderSearch(s, keep);
|
||||
renderReplies(s, keep);
|
||||
renderRedact(s, keep);
|
||||
renderDiscovery(s);
|
||||
renderOTel(s, keep);
|
||||
renderPort(s);
|
||||
renderLAN(s);
|
||||
@@ -20753,6 +20754,31 @@ const REDACT_KINDS = [
|
||||
["bucket", "Cloud storage buckets", "The bucket in s3://, gs://, oss://, cos:// and storage URLs; the path in it stays", false],
|
||||
];
|
||||
|
||||
// renderDiscovery: whether magpie reads the agents' own sign-ins —
|
||||
// Claude Code's and Codex's files, the Keychain, Copilot's, Cursor's and
|
||||
// the rest — and serves them as subscriptions (#1535). Set on its own:
|
||||
// saved, magpie forgets the accounts it read, and API-key providers go on.
|
||||
// MAGPIE_NO_ACCOUNTS keeps it off for that run whatever is saved.
|
||||
function renderDiscovery(s) {
|
||||
const box = $("#discoveryList");
|
||||
const r = el("div", "row pref");
|
||||
const who = el("div", "who");
|
||||
who.append(el("div", "name", t("Subscription accounts")),
|
||||
el("div", "sub", s.noAccountsEnv
|
||||
? t("Off for this run: MAGPIE_NO_ACCOUNTS is set")
|
||||
: t("Read the accounts your agents are signed in to (Claude Code, Codex, Copilot, Cursor and others: their files and the Keychain) and serve them. Off, magpie reads none of them; API-key providers work as before")));
|
||||
const val = el("div", "val");
|
||||
const on = !s.noAccountDiscovery && !s.noAccountsEnv;
|
||||
val.append(segs([["off", t("Off")], ["on", t("On")]], on ? "on" : "off", (v) => {
|
||||
if ((v === "on") === on) return;
|
||||
writingPrefs(api("settings/account-discovery", { off: v === "off" }))
|
||||
.then((ns) => { prefs = state.settings = ns; renderSettings(); refreshAfterSync(); })
|
||||
.catch((e) => { status(t(e.message), "err"); renderSettings(); });
|
||||
}));
|
||||
r.append(who, val);
|
||||
box.replaceChildren(r);
|
||||
}
|
||||
|
||||
// renderRedact: what the gateway masks before a request goes to a vendor —
|
||||
// secrets, personal data, the user's own words — and puts back in what the
|
||||
// vendor answers.
|
||||
|
||||
@@ -789,6 +789,11 @@ const I18N = {
|
||||
"Each subscription's logo before its numbers; off, the numbers alone with a thin line between subscriptions": "每个订阅的数字前显示它的图标;关闭后只显示数字,订阅之间以细线分隔",
|
||||
"Allowance display": "额度显示",
|
||||
"Allowance reads": "额度刷新",
|
||||
"Agents' sign-ins": "智能体登录",
|
||||
"Subscription accounts": "订阅账号",
|
||||
"Off for this run: MAGPIE_NO_ACCOUNTS is set": "本次运行已关闭:设置了 MAGPIE_NO_ACCOUNTS",
|
||||
"Read the accounts your agents are signed in to (Claude Code, Codex, Copilot, Cursor and others: their files and the Keychain) and serve them. Off, magpie reads none of them; API-key providers work as before": "读取你的智能体已登录的账号(Claude Code、Codex、Copilot、Cursor 等:它们的文件和钥匙串)并提供服务。关闭后 magpie 一个都不读;API Key 服务商照常可用",
|
||||
"subscription accounts are off in magpie (Settings → Privacy, or `magpie accounts discovery on`)": "magpie 里的订阅账号已关闭(设置 → 隐私,或 `magpie accounts discovery on`)",
|
||||
"When I ask": "仅手动",
|
||||
"When I ask: opening or refreshing the Usage page, a card's refresh, and magpie quota or accounts read them; routing, the menu bar and alerts go by the last reading till then. An account a vendor turns away for its quota is still read.": "仅手动:打开或刷新用量页、卡片上的刷新,以及 magpie quota 或 accounts 才会读取;在那之前,路由、菜单栏和提醒都按上次读到的额度。被厂商以额度为由拒绝的账号仍会读取。",
|
||||
"How much of each window is used, or how much is left, on the Usage page, the panel and the menu bar": "每个周期显示已用额度或剩余额度,用量页、面板和菜单栏一致",
|
||||
@@ -5003,6 +5008,11 @@ const I18N = {
|
||||
"Each subscription's logo before its numbers; off, the numbers alone with a thin line between subscriptions": "每個訂閱的數字前顯示它的圖示;關閉後只顯示數字,訂閱之間以細線分隔",
|
||||
"Allowance display": "額度顯示",
|
||||
"Allowance reads": "額度重新整理",
|
||||
"Agents' sign-ins": "智慧體登入",
|
||||
"Subscription accounts": "訂閱帳號",
|
||||
"Off for this run: MAGPIE_NO_ACCOUNTS is set": "本次執行已關閉:設定了 MAGPIE_NO_ACCOUNTS",
|
||||
"Read the accounts your agents are signed in to (Claude Code, Codex, Copilot, Cursor and others: their files and the Keychain) and serve them. Off, magpie reads none of them; API-key providers work as before": "讀取你的智慧體已登入的帳號(Claude Code、Codex、Copilot、Cursor 等:它們的檔案和鑰匙圈)並提供服務。關閉後 magpie 一個都不讀;API Key 服務商照常可用",
|
||||
"subscription accounts are off in magpie (Settings → Privacy, or `magpie accounts discovery on`)": "magpie 中的訂閱帳號已關閉(設定 → 隱私,或 `magpie accounts discovery on`)",
|
||||
"When I ask": "僅手動",
|
||||
"When I ask: opening or refreshing the Usage page, a card's refresh, and magpie quota or accounts read them; routing, the menu bar and alerts go by the last reading till then. An account a vendor turns away for its quota is still read.": "僅手動:開啟或重新整理用量頁、卡片上的重新整理,以及 magpie quota 或 accounts 才會讀取;在那之前,路由、選單列和提醒都依上次讀到的額度。被廠商以額度為由拒絕的帳號仍會讀取。",
|
||||
"How much of each window is used, or how much is left, on the Usage page, the panel and the menu bar": "每個週期顯示已用額度或剩餘額度,用量頁、面板和選單列一致",
|
||||
@@ -9186,6 +9196,11 @@ const I18N = {
|
||||
"Each subscription's logo before its numbers; off, the numbers alone with a thin line between subscriptions": "各サブスクリプションの数値の前にロゴを表示します。オフにすると数値のみになり、サブスクリプションの間は細い線で区切られます",
|
||||
"Allowance display": "利用枠の表示",
|
||||
"Allowance reads": "利用枠の読み込み",
|
||||
"Agents' sign-ins": "エージェントのサインイン",
|
||||
"Subscription accounts": "サブスクリプションアカウント",
|
||||
"Off for this run: MAGPIE_NO_ACCOUNTS is set": "この実行ではオフ:MAGPIE_NO_ACCOUNTS が設定されています",
|
||||
"Read the accounts your agents are signed in to (Claude Code, Codex, Copilot, Cursor and others: their files and the Keychain) and serve them. Off, magpie reads none of them; API-key providers work as before": "エージェントがサインインしているアカウント(Claude Code、Codex、Copilot、Cursor など:そのファイルとキーチェーン)を読み取って提供します。オフにすると magpie はどれも読みません。API キーのプロバイダはこれまでどおり使えます",
|
||||
"subscription accounts are off in magpie (Settings → Privacy, or `magpie accounts discovery on`)": "magpie のサブスクリプションアカウントはオフです(設定 → プライバシー、または `magpie accounts discovery on`)",
|
||||
"When I ask": "手動のみ",
|
||||
"When I ask: opening or refreshing the Usage page, a card's refresh, and magpie quota or accounts read them; routing, the menu bar and alerts go by the last reading till then. An account a vendor turns away for its quota is still read.": "手動のみ:使用状況ページを開くか更新したとき、カードの更新、magpie quota または accounts で読み込みます。それまでルーティング、メニューバー、通知は前回の値を使います。利用枠を理由にベンダーに断られたアカウントは引き続き読み込みます。",
|
||||
"How much of each window is used, or how much is left, on the Usage page, the panel and the menu bar": "使用量ページ、パネル、メニューバーで、各期間の使用済み量と残量のどちらを表示するか",
|
||||
@@ -13388,6 +13403,11 @@ const I18N = {
|
||||
"Each subscription's logo before its numbers; off, the numbers alone with a thin line between subscriptions": "Logo jedes Abos vor seinen Zahlen; ausgeschaltet nur die Zahlen mit einer dünnen Linie zwischen den Abos",
|
||||
"Allowance display": "Kontingentanzeige",
|
||||
"Allowance reads": "Kontingente abrufen",
|
||||
"Agents' sign-ins": "Anmeldungen der Agenten",
|
||||
"Subscription accounts": "Abo-Konten",
|
||||
"Off for this run: MAGPIE_NO_ACCOUNTS is set": "Für diesen Lauf aus: MAGPIE_NO_ACCOUNTS ist gesetzt",
|
||||
"Read the accounts your agents are signed in to (Claude Code, Codex, Copilot, Cursor and others: their files and the Keychain) and serve them. Off, magpie reads none of them; API-key providers work as before": "Die Konten lesen, bei denen deine Agenten angemeldet sind (Claude Code, Codex, Copilot, Cursor und andere: ihre Dateien und der Schlüsselbund), und sie bereitstellen. Aus liest magpie keines davon; Anbieter mit API-Schlüssel funktionieren wie bisher",
|
||||
"subscription accounts are off in magpie (Settings → Privacy, or `magpie accounts discovery on`)": "Abo-Konten sind in magpie aus (Einstellungen → Datenschutz, oder `magpie accounts discovery on`)",
|
||||
"When I ask": "Nur auf Anfrage",
|
||||
"When I ask: opening or refreshing the Usage page, a card's refresh, and magpie quota or accounts read them; routing, the menu bar and alerts go by the last reading till then. An account a vendor turns away for its quota is still read.": "Nur auf Anfrage: beim Öffnen oder Aktualisieren der Nutzungsseite, beim Aktualisieren einer Karte und mit magpie quota oder accounts; bis dahin richten sich Routing, Menüleiste und Hinweise nach dem zuletzt gelesenen Stand. Ein Konto, das ein Anbieter wegen seines Kontingents abweist, wird trotzdem gelesen.",
|
||||
"How much of each window is used, or how much is left, on the Usage page, the panel and the menu bar": "Wie viel jedes Zeitfensters verbraucht oder übrig ist, auf der Seite „Nutzung“, im Panel und in der Menüleiste",
|
||||
|
||||
@@ -471,6 +471,8 @@
|
||||
</section>
|
||||
<section class="set-page" id="setPage-privacy" role="tabpanel" aria-labelledby="setTab-privacy">
|
||||
<div class="list prefs" id="redactList"></div>
|
||||
<div class="row-head"><span class="label" data-t>Agents' sign-ins</span></div>
|
||||
<div class="list prefs" id="discoveryList"></div>
|
||||
</section>
|
||||
<section class="set-page" id="setPage-otel" role="tabpanel" aria-labelledby="setTab-otel">
|
||||
<div id="otelList"></div>
|
||||
|
||||
@@ -159,6 +159,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {
|
||||
DesktopLongest: true,
|
||||
GatewayMode: "off",
|
||||
QuotaReads: "asked",
|
||||
NoAccountDiscovery: true,
|
||||
}
|
||||
if err := settings.Save(was); err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// Settings → Privacy → Subscription accounts (#1535, MaxHaiCom): whether
|
||||
// magpie reads the agents' own sign-ins (Claude Code's and Codex's files,
|
||||
// the Keychain) at all. On by default; Off posts
|
||||
// settings/account-discovery {off:true} and is drawn chosen, a save of
|
||||
// another setting keeps it, On takes it back. With MAGPIE_NO_ACCOUNTS set
|
||||
// the row says so and shows Off. The row fits a narrow window without the
|
||||
// page scrolling sideways, and no click moves the page. Every language; no
|
||||
// backend, the API is faked here.
|
||||
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 settingsPayload(over) {
|
||||
return {
|
||||
theme: "light", lang: "en", tray: "panel", quotaLeft: false, currency: "usd",
|
||||
dock: false, dockWindow: false, proxy: "", redact: false, redactPersonal: false, redactWords: [],
|
||||
codexWarmup: "", claudeWarmup: "", codexWarmAt: "", claudeWarmAt: "", workbuddyCheckin: false, noStats: false,
|
||||
trayUsage: "", trayUsages: [], trayUsageEvery: 3, vision: "", imageGen: "",
|
||||
version: "0.1.400", dir: "~/.config/magpie", gateway: "http://127.0.0.1:3425",
|
||||
proxyNow: "none", proxySource: "none", login: false,
|
||||
visionModels: [], imageGenModels: [], workbuddyCheckins: [], lanURLs: [],
|
||||
fx: { rate: 7.2, at: new Date().toISOString(), stale: false },
|
||||
...over,
|
||||
};
|
||||
}
|
||||
|
||||
function server(lang, posts, over) {
|
||||
let cur = settingsPayload({ lang, ...over });
|
||||
return async (route) => {
|
||||
const req = route.request(), url = new URL(req.url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` });
|
||||
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" }, fx: cur.fx });
|
||||
if (url.pathname === "/api/settings/account-discovery") {
|
||||
const body = req.postDataJSON();
|
||||
posts.push(body);
|
||||
cur = { ...cur, noAccountDiscovery: body.off || undefined };
|
||||
return json(cur);
|
||||
}
|
||||
if (url.pathname === "/api/settings") {
|
||||
// the save of every other setting leaves this one as it is (api.go)
|
||||
if (req.method() === "POST") cur = { ...cur, ...req.postDataJSON(), noAccountDiscovery: cur.noAccountDiscovery };
|
||||
return json(cur);
|
||||
}
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
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 });
|
||||
};
|
||||
}
|
||||
|
||||
const view = (page) => page.locator("#view-settings").evaluate((v) => v.scrollTop);
|
||||
|
||||
async function open(browser, lang, width, posts, over) {
|
||||
const errors = [];
|
||||
const context = await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" });
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", server(lang, posts, over));
|
||||
await page.goto("http://magpie.test/?view=usage");
|
||||
await page.locator("#prefs").click();
|
||||
await page.locator("#setTab-privacy").click();
|
||||
await page.locator("#discoveryList .opt").first().waitFor();
|
||||
return { context, page, errors };
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": agents' sign-ins read, or not at all", async (t) => {
|
||||
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
|
||||
for (const [lang, head, name] of [
|
||||
["en", "Agents' sign-ins", "Subscription accounts"],
|
||||
["zh", "智能体登录", "订阅账号"],
|
||||
["zh-TW", "智慧體登入", "訂閱帳號"],
|
||||
["ja", "エージェントのサインイン", "サブスクリプションアカウント"],
|
||||
["de", "Anmeldungen der Agenten", "Abo-Konten"],
|
||||
]) {
|
||||
for (const width of [900, 360]) {
|
||||
await t.test(lang + " " + width, async () => {
|
||||
const posts = [];
|
||||
const { context, page, errors } = await open(browser, lang, width, posts);
|
||||
const box = page.locator("#discoveryList");
|
||||
const opts = box.locator(".opt");
|
||||
assert.equal((await page.locator("#setPage-privacy .row-head .label").last().textContent()).trim(), head);
|
||||
assert.equal((await box.locator(".name").textContent()).trim(), name);
|
||||
const sub = (await box.locator(".sub").textContent()).trim();
|
||||
assert(sub.includes("Claude Code") && sub.includes("Codex"), "the sub names what is read: " + sub);
|
||||
if (lang !== "en") assert(!sub.startsWith("Read the accounts"), lang + " sub not translated");
|
||||
// the same Off and On as Mask secrets above it
|
||||
assert.deepEqual(await opts.allTextContents(), await page.locator("#redactList .row").first().locator(".opt").allTextContents());
|
||||
assert.equal(await opts.nth(1).evaluate((b) => b.classList.contains("on")), true, "On by default");
|
||||
|
||||
const row = box.locator(".row");
|
||||
await row.scrollIntoViewIfNeeded();
|
||||
await page.waitForTimeout(300);
|
||||
const fit = await row.evaluate((r) => {
|
||||
const b = r.getBoundingClientRect(), segs = r.querySelector(".val").getBoundingClientRect();
|
||||
return { right: b.right, segsRight: segs.right, vw: document.documentElement.clientWidth,
|
||||
sideways: document.scrollingElement.scrollWidth > document.documentElement.clientWidth };
|
||||
});
|
||||
assert(fit.segsRight <= fit.vw + 0.5 && fit.right <= fit.vw + 0.5, "the row runs out of the window: " + JSON.stringify(fit));
|
||||
assert.equal(fit.sideways, false, "the page scrolls sideways");
|
||||
|
||||
const before = await view(page);
|
||||
await opts.nth(0).click();
|
||||
for (let i = 0; i < 50 && !posts.length; i++) await page.waitForTimeout(50);
|
||||
assert.deepEqual(posts.at(-1), { off: true });
|
||||
await page.waitForFunction(() => document.querySelectorAll("#discoveryList .opt")[0]?.classList.contains("on"));
|
||||
await page.waitForTimeout(200);
|
||||
assert.equal(await view(page), before, "Off moved the page");
|
||||
|
||||
// another setting saved keeps it
|
||||
await page.locator("#redactList .opt").nth(1).evaluate((b) => b.click());
|
||||
await page.waitForTimeout(300);
|
||||
assert.equal(await page.locator("#discoveryList .opt").nth(0).evaluate((b) => b.classList.contains("on")), true,
|
||||
"a save of another setting turned discovery back on");
|
||||
|
||||
await page.locator("#discoveryList .opt").nth(1).click();
|
||||
for (let i = 0; i < 50 && posts.length < 2; i++) await page.waitForTimeout(50);
|
||||
assert.deepEqual(posts.at(-1), { off: false });
|
||||
await page.waitForFunction(() => document.querySelectorAll("#discoveryList .opt")[1]?.classList.contains("on"));
|
||||
assert.deepEqual(errors, []);
|
||||
if (process.env.ARTIFACT_DIR) {
|
||||
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
|
||||
await page.waitForTimeout(500); // the pages drawn again after the save
|
||||
await row.scrollIntoViewIfNeeded();
|
||||
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-account-discovery-${lang}-${width}.png`) });
|
||||
}
|
||||
await context.close();
|
||||
});
|
||||
}
|
||||
// MAGPIE_NO_ACCOUNTS: off for this run, and the row says why
|
||||
await t.test(lang + " env", async () => {
|
||||
const { context, page, errors } = await open(browser, lang, 900, [], { noAccountsEnv: true });
|
||||
const box = page.locator("#discoveryList");
|
||||
assert.equal(await box.locator(".opt").nth(0).evaluate((b) => b.classList.contains("on")), true, "Off under MAGPIE_NO_ACCOUNTS");
|
||||
assert((await box.locator(".sub").textContent()).includes("MAGPIE_NO_ACCOUNTS"));
|
||||
assert.deepEqual(errors, []);
|
||||
await context.close();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -36,6 +36,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/claudecode"
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// Account is the signed-in agent behind a provider.
|
||||
@@ -184,6 +185,9 @@ func (p Provider) ListedAPIs(model string) []Protocol {
|
||||
// Sign authenticates a request to the provider, refreshing what needs it.
|
||||
// Plain providers get their key; accounts get the agent's tokens.
|
||||
func (p Provider) Sign(ctx context.Context, req *http.Request, proto Protocol, body []byte) error {
|
||||
if p.Account != nil && settings.AccountDiscoveryOff() {
|
||||
return errAccountDiscoveryOff
|
||||
}
|
||||
ctx = p.Via(ctx) // a sign-in refreshed on the way goes through its proxy
|
||||
if p.Account != nil && p.Account.sign != nil {
|
||||
return p.Account.sign(ctx, req, body)
|
||||
@@ -430,8 +434,11 @@ func claudeCredentialsPath() string {
|
||||
}
|
||||
|
||||
func readClaudeCredential() (claudeCredentials, claudeCredentialLocation, bool) {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return claudeCredentials{}, claudeCredentialLocation{}, false
|
||||
}
|
||||
path := claudeCredentialsPath()
|
||||
if b, err := os.ReadFile(path); err == nil {
|
||||
if b, err := readAccountFile(path); err == nil {
|
||||
if c, ok := parseClaudeCredentials(b); ok {
|
||||
return c, claudeCredentialLocation{path: path}, true
|
||||
}
|
||||
@@ -501,6 +508,9 @@ func keychainText(out []byte) ([]byte, bool) {
|
||||
}
|
||||
|
||||
func claudeCredential() (claudeCredentials, claudeCredentialLocation, bool) {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return claudeCredentials{}, claudeCredentialLocation{}, false
|
||||
}
|
||||
claudeCacheMu.Lock()
|
||||
defer claudeCacheMu.Unlock()
|
||||
if time.Since(claudeCacheAt) < claudeCacheTTL {
|
||||
@@ -525,6 +535,9 @@ func forgetClaudeCredential() {
|
||||
}
|
||||
|
||||
func saveClaudeCredential(loc claudeCredentialLocation, c claudeCredentials) error {
|
||||
if discoveryOff() {
|
||||
return errAccountDiscoveryOff
|
||||
}
|
||||
b, err := c.marshal()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -602,6 +615,9 @@ func claudeIdentity() (user, plan string, signedOut bool) {
|
||||
|
||||
// askClaudeStatus runs `claude auth status`; ok is false when it gave no answer.
|
||||
func askClaudeStatus() (user, plan string, signedOut, ok bool) {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return "", "", false, false
|
||||
}
|
||||
path := claudeExecutable()
|
||||
if path == "" {
|
||||
return "", "", false, false
|
||||
@@ -711,6 +727,9 @@ func refreshFailed(status int, agent, msg string) error {
|
||||
|
||||
// Accounts lists the signed-in agents as providers.
|
||||
func Accounts() []Provider {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return nil
|
||||
}
|
||||
rememberLogins(false)
|
||||
home, _ := os.UserHomeDir()
|
||||
cfg := appdir.Getenv("XDG_CONFIG_HOME")
|
||||
@@ -808,7 +827,7 @@ func placeMoved(out, plugins []Provider) []Provider {
|
||||
}
|
||||
|
||||
func readJSON(path string, v any) bool {
|
||||
b, err := os.ReadFile(path)
|
||||
b, err := readAccountFile(path)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
@@ -879,8 +898,11 @@ type codexAuth struct {
|
||||
}
|
||||
|
||||
func codexAccount(home string) (Provider, bool) {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return Provider{}, false
|
||||
}
|
||||
path := filepath.Join(appdir.CodexHomeIn(home), "auth.json")
|
||||
b, err := os.ReadFile(path)
|
||||
b, err := readAccountFile(path)
|
||||
var a codexAuth
|
||||
if err != nil || json.Unmarshal(b, &a) != nil || a.Tokens.AccessToken == "" || a.AuthMode == "apikey" {
|
||||
return Provider{}, false
|
||||
|
||||
@@ -48,6 +48,9 @@ func (c checkiner) clock() time.Time { return c.now() }
|
||||
// out wbCheckinRetry. It says how every account stands, those it didn't
|
||||
// ask as last kept.
|
||||
func (c checkiner) checkinNow(ctx context.Context, soon bool) []WorkBuddyCheckin {
|
||||
if discoveryOff() {
|
||||
return nil
|
||||
}
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
st := readCheckins(c.path)
|
||||
|
||||
@@ -21,6 +21,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"golang.org/x/text/unicode/norm"
|
||||
)
|
||||
|
||||
@@ -45,6 +46,9 @@ func claudeDirService(dir string) string {
|
||||
// readClaudeDir is the sign-in Claude Code keeps in config directory dir,
|
||||
// where it looks first: the keychain on a Mac, then the file.
|
||||
func readClaudeDir(dir string) (claudeCredentials, bool) {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return claudeCredentials{}, false
|
||||
}
|
||||
if claudeKeychain {
|
||||
out, err := proc.Command("security", "find-generic-password", "-s", claudeDirService(dir), "-a", claudeKeychainAccount(), "-w").Output()
|
||||
if err == nil {
|
||||
@@ -56,7 +60,7 @@ func readClaudeDir(dir string) (claudeCredentials, bool) {
|
||||
}
|
||||
}
|
||||
}
|
||||
b, err := os.ReadFile(filepath.Join(dir, ".credentials.json"))
|
||||
b, err := readAccountFile(filepath.Join(dir, ".credentials.json"))
|
||||
if err != nil {
|
||||
return claudeCredentials{}, false
|
||||
}
|
||||
@@ -66,6 +70,9 @@ func readClaudeDir(dir string) (claudeCredentials, bool) {
|
||||
// clearClaudeDir takes the sign-in out of config directory dir, so the one
|
||||
// it was moved to is its only holder.
|
||||
func clearClaudeDir(dir string) {
|
||||
if discoveryOff() {
|
||||
return
|
||||
}
|
||||
if claudeKeychain {
|
||||
_ = proc.Command("security", "delete-generic-password", "-s", claudeDirService(dir), "-a", claudeKeychainAccount()).Run()
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// cliIdentity is who an agent's CLI says is signed in (`cursor-agent about`,
|
||||
@@ -93,6 +95,9 @@ func (c *cliIdentity) keep() {
|
||||
}
|
||||
|
||||
func (c *cliIdentity) get() (user, plan string, ok bool) {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return "", "", false
|
||||
}
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
if c.at.IsZero() && !c.read {
|
||||
|
||||
@@ -137,6 +137,9 @@ func (c codexWarmer) owned() map[string]string {
|
||||
// the times of day dayAts ("06:00", none for none), or the account's own
|
||||
// (ownAt) — and keeps what it saw.
|
||||
func (c codexWarmer) warmNow(ctx context.Context, which string, dayAts []string) []CodexWarm {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return nil
|
||||
}
|
||||
st := readWarmState(c.path)
|
||||
now := c.now()
|
||||
own := c.owned()
|
||||
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// copilotCLIHeaders are what the CLI sends with its token.
|
||||
@@ -76,6 +77,9 @@ var copilotWSL struct {
|
||||
// CLI keeps it when the distro has no keyring to put it in (WSL has none
|
||||
// unless one is set up): magpie can't reach a distro's keyring.
|
||||
func copilotCLILogin() (copilotApp, bool) {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return copilotApp{}, false
|
||||
}
|
||||
if app, ok := copilotCLILoginIn(copilotCLIHome(), copilotCLISecret); ok {
|
||||
return app, true
|
||||
}
|
||||
@@ -103,7 +107,7 @@ func copilotCLILogin() (copilotApp, bool) {
|
||||
// dir is signed in to, with its token: from its config.json, else from
|
||||
// secret (the keychain), when given.
|
||||
func copilotCLILoginIn(dir string, secret func(string) string) (copilotApp, bool) {
|
||||
raw, err := os.ReadFile(filepath.Join(dir, "config.json"))
|
||||
raw, err := readAccountFile(filepath.Join(dir, "config.json"))
|
||||
if err != nil {
|
||||
return copilotApp{}, false
|
||||
}
|
||||
@@ -153,6 +157,9 @@ var copilotSecrets struct {
|
||||
// copilotCLISecret reads the CLI's token from the keychain, once in a
|
||||
// while: each read may ask the user to allow it.
|
||||
var copilotCLISecret = func(account string) string {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return ""
|
||||
}
|
||||
c := &copilotSecrets
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
|
||||
@@ -35,6 +35,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// CursorExecutable finds the cursor-agent CLI; a var so tests can fake it.
|
||||
@@ -62,7 +63,12 @@ func isCursorAgent(path string) bool {
|
||||
var cursorStatus = &cliIdentity{name: "cursor", exe: func() string { return CursorExecutable() }, ask: askCursorStatus}
|
||||
|
||||
// cursorIdentity is who Cursor's CLI says is signed in; see cliIdentity.
|
||||
func cursorIdentity() (user, plan string, ok bool) { return cursorStatus.get() }
|
||||
func cursorIdentity() (user, plan string, ok bool) {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return "", "", false
|
||||
}
|
||||
return cursorStatus.get()
|
||||
}
|
||||
|
||||
// forgetCursorStatus has who is signed in, and the token, read afresh.
|
||||
func forgetCursorStatus() {
|
||||
@@ -82,6 +88,9 @@ func askCursorIdentity() (user, plan string, ok bool) {
|
||||
// runs out of time (it asks Cursor's servers) or prints something other
|
||||
// than its JSON couldn't tell, and the account stays as it was (#154).
|
||||
func askCursorStatus() (user, plan string, ok bool, err error) {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return "", "", false, nil
|
||||
}
|
||||
path := CursorExecutable()
|
||||
if path == "" {
|
||||
return "", "", false, nil
|
||||
@@ -341,6 +350,9 @@ const cursorTokenTTL = 10 * time.Second
|
||||
// cursorKeychainToken is cursor-agent's token in the Keychain, "" for none;
|
||||
// fresh reads it whatever was read last.
|
||||
func cursorKeychainToken(fresh bool) string {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return ""
|
||||
}
|
||||
cursorTok.Lock()
|
||||
defer cursorTok.Unlock()
|
||||
if !fresh && time.Since(cursorTok.at) < cursorTokenTTL {
|
||||
@@ -359,12 +371,15 @@ func readCursorToken() string { return cursorTokenOf(false) }
|
||||
|
||||
// cursorTokenOf is readCursorToken, fresh from the Keychain when asked.
|
||||
func cursorTokenOf(fresh bool) string {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return ""
|
||||
}
|
||||
if runtime.GOOS == "darwin" {
|
||||
if t := cursorKeychainToken(fresh); t != "" {
|
||||
return t
|
||||
}
|
||||
}
|
||||
b, err := os.ReadFile(cursorAuthFile())
|
||||
b, err := readAccountFile(cursorAuthFile())
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -41,6 +41,9 @@ var cursorKeychain = runtime.GOOS == "darwin"
|
||||
// cursorToken is the access token cursor-agent signed in with: in the
|
||||
// Keychain on a Mac, in its auth.json elsewhere.
|
||||
func cursorToken() (string, error) {
|
||||
if discoveryOff() {
|
||||
return "", errAccountDiscoveryOff
|
||||
}
|
||||
if cursorKeychain {
|
||||
if tok := cursorKeychainToken(false); tok != "" {
|
||||
return tok, nil
|
||||
|
||||
@@ -34,6 +34,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// DevinExecutable finds the devin CLI; a var so tests can fake it.
|
||||
@@ -68,7 +69,12 @@ func DevinCredentialsPath() string {
|
||||
var devinStatus = &cliIdentity{name: "devin", exe: func() string { return DevinExecutable() }, ask: askDevinStatus}
|
||||
|
||||
// devinIdentity is who Devin's CLI says is signed in; see cliIdentity.
|
||||
func devinIdentity() (user, plan string, ok bool) { return devinStatus.get() }
|
||||
func devinIdentity() (user, plan string, ok bool) {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return "", "", false
|
||||
}
|
||||
return devinStatus.get()
|
||||
}
|
||||
|
||||
func forgetDevinStatus() { devinStatus.forget() }
|
||||
|
||||
@@ -100,6 +106,9 @@ func askDevinIdentityAt(home string) (user, plan string, ok bool) {
|
||||
|
||||
// askDevinStatusAt asks the CLI who is signed in in home ("" for its own).
|
||||
func askDevinStatusAt(home string) (user, plan string, ok bool, err error) {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return "", "", false, nil
|
||||
}
|
||||
path := DevinExecutable()
|
||||
if path == "" {
|
||||
return "", "", false, nil
|
||||
@@ -718,7 +727,7 @@ func DevinAuth() (key, server string, err error) { return DevinAuthAt("") }
|
||||
// CLI's own.
|
||||
func DevinAuthAt(home string) (key, server string, err error) {
|
||||
path := devinCredentialsAt(home)
|
||||
b, err := os.ReadFile(path)
|
||||
b, err := readAccountFile(path)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
if home != "" {
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
// Account discovery off (#1535, MaxHaiCom): with Settings → Privacy's
|
||||
// "Subscription accounts" off, `magpie accounts discovery off`, or
|
||||
// MAGPIE_NO_ACCOUNTS=1, magpie reads no agent's sign-in — no
|
||||
// ~/.claude/.credentials.json, ~/.codex/auth.json, Copilot, Cursor, Kiro,
|
||||
// Devin or other credential file, no Keychain or Secret Service item, and
|
||||
// no agent CLI asked who is signed in — and serves no subscription. API-key
|
||||
// providers work as before.
|
||||
//
|
||||
// The gates sit at every source (the readers below Accounts, Logins,
|
||||
// usage, renewal, warm-up, session identities) and every sink that would
|
||||
// write a sign-in (switching, forgetting, sign-in, imports, moves onto
|
||||
// plugins), so a route that skips Accounts still reads nothing. What magpie
|
||||
// kept of its own (logins.json, plugin-auth.json) is left as it is, unread
|
||||
// and unwritten, and comes back when discovery is turned on again.
|
||||
// Middleware plugins and Pi extensions in the plugin host are not
|
||||
// subscriptions and run as before.
|
||||
|
||||
package provider
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
var errAccountDiscoveryOff = errors.New("subscription accounts are off in magpie (Settings → Privacy, or `magpie accounts discovery on`)")
|
||||
|
||||
// discoveryOff is whether agents' sign-ins are left unread; see above.
|
||||
func discoveryOff() bool { return settings.AccountDiscoveryOff() }
|
||||
|
||||
// readAccountFile is os.ReadFile for an agent's credential file, refused
|
||||
// while discovery is off.
|
||||
func readAccountFile(path string) ([]byte, error) {
|
||||
if discoveryOff() {
|
||||
return nil, errAccountDiscoveryOff
|
||||
}
|
||||
return os.ReadFile(path)
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
//go:build !windows
|
||||
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// openWatch turns each path into a FIFO and records every open of one for
|
||||
// reading. A FIFO's reader waits in open until a writer comes, and a
|
||||
// non-blocking open for writing succeeds only while a reader is there, so
|
||||
// a loop of such opens sees each read the moment it starts: whoever opened
|
||||
// it is handed "{}" and an end of file, and the path is noted. A plain
|
||||
// file would be read with nothing to show for it.
|
||||
func openWatch(t *testing.T, paths []string) func() []string {
|
||||
t.Helper()
|
||||
for _, p := range paths {
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := syscall.Mkfifo(p, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var (
|
||||
mu sync.Mutex
|
||||
opened []string
|
||||
)
|
||||
stop := make(chan struct{})
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
}
|
||||
for _, p := range paths {
|
||||
fd, err := syscall.Open(p, syscall.O_WRONLY|syscall.O_NONBLOCK, 0)
|
||||
if err != nil {
|
||||
continue // ENXIO: nobody is reading it
|
||||
}
|
||||
mu.Lock()
|
||||
opened = append(opened, p)
|
||||
mu.Unlock()
|
||||
_, _ = syscall.Write(fd, []byte("{}"))
|
||||
_ = syscall.Close(fd)
|
||||
}
|
||||
time.Sleep(200 * time.Microsecond)
|
||||
}
|
||||
}()
|
||||
// a FIFO left behind blocks the next reader for good: Kiro's IDE folder
|
||||
// is the package's, not this test's (kiro_main_test.go)
|
||||
t.Cleanup(func() {
|
||||
close(stop)
|
||||
<-done
|
||||
for _, p := range paths {
|
||||
os.Remove(p)
|
||||
}
|
||||
})
|
||||
return func() []string {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return slices.Clone(opened)
|
||||
}
|
||||
}
|
||||
|
||||
// recordingTools puts a program first on PATH for each name that notes
|
||||
// that it ran, and fails; the notes are read back by the func returned.
|
||||
func recordingTools(t *testing.T, names []string) func() string {
|
||||
t.Helper()
|
||||
bin := t.TempDir()
|
||||
log := filepath.Join(t.TempDir(), "ran.log")
|
||||
for _, n := range names {
|
||||
script := "#!/bin/sh\necho \"" + n + " $*\" >> '" + log + "'\nexit 1\n"
|
||||
if err := os.WriteFile(filepath.Join(bin, n), []byte(script), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
return func() string {
|
||||
b, _ := os.ReadFile(log)
|
||||
return string(b)
|
||||
}
|
||||
}
|
||||
|
||||
// With subscription account discovery off (#1535, MaxHaiCom), no route
|
||||
// into the accounts — listing them, their usage, renewing, warming,
|
||||
// switching, session identities, check-ins, moves onto plugins — opens an
|
||||
// agent's credential file or runs the Keychain's `security`, Linux's
|
||||
// secret-tool or an agent's CLI to ask who is signed in.
|
||||
func TestAccountDiscoveryOffReadsNoSignIn(t *testing.T) {
|
||||
limitsHome(t)
|
||||
home, _ := os.UserHomeDir()
|
||||
cfg := os.Getenv("XDG_CONFIG_HOME")
|
||||
oldClaude, oldCursor := claudeKeychain, cursorKeychain
|
||||
claudeKeychain, cursorKeychain = true, true // every OS: the Keychain is asked, by the fake
|
||||
t.Cleanup(func() { claudeKeychain, cursorKeychain = oldClaude, oldCursor; ForgetAccounts() })
|
||||
ForgetAccounts()
|
||||
|
||||
if err := settings.Save(settings.Settings{NoAccountDiscovery: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ran := recordingTools(t, []string{"security", "secret-tool", "claude", "codex", "cursor-agent", "devin", "grok", "kiro-cli", "copilot"})
|
||||
files := []string{
|
||||
claudeCredentialsPath(),
|
||||
filepath.Join(home, ".claude.json"),
|
||||
codexAuthPath(),
|
||||
filepath.Join(copilotCLIHome(), "config.json"),
|
||||
filepath.Join(cfg, "github-copilot", "apps.json"),
|
||||
filepath.Join(cfg, "github-copilot", "hosts.json"),
|
||||
cursorAuthFile(),
|
||||
DevinCredentialsPath(),
|
||||
filepath.Join(geminiDir(), "oauth_creds.json"),
|
||||
zcodeCredentialsPath(),
|
||||
cmdAuthPath(),
|
||||
filepath.Join(kiroIDEDir(), "kiro-auth-token.json"),
|
||||
filepath.Join(home, ".local", "share", "opencode", "auth.json"),
|
||||
}
|
||||
slices.Sort(files)
|
||||
files = slices.Compact(files)
|
||||
opened := openWatch(t, files)
|
||||
|
||||
// the watch sees a read: this test's own
|
||||
if b, err := os.ReadFile(codexAuthPath()); err != nil || string(b) != "{}" {
|
||||
t.Fatalf("the watch didn't answer a read: %q %v", b, err)
|
||||
}
|
||||
if got := opened(); len(got) != 1 {
|
||||
t.Fatalf("the watch saw %v, want the test's own read", got)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if ps := Accounts(); len(ps) != 0 {
|
||||
t.Errorf("Accounts with discovery off: %d", len(ps))
|
||||
}
|
||||
for _, p := range All() {
|
||||
if p.Account != nil {
|
||||
t.Errorf("All serves the account %s", p.ID)
|
||||
}
|
||||
}
|
||||
if ls := Logins(""); len(ls) != 0 {
|
||||
t.Errorf("Logins: %v", ls)
|
||||
}
|
||||
for _, agent := range []string{"claude", "codex", "copilot", "cursor", "devin", "kiro"} {
|
||||
Logins(agent)
|
||||
LoginUsage(ctx, agent)
|
||||
Allowances(agent)
|
||||
InUseLogin(agent)
|
||||
NextLogin(ctx, agent)
|
||||
if err := SwitchLogin(agent, "someone@example.com"); err == nil {
|
||||
t.Errorf("SwitchLogin %s with discovery off", agent)
|
||||
}
|
||||
if err := ForgetLogin(agent, "someone@example.com"); err == nil {
|
||||
t.Errorf("ForgetLogin %s with discovery off", agent)
|
||||
}
|
||||
if err := SetLoginOn(agent, "someone@example.com", false); err == nil {
|
||||
t.Errorf("SetLoginOn %s with discovery off", agent)
|
||||
}
|
||||
if _, err := StartSignIn(agent); err == nil {
|
||||
t.Errorf("StartSignIn %s with discovery off", agent)
|
||||
}
|
||||
}
|
||||
SubscriptionUsage(ctx)
|
||||
RenewLogins(ctx, 0)
|
||||
SessionIdentities(filepath.Dir(codexAuthPath()))
|
||||
CodexAPIKeySignedIn()
|
||||
CodexUsedUp(ctx)
|
||||
ClaudeLoginVersion("someone@example.com")
|
||||
claudeIdentity()
|
||||
cursorIdentity()
|
||||
devinIdentity()
|
||||
cursorTokenOf(true)
|
||||
readKiroCLI()
|
||||
readKiroIDE()
|
||||
copilotCLILogin()
|
||||
_, _, _ = DevinAuth()
|
||||
MoveCandidates()
|
||||
MoveRetiring(ctx)
|
||||
HandOver(ctx, true)
|
||||
CheckInWorkBuddy(ctx)
|
||||
CheckInMiniMax(ctx)
|
||||
CheckInTrae(ctx)
|
||||
CheckInQoder(ctx)
|
||||
CheckInPlugins(ctx)
|
||||
if _, err := ImportLogins(ctx, "codex", []string{`{"tokens":{"access_token":"a"}}`}); err == nil {
|
||||
t.Error("ImportLogins with discovery off")
|
||||
}
|
||||
if _, err := ImportFactoryKeys(ctx, []string{"fk-0123456789abcdef0123456789abcdef"}); err == nil {
|
||||
t.Error("ImportFactoryKeys with discovery off")
|
||||
}
|
||||
|
||||
// anything started in the background has its moment
|
||||
time.Sleep(300 * time.Millisecond)
|
||||
if got := opened(); len(got) != 1 {
|
||||
read := slices.Compact(slices.Sorted(slices.Values(got[1:])))
|
||||
t.Errorf("with discovery off, %d reads of sign-ins: %s", len(got)-1, strings.Join(read, " "))
|
||||
}
|
||||
if s := ran(); s != "" {
|
||||
t.Errorf("with discovery off, these ran:\n%s", s)
|
||||
}
|
||||
}
|
||||
|
||||
// MAGPIE_NO_ACCOUNTS turns discovery off for the process, and never on
|
||||
// what the user saved off; a sync or a restored backup keeps this
|
||||
// computer's own choice (KeepOwn).
|
||||
func TestAccountDiscoverySetting(t *testing.T) {
|
||||
limitsHome(t)
|
||||
t.Setenv("MAGPIE_NO_ACCOUNTS", "")
|
||||
if settings.AccountDiscoveryOff() {
|
||||
t.Fatal("off by default")
|
||||
}
|
||||
for v, off := range map[string]bool{"1": true, "true": true, "yes": true, "0": false, "false": false, "FALSE": false} {
|
||||
t.Setenv("MAGPIE_NO_ACCOUNTS", v)
|
||||
if got := settings.AccountDiscoveryOff(); got != off {
|
||||
t.Errorf("MAGPIE_NO_ACCOUNTS=%s: off %v, want %v", v, got, off)
|
||||
}
|
||||
}
|
||||
if err := settings.Save(settings.Settings{NoAccountDiscovery: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("MAGPIE_NO_ACCOUNTS", "0")
|
||||
if !settings.AccountDiscoveryOff() {
|
||||
t.Error("the environment turned on what the user saved off")
|
||||
}
|
||||
var restored settings.Settings
|
||||
restored.KeepOwn(settings.Load())
|
||||
if !restored.NoAccountDiscovery {
|
||||
t.Error("a restored backup turned discovery back on")
|
||||
}
|
||||
if err := SwitchLogin("codex", "x@example.com"); err == nil || !strings.Contains(err.Error(), "magpie accounts discovery on") {
|
||||
t.Errorf("the refusal says how to turn it back on: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,9 @@ func factoryKeysIn(texts []string) []string {
|
||||
// pasted texts, each checked with whoami first, and says what became of
|
||||
// each.
|
||||
func ImportFactoryKeys(ctx context.Context, texts []string) ([]ImportedAccount, error) {
|
||||
if discoveryOff() {
|
||||
return nil, errAccountDiscoveryOff
|
||||
}
|
||||
keys := factoryKeysIn(texts)
|
||||
if len(keys) == 0 {
|
||||
return nil, errors.New("no Factory API keys (fk-…) in it")
|
||||
|
||||
@@ -21,6 +21,8 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// ImportedAccount is what became of one account in an import.
|
||||
@@ -174,6 +176,9 @@ func jsonStr(x map[string]any, keys ...string) string {
|
||||
// (see above), each file's text one element of files, and says what
|
||||
// became of each.
|
||||
func ImportGoogleAccounts(ctx context.Context, agent string, files []string) ([]ImportedAccount, error) {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return nil, errAccountDiscoveryOff
|
||||
}
|
||||
app, ok := googleAppOf(agent)
|
||||
if !ok || agent != "antigravity" {
|
||||
return nil, fmt.Errorf("accounts can't be imported for %s", agent)
|
||||
|
||||
@@ -18,6 +18,8 @@ import (
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// keepAliveEvery is how long a saved sign-in goes before it is renewed.
|
||||
@@ -38,6 +40,9 @@ type Renewal struct {
|
||||
// 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 {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return nil
|
||||
}
|
||||
rememberLogins(false)
|
||||
loginsMu.Lock()
|
||||
active := map[string]string{}
|
||||
|
||||
@@ -43,6 +43,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/proc"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"github.com/yetone/magpie/internal/steady"
|
||||
)
|
||||
|
||||
@@ -121,6 +122,9 @@ func (c kiroCred) fresh() bool {
|
||||
// (Builder ID, IAM Identity Center), or with a company's own identity
|
||||
// provider.
|
||||
func readKiroCLI() (kiroCred, bool) {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return kiroCred{}, false
|
||||
}
|
||||
path := kiroCLIDB()
|
||||
if !fileExists(path) {
|
||||
return kiroCred{}, false
|
||||
@@ -178,6 +182,9 @@ func readKiroCLI() (kiroCred, bool) {
|
||||
|
||||
// readKiroIDE reads the Kiro IDE's sign-in.
|
||||
func readKiroIDE() (kiroCred, bool) {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return kiroCred{}, false
|
||||
}
|
||||
path := filepath.Join(kiroIDEDir(), "kiro-auth-token.json")
|
||||
b, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
@@ -237,6 +244,9 @@ func readKiroAt(key, home string) (kiroCred, bool) {
|
||||
if key != "" {
|
||||
return kiroCred{access: key, method: "apikey", region: "us-east-1"}, true
|
||||
}
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return kiroCred{}, false
|
||||
}
|
||||
if home != "" {
|
||||
return readKiroFile(filepath.Join(home, kiroTokenFile))
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ type kiroSaved struct {
|
||||
|
||||
// readKiroFile reads a sign-in made in magpie.
|
||||
func readKiroFile(path string) (kiroCred, bool) {
|
||||
b, err := os.ReadFile(path)
|
||||
b, err := readAccountFile(path)
|
||||
if err != nil {
|
||||
return kiroCred{}, false
|
||||
}
|
||||
|
||||
@@ -29,6 +29,8 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// loginImport is one account read from a file.
|
||||
@@ -230,6 +232,9 @@ func sub2apiEntry(agent string, x, c map[string]any) loginImport {
|
||||
// accounts from other tools' files (see above), each file's text one
|
||||
// element of files, and says what became of each.
|
||||
func ImportLogins(ctx context.Context, agent string, files []string) ([]ImportedAccount, error) {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return nil, errAccountDiscoveryOff
|
||||
}
|
||||
if agent != "codex" && agent != "claude" {
|
||||
return nil, fmt.Errorf("accounts can't be imported for %s", agent)
|
||||
}
|
||||
|
||||
@@ -7,10 +7,11 @@ package provider
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
var loginUsageCache struct {
|
||||
@@ -75,6 +76,9 @@ func LoginUsage(ctx context.Context, agent string) map[string]SubscriptionQuota
|
||||
// one taken from the cache is up to a minute old already, and Allowances
|
||||
// counts its own minute from then, not from when it asked (#1295).
|
||||
func loginUsageAt(ctx context.Context, agent string) (map[string]SubscriptionQuota, time.Time) {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return nil, time.Time{}
|
||||
}
|
||||
asked := time.Now()
|
||||
if out, ok := loginUsageStandIn(ctx, agent); ok {
|
||||
return out, asked
|
||||
@@ -413,7 +417,7 @@ func CodexUsedUp(ctx context.Context) bool {
|
||||
// file Codex is signed in with, or the one kept for it.
|
||||
func codexLoginAuth(l Login) []byte {
|
||||
if l.Active {
|
||||
b, _ := os.ReadFile(codexAuthPath())
|
||||
b, _ := readAccountFile(codexAuthPath())
|
||||
return b
|
||||
}
|
||||
loginsMu.Lock()
|
||||
|
||||
@@ -30,6 +30,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/filememo"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"github.com/yetone/magpie/internal/steady"
|
||||
)
|
||||
|
||||
@@ -183,6 +184,9 @@ func validLogins(b []byte) bool {
|
||||
}
|
||||
|
||||
func readLogins() []savedLogin {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return nil
|
||||
}
|
||||
// parsed once until the file changes: a state of the page asks for it
|
||||
// dozens of times (every agent's drift and models), and with the
|
||||
// accounts' credentials in it the file is large — a Save of a profile
|
||||
@@ -220,6 +224,9 @@ func unreadBytes(path string) []byte {
|
||||
}
|
||||
|
||||
func writeLogins(ls []savedLogin) error {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return errAccountDiscoveryOff
|
||||
}
|
||||
// every account gets its stable id before it is written (#905): the
|
||||
// one it has, or the stand-in made of its name, there to stay
|
||||
for i := range ls {
|
||||
@@ -493,7 +500,7 @@ func codexAuthPath() string { return filepath.Join(appdir.CodexHome(), "auth.jso
|
||||
// sign-in is a key's, and spends no account a gateway key's list
|
||||
// governs.
|
||||
func CodexAPIKeySignedIn() bool {
|
||||
b, err := os.ReadFile(codexAuthPath())
|
||||
b, err := readAccountFile(codexAuthPath())
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
@@ -512,7 +519,7 @@ func claudeProfilePath() string {
|
||||
}
|
||||
|
||||
func readClaudeProfile() (map[string]any, error) {
|
||||
b, err := os.ReadFile(claudeProfilePath())
|
||||
b, err := readAccountFile(claudeProfilePath())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -529,6 +536,9 @@ func readClaudeProfile() (map[string]any, error) {
|
||||
// signed in to, read again only when the file changes: it is large, and a
|
||||
// page asks for it for every provider it lists. It must not be changed.
|
||||
func claudeProfileAccount() (map[string]any, bool) {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return nil, false
|
||||
}
|
||||
acct, err := filememo.Read("claude account", claudeProfilePath(), func(b []byte) (map[string]any, error) {
|
||||
var m struct {
|
||||
OAuthAccount map[string]any `json:"oauthAccount"`
|
||||
@@ -592,9 +602,12 @@ func savedButSignedOut() []Exclusion {
|
||||
|
||||
// liveLogin reads the account an agent is signed in to now.
|
||||
func liveLogin(agent string) (savedLogin, bool) {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return savedLogin{}, false
|
||||
}
|
||||
switch agent {
|
||||
case "codex":
|
||||
b, err := os.ReadFile(codexAuthPath())
|
||||
b, err := readAccountFile(codexAuthPath())
|
||||
if err != nil {
|
||||
return savedLogin{}, false
|
||||
}
|
||||
@@ -652,6 +665,9 @@ func accountRemoved(agent string) bool {
|
||||
}
|
||||
|
||||
func rememberLogins(force bool) {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return
|
||||
}
|
||||
loginsMu.Lock()
|
||||
defer loginsMu.Unlock()
|
||||
if !force && time.Since(loginsSeenAt) < 30*time.Second {
|
||||
@@ -689,6 +705,9 @@ func rememberLogins(force bool) {
|
||||
// Logins lists the remembered accounts of an agent ("" for every one),
|
||||
// the active one flagged.
|
||||
func Logins(agent string) []Login {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return nil
|
||||
}
|
||||
if pp, ok := pluginOfAgent(agent); ok {
|
||||
return pluginLoginList(pp)
|
||||
}
|
||||
@@ -895,6 +914,9 @@ func loginRoom(agent string) func(user string) (known, spent bool) {
|
||||
// they restart; so does Codex's background app-server, which new Codex
|
||||
// sessions attach to (CodexDaemonStale says when it is).
|
||||
func SwitchLogin(agent, user string) error {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return errAccountDiscoveryOff
|
||||
}
|
||||
// the user's own choice: magpie doesn't sign the agent back in to the
|
||||
// account it moved it off
|
||||
if slices.Contains(loginAgents, agent) {
|
||||
@@ -1082,6 +1104,9 @@ func putClaudeLogin(l savedLogin) error {
|
||||
// instead, as `codex logout` does (mamba on Discord: a single Codex account
|
||||
// couldn't be removed at all).
|
||||
func ForgetLogin(agent, user string) error {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return errAccountDiscoveryOff
|
||||
}
|
||||
if pp, ok := pluginOfAgent(agent); ok {
|
||||
return forgetPluginLogin(pp, user)
|
||||
}
|
||||
|
||||
@@ -25,6 +25,9 @@ var savedTokenMu sync.Mutex
|
||||
// SetLoginOn puts a saved account in use beside the agent's own, or takes
|
||||
// it out. The account the agent is signed in to is always in use.
|
||||
func SetLoginOn(agent, user string, on bool) error {
|
||||
if discoveryOff() {
|
||||
return errAccountDiscoveryOff
|
||||
}
|
||||
if pp, ok := pluginOfAgent(agent); ok {
|
||||
return setPluginLoginOn(pp, user, on)
|
||||
}
|
||||
|
||||
@@ -43,6 +43,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/filememo"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
"github.com/yetone/magpie/internal/update"
|
||||
)
|
||||
|
||||
@@ -268,6 +269,9 @@ type MoveCandidate struct {
|
||||
// MoveCandidates are the built-ins not on their plugins that have accounts
|
||||
// to move, by name.
|
||||
func MoveCandidates() []MoveCandidate {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return nil
|
||||
}
|
||||
out := []MoveCandidate{}
|
||||
for id, mv := range movers {
|
||||
if Moved(id) {
|
||||
@@ -474,6 +478,9 @@ var modelsInUse = func(id string) []string {
|
||||
// Move puts the built-in id's accounts onto its plugin (see above). An
|
||||
// error leaves the built-in as it was.
|
||||
func Move(ctx context.Context, id string) error {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return errAccountDiscoveryOff
|
||||
}
|
||||
mv := movers[id]
|
||||
if mv == nil {
|
||||
return fmt.Errorf("%s has no plugin to move to", id)
|
||||
@@ -505,6 +512,9 @@ func Move(ctx context.Context, id string) error {
|
||||
// signed in: the plugin installed, and the subscription signs in through
|
||||
// it from now on, as a moved one does. One with accounts is moved instead.
|
||||
func Adopt(ctx context.Context, id string) error {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return errAccountDiscoveryOff
|
||||
}
|
||||
mv := movers[id]
|
||||
if mv == nil {
|
||||
return fmt.Errorf("%s has no plugin to move to", id)
|
||||
@@ -946,6 +956,9 @@ func MoveBack(ctx context.Context, id string) error {
|
||||
// serves nothing else now, which releasePlugin, about to remove or turn
|
||||
// off the plugin itself, leaves to its caller.
|
||||
func moveBack(ctx context.Context, id string, tidy bool) error {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return errAccountDiscoveryOff
|
||||
}
|
||||
mv := movers[id]
|
||||
if mv == nil {
|
||||
return fmt.Errorf("%s isn't a built-in subscription", id)
|
||||
@@ -1112,6 +1125,9 @@ func pluginOn(id string) map[string]bool {
|
||||
// start-up: once, or again moveRetry after one failed. One the user moved
|
||||
// back stays.
|
||||
func MoveRetiring(ctx context.Context) map[string]error {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return nil
|
||||
}
|
||||
out := map[string]error{}
|
||||
for _, id := range Retiring {
|
||||
m, ok := MigrationOf(id)
|
||||
@@ -1146,6 +1162,9 @@ func MoveRetiring(ctx context.Context) map[string]error {
|
||||
// user moved back stays built-in, and a failed move waits moveRetry. No
|
||||
// plugin is installed for it: the user's own install is what says to.
|
||||
func HandOver(ctx context.Context, accounts bool) map[string]error {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return nil
|
||||
}
|
||||
out := map[string]error{}
|
||||
var pps []plugin.Provider
|
||||
asked := false
|
||||
@@ -1221,6 +1240,10 @@ func KeepRetiringMoved(ctx context.Context) {
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
if settings.AccountDiscoveryOff() {
|
||||
t.Reset(time.Hour)
|
||||
continue
|
||||
}
|
||||
keepMovedCurrent(ctx)
|
||||
moves := MoveRetiring(ctx)
|
||||
maps.Copy(moves, HandOver(ctx, true))
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// A plugin's provider is signed in to as many times as the user likes, as
|
||||
@@ -120,6 +121,9 @@ var pluginOwnUser = func(id string) string {
|
||||
// own account is named as the agent is signed in now; removed in magpie,
|
||||
// it is only hidden, and shows again once the agent signs in anew.
|
||||
func pluginLogins(pp plugin.Provider) []pluginLogin {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return nil
|
||||
}
|
||||
agent := pluginAgent(pp)
|
||||
labels := pluginLabels(pp)
|
||||
byKey := map[string]plugin.Account{}
|
||||
|
||||
@@ -122,6 +122,9 @@ type pluginCheckiner struct {
|
||||
func (c pluginCheckiner) clock() time.Time { return c.now() }
|
||||
|
||||
func (c pluginCheckiner) checkinNow(ctx context.Context, soon bool) []WorkBuddyCheckin {
|
||||
if discoveryOff() {
|
||||
return nil
|
||||
}
|
||||
var out []WorkBuddyCheckin
|
||||
for _, p := range pluginCheckinProviders() {
|
||||
if c.only != nil && !c.only(p.ID) {
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// StartPluginSignIn begins signing in to a plugin's provider (OpenCode's
|
||||
@@ -19,6 +20,9 @@ import (
|
||||
// is. A built-in moved onto its plugin installs the CLI it runs through
|
||||
// first, as the built-in's sign-in did.
|
||||
func StartPluginSignIn(id string, method int, inputs map[string]string) (SignInState, error) {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return SignInState{}, errAccountDiscoveryOff
|
||||
}
|
||||
s := &signInFlow{done: make(chan struct{})}
|
||||
s.st = SignInState{ID: randomToken(9), Agent: PluginID(id), State: "waiting"}
|
||||
var cli agentCLI
|
||||
|
||||
@@ -431,9 +431,12 @@ func store(f file) error {
|
||||
// over, past the 5 s Codex waits for the list (#746).
|
||||
func All() []Provider {
|
||||
held := heldOf("all", allProviders)
|
||||
out := make([]Provider, len(held))
|
||||
for i, p := range held {
|
||||
out[i] = p.clone() // callers change theirs, Keys[i] and Headers included
|
||||
out := make([]Provider, 0, len(held))
|
||||
for _, p := range held {
|
||||
if p.Account != nil && settings.AccountDiscoveryOff() {
|
||||
continue
|
||||
}
|
||||
out = append(out, p.clone()) // callers change theirs, Keys[i] and Headers included
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ import (
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/qoder"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// qoderMu serializes checking, rotating and saving tokens, including sign-in
|
||||
@@ -157,6 +158,9 @@ func qoderSaved(l savedLogin) (qoder.Credential, bool) {
|
||||
// With nothing to move it takes no lock, so listing accounts doesn't wait
|
||||
// behind a refresh.
|
||||
func migrateQoder() error {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return nil
|
||||
}
|
||||
path := filepath.Join(filepath.Dir(Path()), "qoder.json")
|
||||
if _, err := os.Stat(path); os.IsNotExist(err) {
|
||||
return nil
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/filememo"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// SessionIdentity is an account's public identity, without its credentials.
|
||||
@@ -24,6 +25,9 @@ type SessionIdentity struct {
|
||||
// Callers must match the IDs recorded in a session; presence alone is not evidence
|
||||
// that the account served that session's requests.
|
||||
func SessionIdentities(codexDir string) []SessionIdentity {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return nil
|
||||
}
|
||||
out := currentSessionIdentities(codexDir)
|
||||
var saved []SessionIdentity
|
||||
for _, l := range readLogins() {
|
||||
@@ -104,6 +108,9 @@ func claudeSessionIdentity(b []byte) (SessionIdentity, bool) {
|
||||
}
|
||||
|
||||
func currentSessionIdentities(codexDir string) []SessionIdentity {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return nil
|
||||
}
|
||||
var out []SessionIdentity
|
||||
// Cache only the identity parse, not another copy of the credential blob.
|
||||
current, _ := filememo.Read("session codex identity", filepath.Join(codexDir, "auth.json"), func(b []byte) ([]SessionIdentity, error) {
|
||||
|
||||
@@ -26,6 +26,8 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// The vendors' sign-in pages; vars so tests can point them elsewhere.
|
||||
@@ -122,6 +124,9 @@ func StartSignIn(agent string) (SignInState, error) {
|
||||
// StartSignInAt is StartSignIn on one of the sites an agent signs in on:
|
||||
// ZCode's "zai" (the default) or "bigmodel".
|
||||
func StartSignInAt(agent, site string) (SignInState, error) {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return SignInState{}, errAccountDiscoveryOff
|
||||
}
|
||||
// one moved onto its plugin signs in there: an account signed in to
|
||||
// here would be the built-in's, which nothing serves now
|
||||
if Moved(agent) {
|
||||
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
"github.com/yetone/magpie/internal/netproxy"
|
||||
"github.com/yetone/magpie/internal/plugin"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// QuotaWindow is one rolling allowance reported by a subscription provider.
|
||||
@@ -188,6 +189,9 @@ var subscriptionTimeout = 20 * time.Second
|
||||
// cached it comes back at once, and a stale copy is refreshed in the
|
||||
// background; only the very first call waits, for as long as ctx allows.
|
||||
func SubscriptionUsage(ctx context.Context) []SubscriptionQuota {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return nil
|
||||
}
|
||||
c := &subscriptionUsageCache
|
||||
c.Lock()
|
||||
have, fresh := c.data != nil, time.Since(c.at) < time.Minute
|
||||
@@ -327,6 +331,9 @@ func chosenWindows(ws []QuotaWindow, chosen map[string]bool, base func(string) s
|
||||
|
||||
// fetchSubscriptionUsage asks every signed-in vendor at once.
|
||||
func fetchSubscriptionUsage(ctx context.Context) []SubscriptionQuota {
|
||||
if settings.AccountDiscoveryOff() {
|
||||
return nil
|
||||
}
|
||||
ctx, _ = quotaReading(ctx)
|
||||
// read for every card's caller alike, or for the one card ctx reads
|
||||
// again (RefreshUsage), as long as a refresh of them all would be
|
||||
@@ -828,7 +835,7 @@ func codexSubscriptionUsage(ctx context.Context, path string) SubscriptionQuota
|
||||
return q
|
||||
}
|
||||
q.Plan, q.Windows, q.Resets, q.Balance, q.Held, err = codexWindows(ctx, token, accountID)
|
||||
if b, rerr := os.ReadFile(path); rerr == nil {
|
||||
if b, rerr := readAccountFile(path); rerr == nil {
|
||||
q.Until = codexUntil(b, time.Now())
|
||||
}
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package settings
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// AccountDiscoveryOff is whether magpie leaves agents' sign-ins unread
|
||||
// (#1535): NoAccountDiscovery saved, or MAGPIE_NO_ACCOUNTS set to anything
|
||||
// but "", "0" or "false" for this process alone. The variable only ever
|
||||
// turns discovery off; it never turns on what the user saved off.
|
||||
func AccountDiscoveryOff() bool {
|
||||
if v := strings.ToLower(strings.TrimSpace(os.Getenv("MAGPIE_NO_ACCOUNTS"))); v != "" && v != "0" && v != "false" {
|
||||
return true
|
||||
}
|
||||
return Load().NoAccountDiscovery
|
||||
}
|
||||
@@ -185,6 +185,13 @@ type Settings struct {
|
||||
// is stuck in a loop of the same few lines (#1359). Off, as by
|
||||
// default, the gateway ends such a reply with an error.
|
||||
NoLoopGuard bool `json:"noLoopGuard,omitempty"`
|
||||
// NoAccountDiscovery leaves every agent's sign-in unread (#1535,
|
||||
// MaxHaiCom): no credential file, Keychain item or agent CLI is asked
|
||||
// who is signed in, and no subscription is offered; API-key providers
|
||||
// work as before (see AccountDiscoveryOff, provider/discovery.go). Off,
|
||||
// as by default, subscriptions are found as ever. This computer's own
|
||||
// (KeepOwn), set only by its own switch or `magpie accounts discovery`.
|
||||
NoAccountDiscovery bool `json:"noAccountDiscovery,omitempty"`
|
||||
// NoStats stops the one event a day that counts magpie's users (see
|
||||
// internal/stats).
|
||||
NoStats bool `json:"noStats,omitempty"`
|
||||
@@ -762,7 +769,7 @@ func (s Settings) Compact() int {
|
||||
|
||||
// KeepOwn puts back cur's settings that are this computer's own, which a
|
||||
// sync or a restored backup never brings from another: the window's size
|
||||
// and whether it was maximised, the proxy, the gateway's port, the Dock, gateway mode, whether WSL is looked in, when allowances are read, and what the menu bar or tray shows beside magpie's
|
||||
// and whether it was maximised, the proxy, the gateway's port, the Dock, gateway mode, whether WSL is looked in, whether agents' sign-ins are read, when allowances are read, and what the menu bar or tray shows beside magpie's
|
||||
// icon (yoooo on Discord: usage turned off on a Mac came back from a
|
||||
// Windows box that shows it).
|
||||
func (s *Settings) KeepOwn(cur Settings) {
|
||||
@@ -774,6 +781,7 @@ func (s *Settings) KeepOwn(cur Settings) {
|
||||
s.GatewayMode = cur.GatewayMode
|
||||
s.NoWSLAgents = cur.NoWSLAgents
|
||||
s.QuotaReads = cur.QuotaReads
|
||||
s.NoAccountDiscovery = cur.NoAccountDiscovery
|
||||
}
|
||||
|
||||
// RenamePerModel moves what the user said of a provider's models to the id
|
||||
|
||||
@@ -82,6 +82,7 @@ const usage = `magpie — one place to pick every agent's model
|
||||
magpie accounts [agent] [--json] every subscription magpie knows, with each one's allowance used and when it resets
|
||||
magpie accounts add <agent> sign in to one more Claude, ChatGPT or Google (Gemini CLI, Antigravity) subscription
|
||||
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 refresh renew the saved ChatGPT sign-ins now (the gateway does it daily)
|
||||
@@ -197,6 +198,9 @@ func run(args []string) error {
|
||||
// (agent.DisconnectPreview)
|
||||
return agent.DryRun(args[1])
|
||||
}
|
||||
if len(args) > 1 && (args[0] == "accounts" || args[0] == "account") && args[1] == "discovery" {
|
||||
return accountsDiscoveryCmd(args[2:])
|
||||
}
|
||||
// started by an update, the magpie it replaces goes first: the moves
|
||||
// below write the files it may still be writing
|
||||
update.AwaitPredecessor()
|
||||
|
||||
@@ -244,6 +244,7 @@ magpie claude group/opus-anywhere <span class="c"># これを使う</span></p
|
||||
<tr><td><code>magpie presets</code></td><td>magpie が知っているベンダー</td></tr>
|
||||
<tr><td><code>magpie provider add deepseek sk-…</code></td><td>プリセットをキー付きで追加</td></tr>
|
||||
<tr><td><code>magpie accounts add codex</code></td><td>Claude または ChatGPT のサブスクリプションをもう 1 つサインイン</td></tr>
|
||||
<tr><td><code>magpie accounts discovery off</code></td><td>エージェントのサインイン(Claude Code と Codex のファイル、キーチェーン)を読み取らない。<code>on</code> で再び読み取る</td></tr>
|
||||
<tr><td><code>magpie providers</code></td><td>プロバイダ一覧:ホスト、キー、モデル、使っているエージェント</td></tr>
|
||||
<tr><td><code>magpie models</code></td><td>エージェントが選べるすべてのモデル(<code>provider/model</code> 形式)</td></tr>
|
||||
<tr><td><code>magpie claude codex/gpt-5.5</code></td><td>エージェントのモデルを設定</td></tr>
|
||||
|
||||
@@ -244,6 +244,7 @@ magpie claude group/opus-anywhere <span class="c"># use it</span></pre>
|
||||
<tr><td><code>magpie presets</code></td><td>The vendors magpie knows</td></tr>
|
||||
<tr><td><code>magpie provider add deepseek sk-…</code></td><td>Add a preset with its key</td></tr>
|
||||
<tr><td><code>magpie accounts add codex</code></td><td>Sign in to one more Claude or ChatGPT subscription</td></tr>
|
||||
<tr><td><code>magpie accounts discovery off</code></td><td>Never read your agents’ sign-ins (Claude Code’s and Codex’s files, the Keychain); <code>on</code> reads them again</td></tr>
|
||||
<tr><td><code>magpie providers</code></td><td>Your providers: host, key, models, who uses them</td></tr>
|
||||
<tr><td><code>magpie models</code></td><td>Every model agents can pick, as <code>provider/model</code></td></tr>
|
||||
<tr><td><code>magpie claude codex/gpt-5.5</code></td><td>Set an agent’s model</td></tr>
|
||||
|
||||
@@ -244,6 +244,7 @@ magpie claude group/opus-anywhere <span class="c"># 使用它</span></pre>
|
||||
<tr><td><code>magpie presets</code></td><td>magpie 内置的厂商预设</td></tr>
|
||||
<tr><td><code>magpie provider add deepseek sk-…</code></td><td>用密钥添加一个预设</td></tr>
|
||||
<tr><td><code>magpie accounts add codex</code></td><td>再登录一个 Claude 或 ChatGPT 订阅</td></tr>
|
||||
<tr><td><code>magpie accounts discovery off</code></td><td>不读取智能体的登录信息(Claude Code 和 Codex 的文件、钥匙串);<code>on</code> 重新读取</td></tr>
|
||||
<tr><td><code>magpie providers</code></td><td>你的供应商:地址、密钥、模型、谁在用</td></tr>
|
||||
<tr><td><code>magpie models</code></td><td>Agent 能选的所有模型,写作 <code>provider/model</code></td></tr>
|
||||
<tr><td><code>magpie claude codex/gpt-5.5</code></td><td>设置 Agent 的模型</td></tr>
|
||||
|
||||
Reference in New Issue
Block a user