cli: magpie's commands move from the root into internal/cli; the root keeps only main.go

The root held 89 .go files (30 commands, 59 tests). They move as they are
to internal/cli (package cli), with git mv so history follows them. The
only code change is main() becoming cli.Main(version): the root's new
main.go keeps `var version` in package main, so -ldflags "-X
main.version=…" in the Makefile, the Dockerfile and magpie-releases, and
every workflow, work unchanged. go-winres's rsrc_windows_*.syso still land
next to package main in the root.

Tests that read testdata by a root-relative path now go up one level
(../plugin/testdata/fake, ../sessions/testdata). Five subsystem doc links
point at internal/cli/.

Run:
- go build ./..., gofmt -l, go vet on darwin, linux and windows (nogui)
- builds with tags production, dev, "production nogui"; windows
  -H windowsgui; linux CGO_ENABLED=0
- make release-cli TARGETS="darwin/arm64 linux/amd64 windows/amd64
  android/arm64" VERSION=9.9.9-tidy: all four built, binary prints
  "magpie 9.9.9-tidy"
- docker build --build-arg VERSION=7.7.7-tidy: container prints
  "magpie 7.7.7-tidy"
- go test ./internal/cli (default and nogui): 152 tests, the same count
  as the root on main
- go test ./...: all packages pass (agent, gateway, library, provider
  timed out at 10m under other sessions' load and passed rerun alone
  with -timeout 40m; none of them changed)
- the built binary in a sandbox HOME: version, help, ls, providers,
  claude, and an unknown command's error
This commit is contained in:
yetone
2026-10-12 20:40:22 +08:00
parent d56da7e896
commit 23e764d0e0
93 changed files with 760 additions and 744 deletions
+1 -1
View File
@@ -10,7 +10,7 @@ A plugin can be gateway middleware: JavaScript that magpie runs inside its gatew
| Bun host | Skip a plugin that is middleware only (no `main`, no `exports`) | `Middleware(...)` check in [`host.go`](../../internal/plugin/host.go) |
| Load and run | Compile, pool runtimes, call hooks with limits, count calls and failures | [`internal/middleware`](../../internal/middleware): `middleware.go`, `run.go` |
| Gateway | Run the chain on agents' requests only | `serveAgent` in [`internal/gateway/middleware.go`](../../internal/gateway/middleware.go), called from `gateway.go` and `codex_backend.go` |
| GUI and CLI | Show each middleware's hooks, calls, µs per call, failures and load error | `middleware.States()`; `pluginEntryJSON.Middleware` in [`internal/gui/plugins.go`](../../internal/gui/plugins.go), `mwLine` in `plugins.js`, `listPlugins` in [`plugins_cli.go`](../../plugins_cli.go) |
| GUI and CLI | Show each middleware's hooks, calls, µs per call, failures and load error | `middleware.States()`; `pluginEntryJSON.Middleware` in [`internal/gui/plugins.go`](../../internal/gui/plugins.go), `mwLine` in `plugins.js`, `listPlugins` in [`plugins_cli.go`](../../internal/cli/plugins_cli.go) |
| Options | A middleware's `options` in plugins.json, as `ctx.options`; set by name, spec or short name; a package's `magpie.options` is only the editor's example | `SetOptions`, `ShortName` in [`store.go`](../../internal/plugin/store.go); `pluginOptions` in `plugins_cli.go`; `optionsEditor` in `plugins.js` |
| Kind | Whether a plugin is a provider, middleware or both, shown on every card and row, also for one that is off | `isMiddleware`, `middlewareOnly` in `pluginEntryJSON`; `kind: "middleware"` market entries (`market.json`, the community `registry.json`); `kindChip` in `plugins.js` |
| Community middleware | Ready-made packages (`@magpie-community/middleware-<name>`), mostly New API's channel settings | `packages/{param-override,model-map,system-prompt,word-guard,think-tags}` in [magpie-community/plugins](https://github.com/magpie-community/plugins), tested with `scripts/middleware.mjs` |
+1 -1
View File
@@ -17,7 +17,7 @@ three.
| Browser mode | `StartWeb` serves the page and the gateway for `magpie web`. The browser signs in with a run key in a link. Gateway mode shows Providers, Gateway, Routing, Usage, Sessions, Plugins and Settings on a machine that is only a gateway. `webHandler` gzips the page's text files and the API's JSON for a browser that takes gzip (`webCompressed`, with a `-gzip` ETag that still answers 304); the app's own windows read the page in-process and get it uncompressed. | [`web.go`](../../internal/gui/web.go), [`gatewaymode.go`](../../internal/gui/gatewaymode.go) |
| The page | `app.js` keeps one state object per view and renders it into a list, with no framework. The views have their own files: `routing.js`, `library.js`, `plugins.js`, `sessions.js` and `context.js` (Usage's Context tab, and the context window card the Routing page draws under a request's story, fed by `/api/context` in `context.go`, which scores and tags each agent; clicking a part, a cell or an item opens its text from `/api/context/text`, the last 10 requests' masked bodies in memory (`openCtxText`), rendered 100 items and 20000 characters at a time; its "Tuned for you" cards are fed by `/api/tune` in `tune.go`, see [agent wiring](agent-wiring.md)). Strings go through `t()` with translations in `i18n.js` (zh, zh-TW, ja and de; the English text is the key and the fallback). zh-TW is Traditional Chinese with Taiwan's words; a system language of zh-TW, zh-HK, zh-MO or any zh-Hant picks it, and the tray menu and notifications follow (`trayLang`). Dropdowns use `openProtoMenu`. Every app menu (`openProtoMenu`, `openRowMenu`, `openSessCombo`) is placed by `placeMenu`: under its anchor, or over it when the window runs out below; one that fits neither way takes the larger room, its height held to it, and scrolls inside itself, and a scroll inside a menu doesn't close it (#1437, `removed-groups-menu-scroll.test.cjs`). The highest any popover goes is `popTop`: 8px under `header.top` on a Mac window, where the traffic lights are drawn over the page, and 8px from the top elsewhere; `placeMenu`, the field picker's `placePop` (which also holds `#pop`'s height to that room) and an agent's model list (`openAgentModels`) all use it (#1573, `popover-mac-chrome.test.cjs`). Scrolling is done only by `scrollOnPurpose(e)` with the reader's event. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/i18n.js`](../../internal/gui/assets/i18n.js) |
| Window navigation | In the window from 1024 points wide (`SIDE_AT`, the same width as app.css's `side-nav` rules), `layoutNav` moves the brand, the pages (`#nav`) and Settings into the sidebar (`#side`): the pages in four groups (Work, Models, Insights, Extend; a group none of whose pages shows, as in gateway mode, leaves out its name), the gateway's address at its foot (`sideGwRead`, read from `/api/providers` only while there is a sidebar), and the header a breadcrumb (`renderCrumb`). The open page's own tabs (`NAV_SUBS`: Usage, Library, Plugins, Settings) are listed under it as `.nav-s` rows (`role="tab"`, `data-of` the page tab's id) and the page's strip is hidden; a row's click clicks that tab at once, the selection (`.nav-hl`) having set off as the row was pressed (`navSubGlide`; back if the press leaves the row), and is the list's only shape: a row hovered or pressed has no ground of its own, and a `MutationObserver` draws the list again when the strip changes. The list opens and folds with an iOS-like spring (`navSubEnter`, `navSubLeave`; none under reduced motion), and a folding list is out of reach at once. Narrower, the page beside a sidebar would be narrower than Usage's requests table needs (768 points), so they go back into the header's row, as a Mac sidebar gives way in a narrow window. At every width the reader can pick the sidebar or the header's tabs from the title bar's button (`#sideToggle`, ⌃⌘S or Ctrl+Shift+S; `toggleSideNav`), kept in localStorage `magpie.navLayout` (`side` or `top`) and so laid out from the first frame; none picked, the sidebar comes from `SIDE_AT`. Picked in a narrow window the sidebar is narrower (184 points under 860), and magpie web on a phone keeps its own tab bar and has no button. The two layouts trade places in a view transition (`navMorph`, app.css `.nav-morph`): the sidebar slides, each page's tab flies to its place in the other, and the page slides as one (its old image dropped, so no line prints twice); without view transitions, under reduced motion, or in the Linux app the change is at once: WebKitGTK with compositing off (`WEBKIT_DISABLE_COMPOSITING_MODE`, which `webkit_linux.go` sets under Wayland) crashes in a view transition. Elsewhere a transition still going after `MORPH_MAX` (1.5s) is skipped, so a webview that never ends one can't leave the window on the old layout's picture. See `side-toggle.test.cjs`. A window made wider or narrower drops what a click held (`heldWidth`): the page laid out again isn't the click's doing. See `sidebar.test.cjs`. | [`assets/app.js`](../../internal/gui/assets/app.js), [`assets/app.css`](../../internal/gui/assets/app.css) |
| No GUI build | `-tags nogui` builds magpie without the GUI: `hasGUI` is false and `runGUI` says to use `magpie tui`. The files of `internal/gui` that need Wails build under `!nogui`. | [`gui_off.go`](../../gui_off.go) |
| No GUI build | `-tags nogui` builds magpie without the GUI: `hasGUI` is false and `runGUI` says to use `magpie tui`. The files of `internal/gui` that need Wails build under `!nogui`. | [`gui_off.go`](../../internal/cli/gui_off.go) |
## Runtime path
+3 -3
View File
@@ -29,8 +29,8 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
| 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`). ChatGPT's sign-in comes back only to port 1455; when that port can't be opened, the sign-in still starts and waits for the pasted address alone, and says why in `CallbackBlocked` with the port in `CallbackPort`: `reserved` for Windows' WSAEACCES on a port in a range it excludes for Hyper-V, WSL or Docker, `busy` for anything else, such as another program holding it (`callbackBlocked`, #1782). 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`. A sign-in leaves through the proxy the account's own requests will use (#1663): `ProxyOfLogin` (the account's, else the subscription's, else the global one) for the account being signed in again, the subscription's for a new one. Every request of the flow goes through `signInFlow.via`, Claude Code's own login gets it as *_PROXY (`netproxy.EnvWith`), and a plugin's sign-in runs its fetch under that proxy (`via` in `host.js`; `plugins_cli.go` for the command line). The window's sign-in box shows it as a "Proxy: …" link (`signInProxyLink`, the app menu, no userinfo shown) with Global, Direct, the subscription's and each account's proxy, or a typed one; picking one starts the sign-in again through it (`SignInOptions.Proxy`), and when it ends the pick is kept as the account's (`keepSignInProxy`: the subscription's own when it is its only account, else the account's entry). Global isn't offered while the subscription has a proxy and other accounts, since nothing could keep it. The browser's own leg goes through the browser's network, not magpie's. Signing out leaves through the same exit: a ChatGPT account's refresh token is revoked through its own proxy, read before the account is forgotten (`forgetSIWCLogin`), and Devin's CLI, asked who is signed in or for its models, runs with the account's proxy (`devinCommand`, `devinProxy`), or with the sign-in's while one asks it. | [`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), [`proxy.go`](../../internal/provider/proxy.go), [`plugins_cli.go`](../../plugins_cli.go) |
| Import from files | `ImportLogins` (ChatGPT, Claude), `ImportGoogleAccounts` (Antigravity) and `ImportFactoryKeys` take other tools' files, from the window (`signin/import`) or `magpie accounts import` (#1453). ChatGPT reads Codex's `auth.json`, CLIProxyAPI's and Cockpit Tools' files, Sub2API's export (`sub2apiEntry`) and codexbar's `~/.codexbar/config.json` (`codexbarEntries`: the `openai_oauth` provider's accounts and `openAI.remoteConnectionAccounts`, the workspace from `openAIAccountId`). Each ChatGPT and Google sign-in is refreshed before it is added, so the tool the file came from is signed out of it; both surfaces say so first, and the command imports nothing without `--yes` or a yes. Claude's are kept as the file has them. A refresh token magpie holds already is `exists`, never refreshed; accounts are matched by email and workspace (`sameLogin`). An entry with an access token and no refresh token is refused (`accessOnly`). One file of several that holds no account is a failed row with its place (`ImportedAccount.File`), never skipped. The files are only read. | [`login_import.go`](../../internal/provider/login_import.go), [`google_import.go`](../../internal/provider/google_import.go), [`factory_key.go`](../../internal/provider/factory_key.go), [`accounts_cli.go`](../../accounts_cli.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`). ChatGPT's sign-in comes back only to port 1455; when that port can't be opened, the sign-in still starts and waits for the pasted address alone, and says why in `CallbackBlocked` with the port in `CallbackPort`: `reserved` for Windows' WSAEACCES on a port in a range it excludes for Hyper-V, WSL or Docker, `busy` for anything else, such as another program holding it (`callbackBlocked`, #1782). 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`. A sign-in leaves through the proxy the account's own requests will use (#1663): `ProxyOfLogin` (the account's, else the subscription's, else the global one) for the account being signed in again, the subscription's for a new one. Every request of the flow goes through `signInFlow.via`, Claude Code's own login gets it as *_PROXY (`netproxy.EnvWith`), and a plugin's sign-in runs its fetch under that proxy (`via` in `host.js`; `plugins_cli.go` for the command line). The window's sign-in box shows it as a "Proxy: …" link (`signInProxyLink`, the app menu, no userinfo shown) with Global, Direct, the subscription's and each account's proxy, or a typed one; picking one starts the sign-in again through it (`SignInOptions.Proxy`), and when it ends the pick is kept as the account's (`keepSignInProxy`: the subscription's own when it is its only account, else the account's entry). Global isn't offered while the subscription has a proxy and other accounts, since nothing could keep it. The browser's own leg goes through the browser's network, not magpie's. Signing out leaves through the same exit: a ChatGPT account's refresh token is revoked through its own proxy, read before the account is forgotten (`forgetSIWCLogin`), and Devin's CLI, asked who is signed in or for its models, runs with the account's proxy (`devinCommand`, `devinProxy`), or with the sign-in's while one asks it. | [`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), [`proxy.go`](../../internal/provider/proxy.go), [`plugins_cli.go`](../../internal/cli/plugins_cli.go) |
| Import from files | `ImportLogins` (ChatGPT, Claude), `ImportGoogleAccounts` (Antigravity) and `ImportFactoryKeys` take other tools' files, from the window (`signin/import`) or `magpie accounts import` (#1453). ChatGPT reads Codex's `auth.json`, CLIProxyAPI's and Cockpit Tools' files, Sub2API's export (`sub2apiEntry`) and codexbar's `~/.codexbar/config.json` (`codexbarEntries`: the `openai_oauth` provider's accounts and `openAI.remoteConnectionAccounts`, the workspace from `openAIAccountId`). Each ChatGPT and Google sign-in is refreshed before it is added, so the tool the file came from is signed out of it; both surfaces say so first, and the command imports nothing without `--yes` or a yes. Claude's are kept as the file has them. A refresh token magpie holds already is `exists`, never refreshed; accounts are matched by email and workspace (`sameLogin`). An entry with an access token and no refresh token is refused (`accessOnly`). One file of several that holds no account is a failed row with its place (`ImportedAccount.File`), never skipped. The files are only read. | [`login_import.go`](../../internal/provider/login_import.go), [`google_import.go`](../../internal/provider/google_import.go), [`factory_key.go`](../../internal/provider/factory_key.go), [`accounts_cli.go`](../../internal/cli/accounts_cli.go) |
| Used-up switch | When the account Codex or Claude Code is signed in to has used its allowance, the agent is signed in to the next account that is on and has room (#208). | [`codex_switch.go`](../../internal/provider/codex_switch.go) |
| Routing groups | User-made groups from the Routing view, and auto-found groups of the same model across providers (derived, never stored). Members are `provider/model[:effort]`. A group can nest another (`group/<id>`); `SaveGroup` refuses loops. `Match` takes a glob or `re:` pattern (#766). A found group follows its providers: one switched off or removed leaves it, and one on again is back. A found group the user changed (an `auto-…` id stored) is read without the members of providers magpie no longer has (`withoutRemoved`, not written back, so a provider back under its id is back in it), except a manual group's pick, a rule's model, or all of them when none would be left. A switched-off provider's members stay in it, skipped by `membersIn`, and the Routing page says them as switched off (`memberJSON.providerOff`). The user's own groups keep their members. Three templates make a group in one click from the models the user has (`provider.Templates`, `AddTemplate`; the Routing page's cards before a first group and its Templates menu after, `magpie group template [kind] [name]`): `smart` sends a hard turn to the strongest model and an easy one or a compaction to a cheap one, asked by a classifier (the decision API when there is one, else the cheapest priced model that doesn't reason); `thrifty` starts on two cheap models of different providers and sends high reasoning to the strongest; `steady` fails over between the strongest model of up to three providers. A model is weighed by its maker's list price when known, else what its provider charges, else by its id's size words (`sizeOf`); one over `tooDear` (USD 100 a million output tokens) is never picked. A template that can't be made says what is missing (`Need`). It is saved under a name and id no group has (`freeGroupName`, shared with `CopyGroup`), never over one. A group is shared as text (`ShareGroup`, a group row's Copy to share): JSON marked `"magpie": "routing-group"` with a format `version` (`ShareVersion`), holding the group's members as it names them, patterns, routing, rules, classifier and settings. A group holds only `provider/model` ids, never a key, account or address, and the derived matches, found/hidden/off flags and the rules that hold by a folder (a path on the sharer's machine, `Rule.Folders`) stay behind; a pasted one is left out too. `ImportGroup` (the Routing page's Import, `POST /api/groups/import`) reads it with words or a code fence around it, refuses another text, a newer format or none (`ShareError`, said in the reader's language). A member whose provider the importer has is kept; else the same model (`AutoGroupOf`) under the first provider of theirs that serves it (`Instead`); else it is left out and named (`Missing`), with the rules that send to it, its place among the off and fast members, and a classifier gone takes the intent rules and auto effort with it. Nothing is added when no member is left; what is added gets a free name, never replacing a group. A group of patterns only that match nothing now (a plugin's models not listed) has no members: `/api/groups` says them, and an unmakeable template's, as `[]`, never `null`; the Routing page reads the response through `groupsFrom` and draws a group it still can't draw as one row saying so, so one bad group never hides the rest (#1585). | [`group.go`](../../internal/provider/group.go), [`grouptemplate.go`](../../internal/provider/grouptemplate.go), [`group_share.go`](../../internal/provider/group_share.go) |
| Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it. A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). Each key of a remote-magpie provider also gets a card of its own, under `<remote>/~keys`, one section per key (#1547, `remoteKeyCards` in `remote_key_limits.go`): the gateway key's limit as that magpie holds it, read from `GET /v1/magpie/limit` asked with that key alone, so a key never sees another's numbers. It shows a window per cap (tokens, spend) named for the period, used against the cap, with its reset, plus `GatewayKey` (what is left, calls, a cycle of days, used up); a key held to no limit shows `Unlimited`. It is kept for `remoteCardsFor` like the remote's cards and read again by the card's refresh (`?provider=<remote>/~keys&user=<key name>`). A read that fails keeps the last numbers, dated (`AsOf`); with none the card says why, never zero or no limit. A remote from before `/v1/magpie/limit` (404) says it is too old to tell (`errRemoteNoKeyLimit`). Cursor, Grok and a Kiro key keep the page's cards only. With Settings → Allowances → *Allowance reads* at *When I ask* (`QuotaReads == "asked"`, #1518: magpie started at login before the proxy app read by itself, direct), only a read the user asked for goes out: the Usage page or the tray panel's Allowances opened (no more than once in 30s, `quotasOpened`, #1588) or refreshed (`?asked=1`), a card's refresh (`RefreshUsage`), `magpie quota`, `magpie accounts`, `magpie quota wait` and the TUI's quotas (`Asked`). Any other read (`quotaReading` → `holdUnasked`) carries `netproxy.Hold`, so its requests fail before they leave, and every reader gives back what it last read, dated, or "not read yet" (`errNotAsked`): routing, the used-up switch, the menu bar and alerts go by that. An account refused for its quota (`StaleAllowance` → `markStaleRead`) or a key refused (`StaleKeyAllowance` → `refused`) is still read, once (`unheld`). Warm-up and check-in are not reads and are unchanged. | [`cards_kept.go`](../../internal/provider/cards_kept.go), [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go), [`remote_key_limits.go`](../../internal/provider/remote_key_limits.go), [`quota_asked.go`](../../internal/provider/quota_asked.go) |
@@ -92,7 +92,7 @@ before the preset had a decision base gets its chat base as one.
The CLI and TUI report model-list fetch errors for remote and other mixed providers
(such as OpenRouter, serving conversation and decision models). Only a
decision-only provider keeps the separate decision discovery behavior
(`announce` in [`providers_cli.go`](../../providers_cli.go), `addKeyAsk` in
(`announce` in [`providers_cli.go`](../../internal/cli/providers_cli.go), `addKeyAsk` in
[`pages.go`](../../internal/tui/pages.go)). A remote's endpoint test reuses
successful model discovery for its decision result, and reports none when
no decision model was discovered (`Test` in
@@ -1,4 +1,4 @@
package main
package cli
import (
"encoding/base64"
@@ -1,4 +1,4 @@
package main
package cli
import (
"testing"
@@ -1,4 +1,4 @@
package main
package cli
import (
"fmt"
@@ -1,4 +1,4 @@
package main
package cli
import (
"io"
@@ -1,4 +1,4 @@
package main
package cli
import (
"os"
@@ -1,4 +1,4 @@
package main
package cli
import (
"bytes"
@@ -1,4 +1,4 @@
package main
package cli
import (
"bufio"
@@ -1,4 +1,4 @@
package main
package cli
import (
"fmt"
@@ -1,4 +1,4 @@
package main
package cli
import (
"context"
@@ -1,4 +1,4 @@
package main
package cli
import (
"encoding/json"
@@ -1,4 +1,4 @@
package main
package cli
import (
"encoding/base64"
@@ -1,4 +1,4 @@
package main
package cli
import (
"context"
@@ -27,7 +27,7 @@ func TestAccountsOfAPlugin(t *testing.T) {
t.Cleanup(plugin.Settle)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
abs, _ := filepath.Abs("internal/plugin/testdata/fake/index.js")
abs, _ := filepath.Abs("../plugin/testdata/fake/index.js")
if _, err := plugin.Add(ctx, abs); err != nil {
t.Fatal(err)
}
@@ -1,4 +1,4 @@
package main
package cli
import (
"os"
@@ -1,4 +1,4 @@
package main
package cli
import (
"fmt"
+1 -1
View File
@@ -1,4 +1,4 @@
package main
package cli
import (
"bufio"
@@ -1,4 +1,4 @@
package main
package cli
import (
"os"
@@ -1,4 +1,4 @@
package main
package cli
import (
"context"
@@ -1,4 +1,4 @@
package main
package cli
import (
"crypto/sha256"
@@ -1,4 +1,4 @@
package main
package cli
import (
"os"
@@ -1,4 +1,4 @@
package main
package cli
import (
"cmp"
@@ -1,4 +1,4 @@
package main
package cli
import (
"bytes"
+1 -1
View File
@@ -1,4 +1,4 @@
package main
package cli
import (
"fmt"
@@ -1,4 +1,4 @@
package main
package cli
import (
"encoding/json"
@@ -1,4 +1,4 @@
package main
package cli
import (
"slices"
@@ -1,4 +1,4 @@
package main
package cli
import (
"strings"
@@ -1,4 +1,4 @@
package main
package cli
import (
"slices"
@@ -1,4 +1,4 @@
package main
package cli
import (
"slices"
@@ -1,4 +1,4 @@
package main
package cli
import (
"fmt"
@@ -1,4 +1,4 @@
package main
package cli
import (
"fmt"
@@ -1,4 +1,4 @@
package main
package cli
import (
"testing"
@@ -1,4 +1,4 @@
package main
package cli
import (
"fmt"
@@ -1,4 +1,4 @@
package main
package cli
import (
"strings"
@@ -1,4 +1,4 @@
package main
package cli
import (
"slices"
+1 -1
View File
@@ -1,6 +1,6 @@
//go:build nogui
package main
package cli
import "errors"
+1 -1
View File
@@ -1,6 +1,6 @@
//go:build !nogui
package main
package cli
import (
"github.com/yetone/magpie/internal/gui"
@@ -1,4 +1,4 @@
package main
package cli
import (
"bytes"
@@ -1,4 +1,4 @@
package main
package cli
import (
"net"
+1 -1
View File
@@ -1,4 +1,4 @@
package main
package cli
import (
"fmt"
@@ -1,4 +1,4 @@
package main
package cli
import (
"go/ast"
@@ -1,4 +1,4 @@
package main
package cli
import (
"errors"
@@ -1,4 +1,4 @@
package main
package cli
import (
"os"
+657
View File
@@ -0,0 +1,657 @@
// Package cli is magpie's command line: every command, and the app, tray
// and TUI it opens (the root's main.go only calls Main).
package cli
import (
"context"
"errors"
"fmt"
"os"
"slices"
"strings"
"time"
"github.com/charmbracelet/lipgloss"
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/claudebridge"
"github.com/yetone/magpie/internal/davsync"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/imagemcp"
"github.com/yetone/magpie/internal/netproxy"
"github.com/yetone/magpie/internal/proc"
"github.com/yetone/magpie/internal/profile"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/sessions"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/tui"
"github.com/yetone/magpie/internal/update"
)
// version is the root main package's, set at build time
// (-ldflags "-X main.version=…") and handed over by Main.
var version = "dev"
const usage = `magpie — one place to pick every agent's model
magpie open the app: a window plus a menu bar icon
magpie tray start in the menu bar only
magpie panel open the menu bar icon's quick panel, or close it
magpie autostart [on|off] open magpie (in the menu bar) when you log in, or say whether it does
magpie tui the same thing, in the terminal (serves the gateway while open when no magpie does)
magpie web [--addr host:port] [--lan] [--no-open] [--gateway]
the app's window in a browser, with the gateway (no desktop needed: WSL, a server over SSH)
a new key each run; MAGPIE_WEB_KEY (16+ letters, digits, - . _ ~) keeps one, signed in for 400 days
behind a reverse proxy, MAGPIE_WEB_URL=https://<the page there> prints the link through it
--gateway: gateway mode, no Agents, Sessions or Library (on by itself with no agents here; Settings › General turns it off)
magpie ls list detected agents and their settings
magpie <agent> show one agent
magpie <agent> <model> set an agent's model e.g. magpie claude deepseek/deepseek-chat
magpie <agent> <field> <value> set another field e.g. magpie codex effort high
magpie <agent> default take magpie out: the agent back on what it had before
magpie <agent> <field> default that field back to the agent's own default
magpie <command> --help what a command or an agent takes; -h or --help anywhere does nothing else
magpie save <name> snapshot every agent's settings as a profile
magpie use <name> apply a profile
magpie profiles list profiles
magpie rm <name> delete a profile
magpie backup [--no-keys] [--no-library] [file] providers, keys, settings, profiles, agent models and the library in one file, sealed with a passphrase
magpie restore [--no-agents] [--no-library] <file> put a backup in on this machine
magpie webdav [on <address>|set k=v…|now|off] the same, kept the same on every computer through a WebDAV folder (magpie webdav help)
magpie s3 [on s3://<bucket>[/<prefix>]|set k=v…|now|off] the same through an S3-compatible bucket: AWS, R2, B2, MinIO… (magpie s3 help)
magpie library [sync|instructions|mcp|skill] the instructions, MCP servers and skills written into every agent (magpie library help)
magpie providers list your providers: host, key, models, who uses them
magpie presets the vendors magpie knows: add one with just a key
magpie provider add <preset> <key> e.g. magpie provider add deepseek sk-…
magpie provider add <name> k=v… a custom vendor (magpie provider for the fields)
magpie provider key|models|test|rm <id>
magpie provider fallback <id> <provider/model>… use these when it's out of quota or down
magpie import [-y] <link> add the provider a magpie://import?… link describes
magpie models [<agent>] every model agents can pick, as provider/model; an agent's, and why others aren't
magpie model name <provider/model> <name>|--reset the name a model goes by, everywhere
magpie model efforts <provider/model> <l>,<l>|--reset the reasoning levels a model offers (magpie model help)
magpie visible [<agent> <family|provider|group>,… | all | --only-picked | --show-new]
which models an agent is shown: families (magpie provider/group set <id> family=…),
or only the models ticked for it, a new one off until it is ticked
magpie search [add <api> <key>|rm <api>] Tavily, Brave, Exa, Firecrawl, You.com or SearXNG for web search when no provider can search
magpie groups routing groups: several models agents pick as one, group/<id>
magpie group add <name> models=<m1>,<m2> [routing=smart|order|rotate|usage|pace] [stays=auto|session|turn|off]
magpie group <id> | set <id> k=v… | rm <id> show, change or remove one (magpie group help for more)
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)
magpie accounts checkin WorkBuddy's daily check-in (签到) for each WorkBuddy account, now (Settings can do it daily)
magpie accounts project <gemini|antigravity> <email> <project> the Google Cloud project a Google account's requests go to
magpie accounts alias <agent> <email> [<name>|--clear] a name of your own for an account, shown on its card, in the menu bar and in magpie quota
magpie claude-code [install [--yes]|remove] the Claude Code a Claude subscription runs; install downloads Anthropic's own build, checked against its manifest, for a server or container without one
magpie plugin [add <package>|rm|update|on|off|login <provider>|logout <provider>]
OpenCode provider plugins and pi packages: subscriptions signed in to, and served, through a plugin
magpie plugin move|migrate <subscription> run a built-in subscription's accounts on its community plugin
magpie plugin move-back|unmigrate <subscription> go back to the built-in, with its accounts
magpie serve run the gateway alone (the app runs it too)
magpie healthcheck exit 0 when the gateway answers (a container's HEALTHCHECK)
magpie gateway-key list|add <name>|rotate <id>|remove <id> manage the keys clients use to call a shared gateway
magpie gateway-key limit <id> [off|reset|day|week|month|<N>d --tokens N --cost USD --cache-reads] a key's own limit, and what it used
magpie gateway-key models <id> [all|<provider>/<model>|<provider>/* ...] the models a key may use, every one unless it names some
magpie mcp image the image and video generation MCP server an agent is given from the library (stdio)
magpie usage [today|7d|30d|all] tokens and cost per agent, model and subscription account (30d)
magpie usage --csv [--account <name>] [today|7d|30d|all] every request as CSV (or one account's): the model asked for, sent and served, tokens, cost, time, status, account
magpie sessions [--model <m>] [--folder <f>] [--json] the latest Claude Code, Codex, OpenCode and Pi sessions, with what each cost
magpie sessions --days N|today|all [--model <m>] [--folder <f>] [--json]
what every session spent, day by day, with the top models and folders (7 days)
magpie quota [<provider>] [--json] what is left of every subscription, plan and key balance
magpie quota wait <provider|account> [--timeout <d>] [--quiet]
block until that subscription (any of its accounts) or account has allowance again
magpie quota history [<provider|account>] [--days N] [--json]
each window's readings over time, kept 45 days
magpie sync refresh the model catalog and vendor model lists
magpie agents list every supported agent
magpie update [check] [--proxy <url>] [--mirror <prefix>]
install the newest release (check: only say if there is one); --proxy: an
http(s):// or socks5:// proxy for it; --mirror: a GitHub download mirror put
before the github.com URL (none unless given; still checked against usemagpie.ai's SHA-256)
magpie update mirror [<prefix>|off] the mirror every update, the app's own too, is downloaded through
magpie update auto [on|off] [30m|1h|6h|24h] whether the app looks for updates by itself, and how often (6h)
agents: claude (cc), codex, gemini, opencode (oc), mimocode, pi, goose, cursor, zed, copilot, crush, aside
`
var (
bold = lipgloss.NewStyle().Bold(true)
muted = lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "#8B8F98", Dark: "#7C8290"})
faint = lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "#C4C7CE", Dark: "#4A4F5A"})
green = lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "#0F9D58", Dark: "#7EE2A8"})
)
// Main runs magpie with os.Args, at the version the build was stamped with.
func Main(v string) {
version = v
// before anything reads or writes a file: no home, or a relative one,
// would put the agents' configs and magpie's keys under the working
// folder. What needs no file still answers (magpie version in a
// container or a script without HOME): run makes magpie's folders first.
ignored, err := appdir.CheckEnv()
if err != nil {
if len(os.Args) > 1 {
switch os.Args[1] {
case "-v", "--version", "version":
fmt.Println("magpie", version)
return
case "-h", "--help", "help":
fmt.Print(usage)
return
}
}
fmt.Fprintln(os.Stderr, "magpie:", err)
os.Exit(1)
}
slices.Sort(ignored)
for _, v := range ignored {
fmt.Fprintf(os.Stderr, "magpie: ignoring %s: not an absolute path (the programs magpie starts still get it)\n", v)
}
if provider.TookOpenedURL(os.Args[1:]) {
// Claude Code, signing in for magpie, handed over the page to open
return
}
endProbesOnSignal()
gateway.Version = version
netproxy.Install()
update.GUI = hasGUI
err = run(os.Args[1:])
proc.EndProbes() // a CLI still being asked something isn't left to init
sessions.Saved() // the session index kept, for the next run
if err != nil {
// a command with exit codes of its own (quota wait) says which
code := 1
var e exitError
if errors.As(err, &e) {
code = e.code
}
if msg := err.Error(); msg != "" {
fmt.Fprintln(os.Stderr, "magpie:", msg)
}
os.Exit(code)
}
}
// runTUI runs the TUI, which quits on Ctrl+C and SIGTERM itself once it
// has started; it asks CLIs first, and a signal then ends those.
func runTUI() error {
return tuiRun(ownSignals)
}
// tuiRun is tui.Run; a var so tests can stand in for it.
var tuiRun = tui.Run
func run(args []string) error {
// before anything is read, moved or started: --help on any command
// prints its usage and does nothing else
if helpAsked(args) {
fmt.Println(strings.TrimRight(helpFor(args), "\n"))
return nil
}
if len(args) > 0 && args[0] == "healthcheck" {
return healthcheck() // every few seconds in a container: nothing else
}
if len(args) == 2 && args[0] == agent.DryRunArg {
// an agent disconnected on a copy of its files under a temporary
// home, for the Agents page to show what disconnecting changes
// (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()
makeDirs()
settings.Migrate()
// the providers and settings read once for every agent's fields, which
// the moves below look at (a write among them reads them again)
release := provider.Hold()
agent.RenameLegacy()
agent.MoveCursorEfforts()
agent.MoveAntigravityEfforts()
agent.MoveOffAccountIDs()
release()
// a provider added, edited or removed, or a list fetched anew, reaches
// the model lists agents keep in files of their own
catalog.Changed = agent.SyncCatalog
// a model Claude Code names that magpie doesn't serve goes to the one
// it is set to use for that tier
gateway.StandIn = agent.StandIn
// a Codex that reaches magpie for account failover alone is handed
// only its own models (#1385)
gateway.CodexOwnOnly = agent.CodexOwnOnly
// the setup kept the same on every computer, by whichever serves
gateway.WhileServing = append(gateway.WhileServing, davsync.Run)
// and dsh's patch lists, which dsh reads live: a route left behind by
// something else writing the file fails every session there until
// magpie writes its own list again
gateway.WhileServing = append(gateway.WhileServing, agent.KeepDshWired)
// and Cursor Private Inference's variables, which the Mac's launchd
// forgets at a restart, for the gateway's address now
gateway.WhileServing = append(gateway.WhileServing, agent.KeepCursorLocalEnv)
// and the request archive, when it is on, goes to the bucket sync is to
gateway.ArchiveBucket = func() (gateway.Putter, bool) {
if b, ok := davsync.S3Bucket(); ok {
return b, true
}
return nil, false
}
if len(args) == 0 {
if hasGUI {
return runGUI(true, "")
}
return runTUI()
}
// a magpie:// link the system handed over (Windows, Linux): the app
// opens it for the user to confirm
if strings.HasPrefix(strings.ToLower(args[0]), "magpie:") {
if !hasGUI {
return importCmd(args)
}
return runGUI(false, args[0])
}
switch args[0] {
case "tui":
return runTUI()
case "web":
return webCmd(args[1:])
case "app", "gui":
// `magpie gui settings`: the window on that tab, as a restart to
// update from it comes back (update.RelaunchArgs)
if len(args) > 1 {
return runWindow(args[1])
}
return runGUI(true, "")
case "tray":
return runGUI(false, "")
case "-Embedding":
// Windows starting magpie for a click on one of its notifications
// (a usage alert, #368) left in the Action Center after it quit:
// the window, on the Usage page
return runWindow("usage")
case "panel":
return runPanel()
case "autostart":
return autostartCmd(args[1:])
case "-h", "--help", "help":
fmt.Print(usage)
return nil
case "-v", "--version", "version":
fmt.Println("magpie", version)
return nil
case "ls", "list":
// in the order the app lists them; those hidden there come last, dimmed
shown, hidden := settings.Arrange(settings.Load(), agent.Detected(), func(a *agent.Agent) string { return a.ID })
return list(append(shown, hidden...), true, len(shown))
case "agents":
return list(agent.All(), false, -1)
case "sync":
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := catalog.Sync(ctx); err != nil {
return err
}
fmt.Println(green.Render("✓"), "catalog saved to", catalog.CachePath())
refreshLive(ctx)
return nil
case "save", "use", "rm", "profiles":
return profiles(args)
case "import":
return importCmd(args[1:])
case "providers":
return providers()
case "presets":
return presets()
case "provider":
return providerCmd(args)
case "models":
return models(args[1:])
case "model":
return modelCmd(args[1:])
case "visible":
return visibleCmd(args[1:])
case "search":
return searchCmd(args[1:])
case "groups":
return groups()
case "group":
return groupCmd(args)
case "serve":
return serve()
case "gateway-key":
return gatewayKeys(args)
case "accounts", "account":
return accountsCmd(args)
case "usage":
return usageCmd(args)
case "sessions":
return sessionsCmd(args)
case "quota", "quotas":
return quotaCmd(args)
case "update":
return updateCmd(args)
case "library", "lib":
return libraryCmd(args)
case "backup":
return backupCmd(args[1:])
case "restore":
return restoreCmd(args[1:])
case "webdav", "dav":
return webdavCmd(args[1:])
case "plugin", "plugins":
return pluginCmd(args)
case "s3":
return s3Cmd(args[1:])
case "mcp":
return imagemcp.Run(args[1:])
case "claude-code":
return claudeCodeCmd(args[1:])
case "claude-mcp-helper": // internal: stdio MCP subprocess spawned by Claude Code
return claudebridge.RunMCP(args[1:])
}
a, err := agent.Find(args[0])
if err != nil {
return err
}
// no agent form takes a flag: one is never set as a model or a value
// (`magpie snow --verbose` would take magpie out of Snow, #1457)
if f := flagArg(args[1:]); f != "" {
return fmt.Errorf("unknown flag %s: nothing was changed\n\n%s", f, strings.TrimRight(agentHelp(a), "\n"))
}
if len(a.Fields) == 0 && a.Import != nil {
// `magpie cindy`: it takes magpie through its own link, confirmed there
if len(args) > 1 {
link := a.Import()
openInBrowser(link)
fmt.Println(green.Render("✓"), bold.Render(a.Name), muted.Render("opened to add magpie — confirm it there"))
fmt.Println(muted.Render(" " + link))
return nil
}
}
switch len(args) {
case 1:
return list([]*agent.Agent{a}, true, -1)
case 2:
if args[1] == "default" {
if a.Wired() {
return disconnect(a)
}
return set(a, a.Fields[0].Key, "")
}
// `magpie codex xhigh`: a bare value that belongs to a non-model field
// (effort levels, for instance) is routed there; anything else is a model.
if f := fieldForValue(a, args[1]); f != nil {
return set(a, f.Key, args[1])
}
return set(a, a.Fields[0].Key, args[1])
case 3:
if args[2] == "default" {
args[2] = ""
}
return set(a, args[1], args[2])
}
return fmt.Errorf("too many arguments\n\n%s", usage)
}
func set(a *agent.Agent, key, value string) error {
f := a.Field(key)
if f == nil {
var keys []string
for _, f := range a.Fields {
keys = append(keys, f.Key)
}
return fmt.Errorf("%s has no field %q (fields: %s)", a.Name, key, strings.Join(keys, ", "))
}
value, err := a.Spell(f.Key, value)
if err != nil {
return err
}
before := f.Get()
if err := a.Apply(f.Key, value); err != nil {
return err
}
// what the config reads now, not what was asked: an agent may name the
// model under a provider of its own (OpenCode's magpie-relay/…), and a
// value it had already is said to be so
now := f.Get()
shown := now
if value == "" || now == "" {
shown = muted.Render("default")
}
if now == before {
shown += " " + muted.Render("(unchanged)")
}
fmt.Println(green.Render("✓"), bold.Render(a.Name), muted.Render(f.Label), shown)
if a.Notice != nil {
if n := a.Notice(); n != "" {
fmt.Println(muted.Render(" ↻ " + n))
}
}
return nil
}
// disconnect is `magpie <agent> default` on an agent magpie is wired into:
// the Agents page's Disconnect, which puts back what the user had before
// magpie — Claude Code's own model, its endpoint — where a field's default
// leaves the agent as installed (__jingling on X: magpie claude default
// took the model they had set away with magpie's)
func disconnect(a *agent.Agent) error {
before := a.Values()
if err := a.Disconnect(); err != nil {
return err
}
now := a.Values()
for _, f := range a.Fields {
if before[f.Key] == now[f.Key] {
continue
}
shown := now[f.Key]
if shown == "" {
shown = muted.Render("default")
}
fmt.Println(green.Render("✓"), bold.Render(a.Name), muted.Render(f.Label), shown)
}
fmt.Println(muted.Render(" disconnected from magpie, back to what it had before"))
if a.Notice != nil {
if n := a.Notice(); n != "" {
fmt.Println(muted.Render(" ↻ " + n))
}
}
return nil
}
func fieldForValue(a *agent.Agent, v string) *agent.Field {
vals := a.Values()
// the agent's suffix after a model (omp's ":max") aside: a role on the
// same model at that level offers it as typed, and would take it. A list
// of models no picker offers: it is for the model
if a.SplitSuffix != nil {
m, _, one := a.SplitSuffix(v)
if !one {
return nil
}
v = m
}
// a model stays with the model, even where other fields offer it too
// (Claude Code's opus/sonnet/haiku/fable)
for _, o := range a.Fields[0].Options(vals) {
if o.Value == v {
return nil
}
}
for i := 1; i < len(a.Fields); i++ {
for _, o := range a.Fields[i].Options(vals) {
if o.Value == v {
return &a.Fields[i]
}
}
}
return nil
}
// list prints the agents; those from dimFrom on (when not -1) are the ones
// hidden in the app, and are dimmed.
func list(agents []*agent.Agent, detectedOnly bool, dimFrom int) error {
if len(agents) == 0 {
return fmt.Errorf("no supported agents found on this machine")
}
type row struct{ name, vals, path string }
var rows []row
nameW, valW := 0, 0
for i, a := range agents {
r := row{name: a.Name, path: tilde(a.Path)}
if !detectedOnly && !a.Detected() {
r.name = faint.Render(a.Name)
r.vals = faint.Render("not detected")
r.path = ""
} else {
vals := a.Values()
dim := dimFrom >= 0 && i >= dimFrom
label, value := muted, lipgloss.NewStyle()
if dim {
label, value = faint, faint
}
var parts []string
for _, f := range a.Fields {
v := vals[f.Key]
if v == "" && f.Quiet {
continue
}
if v == "" {
v = faint.Render("—")
} else {
v = value.Render(v)
}
if f.Label == "model" {
parts = append(parts, v)
} else {
parts = append(parts, label.Render(f.Label)+" "+v)
}
}
r.name = bold.Render(a.Name)
if dim {
r.name = faint.Render(a.Name) + " " + faint.Render("hidden")
}
r.vals = strings.Join(parts, label.Render(" · "))
// through magpie for account failover while not connected (#1385)
if said := a.FailoverSaid(); said != "" {
r.vals += label.Render(" · " + said)
}
if a.Import != nil {
if a.Added != nil && a.Added() {
r.vals = value.Render("magpie added")
} else {
r.vals = label.Render("magpie "+a.ID+" add") + faint.Render(" to add magpie")
}
}
}
nameW = max(nameW, lipgloss.Width(r.name))
valW = max(valW, lipgloss.Width(r.vals))
rows = append(rows, r)
}
for _, r := range rows {
fmt.Printf(" %s %s %s\n", pad(r.name, nameW), pad(r.vals, valW), faint.Render(r.path))
}
return nil
}
func tilde(p string) string {
if home, err := os.UserHomeDir(); err == nil && strings.HasPrefix(p, home) {
return "~" + p[len(home):]
}
return p
}
func profiles(args []string) error {
switch args[0] {
case "profiles":
ps, err := profile.Load()
if err != nil {
return err
}
if len(ps) == 0 {
fmt.Println(muted.Render("no profiles yet · magpie save <name>"))
return nil
}
detected := agent.Detected()
for _, n := range profile.Names(ps) {
// ✓ the one the setup is now (superhtoooth on X)
mark := " "
if profile.InUse(ps[n], detected, nil) {
mark = green.Render("✓")
}
fmt.Printf("%s %s %s\n", mark, bold.Render(n), muted.Render(profile.LongSummary(ps[n])))
}
return nil
case "save":
if len(args) < 2 {
return fmt.Errorf("usage: magpie save <name>")
}
p, err := profile.Snapshot()
if err != nil {
return err
}
if err := profile.Save(args[1], p); err != nil {
return err
}
fmt.Println(green.Render("✓"), "saved profile", bold.Render(args[1]))
if p.Library != nil {
fmt.Println(" ", muted.Render("with the "+p.Library.Summary()))
}
return nil
case "use":
if len(args) < 2 {
return fmt.Errorf("usage: magpie use <name>")
}
ps, err := profile.Load()
if err != nil {
return err
}
p, ok := ps[args[1]]
if !ok {
return fmt.Errorf("no profile named %q", args[1])
}
a, err := profile.Apply(p)
if err != nil {
return err
}
fmt.Println(green.Render("✓"), "applied", bold.Render(args[1]), muted.Render(fmt.Sprintf("(%d changed)", a.Changed)))
for _, line := range profile.Report(a) {
fmt.Println(" ", muted.Render(line))
}
return nil
case "rm":
if len(args) < 2 {
return fmt.Errorf("usage: magpie rm <name>")
}
if err := profile.Delete(args[1]); err != nil {
return err
}
fmt.Println(green.Render("✓"), "deleted profile", bold.Render(args[1]))
return nil
}
return nil
}
func pad(s string, w int) string {
if n := w - lipgloss.Width(s); n > 0 {
return s + strings.Repeat(" ", n)
}
return s
}
+1 -1
View File
@@ -1,4 +1,4 @@
package main
package cli
import (
"testing"
+1 -1
View File
@@ -1,4 +1,4 @@
package main
package cli
import (
"fmt"
@@ -1,4 +1,4 @@
package main
package cli
import (
"io"
@@ -1,4 +1,4 @@
package main
package cli
import (
"testing"
@@ -1,4 +1,4 @@
package main
package cli
import (
"strings"
@@ -1,4 +1,4 @@
package main
package cli
import (
"testing"
@@ -1,4 +1,4 @@
package main
package cli
import (
"os"
@@ -1,4 +1,4 @@
package main
package cli
import (
"context"
@@ -21,7 +21,7 @@ func TestPluginListSaysClash(t *testing.T) {
t.Setenv("MAGPIE_PLUGIN_MARKET", "off")
t.Setenv("NO_COLOR", "1")
t.Cleanup(plugin.Settle)
src, err := os.ReadFile("internal/plugin/testdata/fake/index.js")
src, err := os.ReadFile("../plugin/testdata/fake/index.js")
if err != nil {
t.Fatal(err)
}
@@ -1,4 +1,4 @@
package main
package cli
import (
"strings"
@@ -1,4 +1,4 @@
package main
package cli
import (
"context"
@@ -112,7 +112,7 @@ func fakeCoHome(t *testing.T) context.Context {
t.Cleanup(plugin.Settle)
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
t.Cleanup(cancel)
abs, _ := filepath.Abs("internal/plugin/testdata/fake/index.js")
abs, _ := filepath.Abs("../plugin/testdata/fake/index.js")
if _, err := plugin.Add(ctx, abs); err != nil {
t.Fatal(err)
}
@@ -1,4 +1,4 @@
package main
package cli
import (
"context"
@@ -1,4 +1,4 @@
package main
package cli
import (
"context"
@@ -1,4 +1,4 @@
package main
package cli
import (
"os"
@@ -1,4 +1,4 @@
package main
package cli
import (
"os"
@@ -1,4 +1,4 @@
package main
package cli
import (
"encoding/json"
@@ -1,4 +1,4 @@
package main
package cli
import (
"cmp"
@@ -1,4 +1,4 @@
package main
package cli
import (
"io"
@@ -1,4 +1,4 @@
package main
package cli
import (
"bytes"
@@ -1,4 +1,4 @@
package main
package cli
import (
"io"
+1 -1
View File
@@ -1,4 +1,4 @@
package main
package cli
import (
"cmp"
@@ -1,4 +1,4 @@
package main
package cli
import (
"encoding/json"
@@ -1,4 +1,4 @@
package main
package cli
import (
"encoding/json"
+1 -1
View File
@@ -1,4 +1,4 @@
package main
package cli
import (
"cmp"
@@ -1,4 +1,4 @@
package main
package cli
import (
"context"
@@ -1,4 +1,4 @@
package main
package cli
import (
"os"
@@ -1,4 +1,4 @@
package main
package cli
import (
"crypto/md5"
+1 -1
View File
@@ -1,4 +1,4 @@
package main
package cli
import (
"fmt"
@@ -1,4 +1,4 @@
package main
package cli
import (
"os"
@@ -1,4 +1,4 @@
package main
package cli
import (
"os"
@@ -1,4 +1,4 @@
package main
package cli
import (
"encoding/json"
@@ -1,4 +1,4 @@
package main
package cli
import (
"bytes"
@@ -36,7 +36,7 @@ func sessionsHome(t *testing.T) time.Time {
for from, env := range map[string]string{"claude": "CLAUDE_CONFIG_DIR", "codex": "CODEX_HOME"} {
dir := filepath.Join(h, "."+from)
if err := os.CopyFS(dir, os.DirFS(filepath.Join("internal", "sessions", "testdata", from))); err != nil {
if err := os.CopyFS(dir, os.DirFS(filepath.Join("..", "sessions", "testdata", from))); err != nil {
t.Fatal(err)
}
t.Setenv(env, dir)
+1 -1
View File
@@ -1,4 +1,4 @@
package main
package cli
import (
"context"
@@ -1,6 +1,6 @@
//go:build !windows
package main
package cli
import (
"context"
@@ -1,6 +1,6 @@
//go:build !windows
package main
package cli
import (
"os"
@@ -1,4 +1,4 @@
package main
package cli
import "os"
@@ -1,4 +1,4 @@
package main
package cli
import (
"os"
@@ -1,4 +1,4 @@
package main
package cli
import (
"bytes"
+1 -1
View File
@@ -1,4 +1,4 @@
package main
package cli
import (
"context"
@@ -1,4 +1,4 @@
package main
package cli
import (
"encoding/json"
@@ -1,4 +1,4 @@
package main
package cli
import (
"slices"
+1 -1
View File
@@ -1,4 +1,4 @@
package main
package cli
import (
"context"
@@ -1,4 +1,4 @@
package main
package cli
import (
"encoding/csv"
@@ -1,4 +1,4 @@
package main
package cli
import (
"fmt"
+1 -1
View File
@@ -1,4 +1,4 @@
package main
package cli
import (
"fmt"
@@ -1,4 +1,4 @@
package main
package cli
import "testing"
+1 -1
View File
@@ -1,4 +1,4 @@
package main
package cli
import (
"context"
@@ -1,4 +1,4 @@
package main
package cli
import (
"bufio"
+6 -647
View File
@@ -1,652 +1,11 @@
// magpie — one place to pick every agent's model.
// magpie — one place to pick every agent's model. The commands live in
// internal/cli; this is only where the binary starts.
package main
import (
"context"
"errors"
"fmt"
"os"
"slices"
"strings"
"time"
"github.com/charmbracelet/lipgloss"
"github.com/yetone/magpie/internal/agent"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/claudebridge"
"github.com/yetone/magpie/internal/davsync"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/imagemcp"
"github.com/yetone/magpie/internal/netproxy"
"github.com/yetone/magpie/internal/proc"
"github.com/yetone/magpie/internal/profile"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/sessions"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/tui"
"github.com/yetone/magpie/internal/update"
)
import "github.com/yetone/magpie/internal/cli"
// version is set at build time: -ldflags "-X main.version=…" (Makefile,
// Dockerfile, magpie-releases), so it stays in package main.
var version = "dev"
const usage = `magpie — one place to pick every agent's model
magpie open the app: a window plus a menu bar icon
magpie tray start in the menu bar only
magpie panel open the menu bar icon's quick panel, or close it
magpie autostart [on|off] open magpie (in the menu bar) when you log in, or say whether it does
magpie tui the same thing, in the terminal (serves the gateway while open when no magpie does)
magpie web [--addr host:port] [--lan] [--no-open] [--gateway]
the app's window in a browser, with the gateway (no desktop needed: WSL, a server over SSH)
a new key each run; MAGPIE_WEB_KEY (16+ letters, digits, - . _ ~) keeps one, signed in for 400 days
behind a reverse proxy, MAGPIE_WEB_URL=https://<the page there> prints the link through it
--gateway: gateway mode, no Agents, Sessions or Library (on by itself with no agents here; Settings › General turns it off)
magpie ls list detected agents and their settings
magpie <agent> show one agent
magpie <agent> <model> set an agent's model e.g. magpie claude deepseek/deepseek-chat
magpie <agent> <field> <value> set another field e.g. magpie codex effort high
magpie <agent> default take magpie out: the agent back on what it had before
magpie <agent> <field> default that field back to the agent's own default
magpie <command> --help what a command or an agent takes; -h or --help anywhere does nothing else
magpie save <name> snapshot every agent's settings as a profile
magpie use <name> apply a profile
magpie profiles list profiles
magpie rm <name> delete a profile
magpie backup [--no-keys] [--no-library] [file] providers, keys, settings, profiles, agent models and the library in one file, sealed with a passphrase
magpie restore [--no-agents] [--no-library] <file> put a backup in on this machine
magpie webdav [on <address>|set k=v…|now|off] the same, kept the same on every computer through a WebDAV folder (magpie webdav help)
magpie s3 [on s3://<bucket>[/<prefix>]|set k=v…|now|off] the same through an S3-compatible bucket: AWS, R2, B2, MinIO… (magpie s3 help)
magpie library [sync|instructions|mcp|skill] the instructions, MCP servers and skills written into every agent (magpie library help)
magpie providers list your providers: host, key, models, who uses them
magpie presets the vendors magpie knows: add one with just a key
magpie provider add <preset> <key> e.g. magpie provider add deepseek sk-…
magpie provider add <name> k=v… a custom vendor (magpie provider for the fields)
magpie provider key|models|test|rm <id>
magpie provider fallback <id> <provider/model>… use these when it's out of quota or down
magpie import [-y] <link> add the provider a magpie://import?… link describes
magpie models [<agent>] every model agents can pick, as provider/model; an agent's, and why others aren't
magpie model name <provider/model> <name>|--reset the name a model goes by, everywhere
magpie model efforts <provider/model> <l>,<l>|--reset the reasoning levels a model offers (magpie model help)
magpie visible [<agent> <family|provider|group>,… | all | --only-picked | --show-new]
which models an agent is shown: families (magpie provider/group set <id> family=…),
or only the models ticked for it, a new one off until it is ticked
magpie search [add <api> <key>|rm <api>] Tavily, Brave, Exa, Firecrawl, You.com or SearXNG for web search when no provider can search
magpie groups routing groups: several models agents pick as one, group/<id>
magpie group add <name> models=<m1>,<m2> [routing=smart|order|rotate|usage|pace] [stays=auto|session|turn|off]
magpie group <id> | set <id> k=v… | rm <id> show, change or remove one (magpie group help for more)
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)
magpie accounts checkin WorkBuddy's daily check-in (签到) for each WorkBuddy account, now (Settings can do it daily)
magpie accounts project <gemini|antigravity> <email> <project> the Google Cloud project a Google account's requests go to
magpie accounts alias <agent> <email> [<name>|--clear] a name of your own for an account, shown on its card, in the menu bar and in magpie quota
magpie claude-code [install [--yes]|remove] the Claude Code a Claude subscription runs; install downloads Anthropic's own build, checked against its manifest, for a server or container without one
magpie plugin [add <package>|rm|update|on|off|login <provider>|logout <provider>]
OpenCode provider plugins and pi packages: subscriptions signed in to, and served, through a plugin
magpie plugin move|migrate <subscription> run a built-in subscription's accounts on its community plugin
magpie plugin move-back|unmigrate <subscription> go back to the built-in, with its accounts
magpie serve run the gateway alone (the app runs it too)
magpie healthcheck exit 0 when the gateway answers (a container's HEALTHCHECK)
magpie gateway-key list|add <name>|rotate <id>|remove <id> manage the keys clients use to call a shared gateway
magpie gateway-key limit <id> [off|reset|day|week|month|<N>d --tokens N --cost USD --cache-reads] a key's own limit, and what it used
magpie gateway-key models <id> [all|<provider>/<model>|<provider>/* ...] the models a key may use, every one unless it names some
magpie mcp image the image and video generation MCP server an agent is given from the library (stdio)
magpie usage [today|7d|30d|all] tokens and cost per agent, model and subscription account (30d)
magpie usage --csv [--account <name>] [today|7d|30d|all] every request as CSV (or one account's): the model asked for, sent and served, tokens, cost, time, status, account
magpie sessions [--model <m>] [--folder <f>] [--json] the latest Claude Code, Codex, OpenCode and Pi sessions, with what each cost
magpie sessions --days N|today|all [--model <m>] [--folder <f>] [--json]
what every session spent, day by day, with the top models and folders (7 days)
magpie quota [<provider>] [--json] what is left of every subscription, plan and key balance
magpie quota wait <provider|account> [--timeout <d>] [--quiet]
block until that subscription (any of its accounts) or account has allowance again
magpie quota history [<provider|account>] [--days N] [--json]
each window's readings over time, kept 45 days
magpie sync refresh the model catalog and vendor model lists
magpie agents list every supported agent
magpie update [check] [--proxy <url>] [--mirror <prefix>]
install the newest release (check: only say if there is one); --proxy: an
http(s):// or socks5:// proxy for it; --mirror: a GitHub download mirror put
before the github.com URL (none unless given; still checked against usemagpie.ai's SHA-256)
magpie update mirror [<prefix>|off] the mirror every update, the app's own too, is downloaded through
magpie update auto [on|off] [30m|1h|6h|24h] whether the app looks for updates by itself, and how often (6h)
agents: claude (cc), codex, gemini, opencode (oc), mimocode, pi, goose, cursor, zed, copilot, crush, aside
`
var (
bold = lipgloss.NewStyle().Bold(true)
muted = lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "#8B8F98", Dark: "#7C8290"})
faint = lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "#C4C7CE", Dark: "#4A4F5A"})
green = lipgloss.NewStyle().Foreground(lipgloss.AdaptiveColor{Light: "#0F9D58", Dark: "#7EE2A8"})
)
func main() {
// before anything reads or writes a file: no home, or a relative one,
// would put the agents' configs and magpie's keys under the working
// folder. What needs no file still answers (magpie version in a
// container or a script without HOME): run makes magpie's folders first.
ignored, err := appdir.CheckEnv()
if err != nil {
if len(os.Args) > 1 {
switch os.Args[1] {
case "-v", "--version", "version":
fmt.Println("magpie", version)
return
case "-h", "--help", "help":
fmt.Print(usage)
return
}
}
fmt.Fprintln(os.Stderr, "magpie:", err)
os.Exit(1)
}
slices.Sort(ignored)
for _, v := range ignored {
fmt.Fprintf(os.Stderr, "magpie: ignoring %s: not an absolute path (the programs magpie starts still get it)\n", v)
}
if provider.TookOpenedURL(os.Args[1:]) {
// Claude Code, signing in for magpie, handed over the page to open
return
}
endProbesOnSignal()
gateway.Version = version
netproxy.Install()
update.GUI = hasGUI
err = run(os.Args[1:])
proc.EndProbes() // a CLI still being asked something isn't left to init
sessions.Saved() // the session index kept, for the next run
if err != nil {
// a command with exit codes of its own (quota wait) says which
code := 1
var e exitError
if errors.As(err, &e) {
code = e.code
}
if msg := err.Error(); msg != "" {
fmt.Fprintln(os.Stderr, "magpie:", msg)
}
os.Exit(code)
}
}
// runTUI runs the TUI, which quits on Ctrl+C and SIGTERM itself once it
// has started; it asks CLIs first, and a signal then ends those.
func runTUI() error {
return tuiRun(ownSignals)
}
// tuiRun is tui.Run; a var so tests can stand in for it.
var tuiRun = tui.Run
func run(args []string) error {
// before anything is read, moved or started: --help on any command
// prints its usage and does nothing else
if helpAsked(args) {
fmt.Println(strings.TrimRight(helpFor(args), "\n"))
return nil
}
if len(args) > 0 && args[0] == "healthcheck" {
return healthcheck() // every few seconds in a container: nothing else
}
if len(args) == 2 && args[0] == agent.DryRunArg {
// an agent disconnected on a copy of its files under a temporary
// home, for the Agents page to show what disconnecting changes
// (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()
makeDirs()
settings.Migrate()
// the providers and settings read once for every agent's fields, which
// the moves below look at (a write among them reads them again)
release := provider.Hold()
agent.RenameLegacy()
agent.MoveCursorEfforts()
agent.MoveAntigravityEfforts()
agent.MoveOffAccountIDs()
release()
// a provider added, edited or removed, or a list fetched anew, reaches
// the model lists agents keep in files of their own
catalog.Changed = agent.SyncCatalog
// a model Claude Code names that magpie doesn't serve goes to the one
// it is set to use for that tier
gateway.StandIn = agent.StandIn
// a Codex that reaches magpie for account failover alone is handed
// only its own models (#1385)
gateway.CodexOwnOnly = agent.CodexOwnOnly
// the setup kept the same on every computer, by whichever serves
gateway.WhileServing = append(gateway.WhileServing, davsync.Run)
// and dsh's patch lists, which dsh reads live: a route left behind by
// something else writing the file fails every session there until
// magpie writes its own list again
gateway.WhileServing = append(gateway.WhileServing, agent.KeepDshWired)
// and Cursor Private Inference's variables, which the Mac's launchd
// forgets at a restart, for the gateway's address now
gateway.WhileServing = append(gateway.WhileServing, agent.KeepCursorLocalEnv)
// and the request archive, when it is on, goes to the bucket sync is to
gateway.ArchiveBucket = func() (gateway.Putter, bool) {
if b, ok := davsync.S3Bucket(); ok {
return b, true
}
return nil, false
}
if len(args) == 0 {
if hasGUI {
return runGUI(true, "")
}
return runTUI()
}
// a magpie:// link the system handed over (Windows, Linux): the app
// opens it for the user to confirm
if strings.HasPrefix(strings.ToLower(args[0]), "magpie:") {
if !hasGUI {
return importCmd(args)
}
return runGUI(false, args[0])
}
switch args[0] {
case "tui":
return runTUI()
case "web":
return webCmd(args[1:])
case "app", "gui":
// `magpie gui settings`: the window on that tab, as a restart to
// update from it comes back (update.RelaunchArgs)
if len(args) > 1 {
return runWindow(args[1])
}
return runGUI(true, "")
case "tray":
return runGUI(false, "")
case "-Embedding":
// Windows starting magpie for a click on one of its notifications
// (a usage alert, #368) left in the Action Center after it quit:
// the window, on the Usage page
return runWindow("usage")
case "panel":
return runPanel()
case "autostart":
return autostartCmd(args[1:])
case "-h", "--help", "help":
fmt.Print(usage)
return nil
case "-v", "--version", "version":
fmt.Println("magpie", version)
return nil
case "ls", "list":
// in the order the app lists them; those hidden there come last, dimmed
shown, hidden := settings.Arrange(settings.Load(), agent.Detected(), func(a *agent.Agent) string { return a.ID })
return list(append(shown, hidden...), true, len(shown))
case "agents":
return list(agent.All(), false, -1)
case "sync":
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := catalog.Sync(ctx); err != nil {
return err
}
fmt.Println(green.Render("✓"), "catalog saved to", catalog.CachePath())
refreshLive(ctx)
return nil
case "save", "use", "rm", "profiles":
return profiles(args)
case "import":
return importCmd(args[1:])
case "providers":
return providers()
case "presets":
return presets()
case "provider":
return providerCmd(args)
case "models":
return models(args[1:])
case "model":
return modelCmd(args[1:])
case "visible":
return visibleCmd(args[1:])
case "search":
return searchCmd(args[1:])
case "groups":
return groups()
case "group":
return groupCmd(args)
case "serve":
return serve()
case "gateway-key":
return gatewayKeys(args)
case "accounts", "account":
return accountsCmd(args)
case "usage":
return usageCmd(args)
case "sessions":
return sessionsCmd(args)
case "quota", "quotas":
return quotaCmd(args)
case "update":
return updateCmd(args)
case "library", "lib":
return libraryCmd(args)
case "backup":
return backupCmd(args[1:])
case "restore":
return restoreCmd(args[1:])
case "webdav", "dav":
return webdavCmd(args[1:])
case "plugin", "plugins":
return pluginCmd(args)
case "s3":
return s3Cmd(args[1:])
case "mcp":
return imagemcp.Run(args[1:])
case "claude-code":
return claudeCodeCmd(args[1:])
case "claude-mcp-helper": // internal: stdio MCP subprocess spawned by Claude Code
return claudebridge.RunMCP(args[1:])
}
a, err := agent.Find(args[0])
if err != nil {
return err
}
// no agent form takes a flag: one is never set as a model or a value
// (`magpie snow --verbose` would take magpie out of Snow, #1457)
if f := flagArg(args[1:]); f != "" {
return fmt.Errorf("unknown flag %s: nothing was changed\n\n%s", f, strings.TrimRight(agentHelp(a), "\n"))
}
if len(a.Fields) == 0 && a.Import != nil {
// `magpie cindy`: it takes magpie through its own link, confirmed there
if len(args) > 1 {
link := a.Import()
openInBrowser(link)
fmt.Println(green.Render("✓"), bold.Render(a.Name), muted.Render("opened to add magpie — confirm it there"))
fmt.Println(muted.Render(" " + link))
return nil
}
}
switch len(args) {
case 1:
return list([]*agent.Agent{a}, true, -1)
case 2:
if args[1] == "default" {
if a.Wired() {
return disconnect(a)
}
return set(a, a.Fields[0].Key, "")
}
// `magpie codex xhigh`: a bare value that belongs to a non-model field
// (effort levels, for instance) is routed there; anything else is a model.
if f := fieldForValue(a, args[1]); f != nil {
return set(a, f.Key, args[1])
}
return set(a, a.Fields[0].Key, args[1])
case 3:
if args[2] == "default" {
args[2] = ""
}
return set(a, args[1], args[2])
}
return fmt.Errorf("too many arguments\n\n%s", usage)
}
func set(a *agent.Agent, key, value string) error {
f := a.Field(key)
if f == nil {
var keys []string
for _, f := range a.Fields {
keys = append(keys, f.Key)
}
return fmt.Errorf("%s has no field %q (fields: %s)", a.Name, key, strings.Join(keys, ", "))
}
value, err := a.Spell(f.Key, value)
if err != nil {
return err
}
before := f.Get()
if err := a.Apply(f.Key, value); err != nil {
return err
}
// what the config reads now, not what was asked: an agent may name the
// model under a provider of its own (OpenCode's magpie-relay/…), and a
// value it had already is said to be so
now := f.Get()
shown := now
if value == "" || now == "" {
shown = muted.Render("default")
}
if now == before {
shown += " " + muted.Render("(unchanged)")
}
fmt.Println(green.Render("✓"), bold.Render(a.Name), muted.Render(f.Label), shown)
if a.Notice != nil {
if n := a.Notice(); n != "" {
fmt.Println(muted.Render(" ↻ " + n))
}
}
return nil
}
// disconnect is `magpie <agent> default` on an agent magpie is wired into:
// the Agents page's Disconnect, which puts back what the user had before
// magpie — Claude Code's own model, its endpoint — where a field's default
// leaves the agent as installed (__jingling on X: magpie claude default
// took the model they had set away with magpie's)
func disconnect(a *agent.Agent) error {
before := a.Values()
if err := a.Disconnect(); err != nil {
return err
}
now := a.Values()
for _, f := range a.Fields {
if before[f.Key] == now[f.Key] {
continue
}
shown := now[f.Key]
if shown == "" {
shown = muted.Render("default")
}
fmt.Println(green.Render("✓"), bold.Render(a.Name), muted.Render(f.Label), shown)
}
fmt.Println(muted.Render(" disconnected from magpie, back to what it had before"))
if a.Notice != nil {
if n := a.Notice(); n != "" {
fmt.Println(muted.Render(" ↻ " + n))
}
}
return nil
}
func fieldForValue(a *agent.Agent, v string) *agent.Field {
vals := a.Values()
// the agent's suffix after a model (omp's ":max") aside: a role on the
// same model at that level offers it as typed, and would take it. A list
// of models no picker offers: it is for the model
if a.SplitSuffix != nil {
m, _, one := a.SplitSuffix(v)
if !one {
return nil
}
v = m
}
// a model stays with the model, even where other fields offer it too
// (Claude Code's opus/sonnet/haiku/fable)
for _, o := range a.Fields[0].Options(vals) {
if o.Value == v {
return nil
}
}
for i := 1; i < len(a.Fields); i++ {
for _, o := range a.Fields[i].Options(vals) {
if o.Value == v {
return &a.Fields[i]
}
}
}
return nil
}
// list prints the agents; those from dimFrom on (when not -1) are the ones
// hidden in the app, and are dimmed.
func list(agents []*agent.Agent, detectedOnly bool, dimFrom int) error {
if len(agents) == 0 {
return fmt.Errorf("no supported agents found on this machine")
}
type row struct{ name, vals, path string }
var rows []row
nameW, valW := 0, 0
for i, a := range agents {
r := row{name: a.Name, path: tilde(a.Path)}
if !detectedOnly && !a.Detected() {
r.name = faint.Render(a.Name)
r.vals = faint.Render("not detected")
r.path = ""
} else {
vals := a.Values()
dim := dimFrom >= 0 && i >= dimFrom
label, value := muted, lipgloss.NewStyle()
if dim {
label, value = faint, faint
}
var parts []string
for _, f := range a.Fields {
v := vals[f.Key]
if v == "" && f.Quiet {
continue
}
if v == "" {
v = faint.Render("—")
} else {
v = value.Render(v)
}
if f.Label == "model" {
parts = append(parts, v)
} else {
parts = append(parts, label.Render(f.Label)+" "+v)
}
}
r.name = bold.Render(a.Name)
if dim {
r.name = faint.Render(a.Name) + " " + faint.Render("hidden")
}
r.vals = strings.Join(parts, label.Render(" · "))
// through magpie for account failover while not connected (#1385)
if said := a.FailoverSaid(); said != "" {
r.vals += label.Render(" · " + said)
}
if a.Import != nil {
if a.Added != nil && a.Added() {
r.vals = value.Render("magpie added")
} else {
r.vals = label.Render("magpie "+a.ID+" add") + faint.Render(" to add magpie")
}
}
}
nameW = max(nameW, lipgloss.Width(r.name))
valW = max(valW, lipgloss.Width(r.vals))
rows = append(rows, r)
}
for _, r := range rows {
fmt.Printf(" %s %s %s\n", pad(r.name, nameW), pad(r.vals, valW), faint.Render(r.path))
}
return nil
}
func tilde(p string) string {
if home, err := os.UserHomeDir(); err == nil && strings.HasPrefix(p, home) {
return "~" + p[len(home):]
}
return p
}
func profiles(args []string) error {
switch args[0] {
case "profiles":
ps, err := profile.Load()
if err != nil {
return err
}
if len(ps) == 0 {
fmt.Println(muted.Render("no profiles yet · magpie save <name>"))
return nil
}
detected := agent.Detected()
for _, n := range profile.Names(ps) {
// ✓ the one the setup is now (superhtoooth on X)
mark := " "
if profile.InUse(ps[n], detected, nil) {
mark = green.Render("✓")
}
fmt.Printf("%s %s %s\n", mark, bold.Render(n), muted.Render(profile.LongSummary(ps[n])))
}
return nil
case "save":
if len(args) < 2 {
return fmt.Errorf("usage: magpie save <name>")
}
p, err := profile.Snapshot()
if err != nil {
return err
}
if err := profile.Save(args[1], p); err != nil {
return err
}
fmt.Println(green.Render("✓"), "saved profile", bold.Render(args[1]))
if p.Library != nil {
fmt.Println(" ", muted.Render("with the "+p.Library.Summary()))
}
return nil
case "use":
if len(args) < 2 {
return fmt.Errorf("usage: magpie use <name>")
}
ps, err := profile.Load()
if err != nil {
return err
}
p, ok := ps[args[1]]
if !ok {
return fmt.Errorf("no profile named %q", args[1])
}
a, err := profile.Apply(p)
if err != nil {
return err
}
fmt.Println(green.Render("✓"), "applied", bold.Render(args[1]), muted.Render(fmt.Sprintf("(%d changed)", a.Changed)))
for _, line := range profile.Report(a) {
fmt.Println(" ", muted.Render(line))
}
return nil
case "rm":
if len(args) < 2 {
return fmt.Errorf("usage: magpie rm <name>")
}
if err := profile.Delete(args[1]); err != nil {
return err
}
fmt.Println(green.Render("✓"), "deleted profile", bold.Render(args[1]))
return nil
}
return nil
}
func pad(s string, w int) string {
if n := w - lipgloss.Width(s); n > 0 {
return s + strings.Repeat(" ", n)
}
return s
}
func main() { cli.Main(version) }