diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 30160ddb9..4309f4594 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -78,7 +78,7 @@ something else shows up as drift. - Grok App (RongleCat/grok-app, a desktop front end that starts Grok Build over ACP) keeps its provider channels in `agent-home/config.toml` under its data folder: `$GROK_APP_HOME`, else where its `directories` crate puts it, or its `~/.grok-app` fallback when that is the one there (`grokApp` in [`grokapp.go`](../../internal/agent/grokapp.go)). Its composer lists only Grok Build's official catalog, never the `[model."magpie/…"]` tables of Grok Build's row, so magpie adds itself as a channel, `[model.magpie]`, with the keys the App's Providers page writes: the gateway's `/v1`, a key naming Grok App, `api_backend = "chat_completions"`, `app_provider_mode = "generic"`, and `app_models`, a JSON list of magpie's models with `contextWindow`, `supportsVision` and their effort levels (no `none`; a default the user marks in the App stays, else medium). The picked model's `context_window` (a bare integer) and `supports_reasoning_effort` (a bare bool, Grok Build's gate for `--reasoning-effort`) are on the channel, as the App puts them there when a model is picked in its composer. `[models] default` is the route, and magpie does not set it: setting it to `"magpie"` makes the App drop its own sign-in (`ensure_independent_for_custom_route`). The route stays whatever the App had. Pressing Use on magpie under Accounts is what switches it. A magpie that already set the route puts the old one back once, on the next sync or connect (`grokAppReleased`); a Use after that stays. Disconnect drops only the channel, and puts the route back only when it is still `"magpie"`: the one stashed at connect, else the one `connect.was` holds. One of the App's own routes picked in magpie's model field is written as the route and takes magpie's channel out, as picking another provider does elsewhere. A sync with no channel and a route other than `"magpie"` writes nothing, magpie's stash included, and Check says so when the route is `"magpie"` with the channel gone. A model picked in the App's composer since is the user's and stays through a sync, and a sync with nothing to change doesn't write. Shared mode keeps `GROK_HOME` at `~/.grok` (Grok Build's library row). Independent mode, which Use turns on, reads agent-home: the Library writes `AGENTS.md`, `[mcp_servers]` in the same `config.toml`, and `skills/` there, and Grok App also reads `~/.agents/skills`. RTK has no Grok hook, so the Library lists Grok App with the switch off. The notice, while the App runs, says magpie is a custom provider in Settings › Account, a chat can pick its models in the model picker, and the App stays on its current route until Use. - JSON/JSONC config edits and their previews reject malformed input rather than editing a partially parsed document. Object edits and VS Code's model-group array edits leave the original file untouched on a parse error; valid comments and trailing commas remain supported (`internal/edit`). - A config that starts with a UTF-8 byte order mark (a Windows `settings.json` or `config.toml` saved by PowerShell, Notepad or a channel switcher, #1534) is read without it (`edit.Read`), and a write keeps it (`keepBOM` in `WriteAtomic`): the user's file keeps the encoding it was saved in. That covers every format `internal/edit` writes (JSON/JSONC and its arrays, TOML, YAML, env); Codex reads a TOML file through a BOM too, so magpie no longer refuses one. A file read some other way trims it with `edit.TrimBOM` (the Claude Code and CC Switch imports). A line an edit takes out of a CRLF file goes with its `\r\n`. -- Codex signed in to ChatGPT stays beside its sign-in (`openai_base_url`) unless the user picks magpie API. magpie becomes its provider only while the Codex app holds the active account, which it sends nothing for: `/wham/usage` says it isn't allowed, and it has no credits and isn't a workspace still within its overage (`codexHeld`, read by `provider.CodexUsedUp`). Where the app goes by what usage can't show (an experiment's gate, a reserve, a Team plan's overage under the reserve experiment), it counts as held: a wrong move costs ChatGPT extras, a missed one every turn. A saved reading kept through a failed read stops saying held once its used-up window has started again; a hold with no window used up stays till a fresh read. The app then loses its ChatGPT state (durable threads, remote control), so a window at 100% alone, which credits get past, doesn't move it (`codex.out` marks the move, and Sync undoes it once the account has room). The same holds on one of Codex's own models joined beside the sign-in (MasterYi on Discord: the Codex app greyed Send for every model on a used-up account): Sync makes magpie the provider on that model as magpie serves it (`codexOwnViaMagpie`, `codex/`), keeps the model picked in `codex.out_own`, and once the account has room puts Codex back joined on it; a model the user picked meanwhile stays theirs. With no ChatGPT account in magpie to serve it, Codex is left as it is (`TestCodexOwnModelGoesThroughMagpieWhileUsedUp`, `TestCodexOwnModelKeptOnChatGPT`). The account is read again at once when a reply says it may be out (a `usage_limit_reached` rest, or an `x-codex-*` window heard at 100%; `provider.CodexMayBeUsedUp`, at most every 20s, the active account only), not only on the five-minute look. The Codex app greys Send for every model, magpie's too, while its `authMethod` is `chatgpt` and its rate limit says not allowed (its composer's gate in ChatGPT.app 26.1013), and reads `authMethod` from its app-server's `account/read` only as the app-server starts; with magpie the provider (`requires_openai_auth` false) that answers no account, so the gate lifts. So the gateway process restarts the app's own app-server each time magpie becomes Codex's provider for the used-up account (`Agent.AppOut`) and again when Codex is put back on the account after its reset, and likewise whenever what the app-server reads as it starts and magpie writes changes (`model_provider`, `openai_base_url`, `model_catalog_json`, the magpie table's `base_url`; `codexAppRoute`, through the `provider.CodexAppRoute` hook): a Disconnect, a Connect, failover written or taken out. Before this an app-server started while Codex was connected kept sending to the gateway after Disconnect until the app was restarted (JiangLiuer222 on X). At the watcher's first look only a used-up account's app-servers are ended, since what the others read before magpie started isn't known. It runs on every system (`KeepCodexAppOnItsProvider`, every 3s; Ethereal499 and Isdavexxx on X, MasterYi on Discord, #540: the earlier once-only reopen ran on macOS from the GUI process only, so Windows, Linux, a GUI-less magpie and the switch back stayed greyed). It ends only app-servers on magpie's Codex home (`codexAppHomeIs`: the process's `CODEX_HOME`, else `HOME/.codex`, read by `proc.EnvOf`; Windows can't tell and counts every one), only once no Codex request is in flight through the gateway nor ended in the last 10s (`Server.CodexBusy`) and no session under the Codex home has a turn started and not ended (`codexTurnOpen`), and with a clean exit (`proc.End`: SIGTERM, `TerminateProcess` with code 0), since the app shows any other exit as a crash. The app starts another app-server at once and keeps its window, threads and drafts (tried in the real app in a sandbox `CODEX_HOME`, both ways). An app-server that outlives three ends, or may not be ended, leaves the row saying to quit and reopen the app (`CodexAppStuck`). Until the reset the app's ChatGPT side is off (cloud tasks, its usage meter, Log out); the Agents row says so with the reset's time (`appOut` in `/api/state`, `CodexOutUntil`), and it all comes back at the reset. While the active account is held or a window is at 90% or more, its usage is read every minute rather than every five (`codexLookEvery`). `TestCodexAppServerRestartedEachWay`, `TestCodexAppServerRestartedOnDisconnect`, `TestCodexAppRouteFollowsConnectAndDisconnect`, `TestCodexAppServerUnknown`, `TestCodexAppServerStuck`, `TestCodexAppServersOnHome`, `TestCodexTurnOpen`, `TestCodexBusy`, `codex-app-out.test.cjs`. +- Codex signed in to ChatGPT stays beside its sign-in (`openai_base_url`) unless the user picks magpie API. magpie becomes its provider only while the Codex app holds the active account, which it sends nothing for: `/wham/usage` says it isn't allowed, and it has no credits and isn't a workspace still within its overage (`codexHeld`, read by `provider.CodexUsedUp`). Where the app goes by what usage can't show (an experiment's gate, a reserve, a Team plan's overage under the reserve experiment), it counts as held: a wrong move costs ChatGPT extras, a missed one every turn. A saved reading kept through a failed read stops saying held once its used-up window has started again; a hold with no window used up stays till a fresh read. The app then loses its ChatGPT state (durable threads, remote control), so a window at 100% alone, which credits get past, doesn't move it (`codex.out` marks the move, and Sync undoes it once the account has room). The same holds on one of Codex's own models joined beside the sign-in (MasterYi on Discord: the Codex app greyed Send for every model on a used-up account): Sync makes magpie the provider on that model as magpie serves it (`codexOwnViaMagpie`, `codex/`), keeps the model picked in `codex.out_own`, and once the account has room puts Codex back joined on it; a model the user picked meanwhile stays theirs. With no ChatGPT account in magpie to serve it, Codex is left as it is (`TestCodexOwnModelGoesThroughMagpieWhileUsedUp`, `TestCodexOwnModelKeptOnChatGPT`). The account is read again at once when a reply says it may be out (a `usage_limit_reached` rest, or an `x-codex-*` window heard at 100%; `provider.CodexMayBeUsedUp`, at most every 20s, the active account only), not only on the five-minute look. The Codex app greys Send for every model, magpie's too, while its `authMethod` is `chatgpt` and its rate limit says not allowed (its composer's gate in ChatGPT.app 26.1013), and reads `authMethod` from its app-server's `account/read` only as the app-server starts; with magpie the provider (`requires_openai_auth` false) that answers no account, so the gate lifts. So the gateway process restarts the app's own app-server each time magpie becomes Codex's provider for the used-up account (`Agent.AppOut`) and again when Codex is put back on the account after its reset, and likewise whenever what the app-server reads as it starts and magpie writes changes (`model_provider`, `openai_base_url`, `model_catalog_json`, the magpie table's `base_url`, and a hash of what the catalog file holds, `codexCatalogTag` in [`codex_app_route.go`](../../internal/agent/codex_app_route.go), read again only when its size or time changes; `codexAppRoute`, through the `provider.CodexAppRoute` hook): a Disconnect, a Connect, failover written or taken out, a provider or group renamed or a model added. Without the catalog in it the app kept the names and models it started with until it was restarted (lucis0116 on X). Before this an app-server started while Codex was connected kept sending to the gateway after Disconnect until the app was restarted (JiangLiuer222 on X). At the watcher's first look only a used-up account's app-servers are ended, since what the others read before magpie started isn't known. It runs on every system (`KeepCodexAppOnItsProvider`, every 3s; Ethereal499 and Isdavexxx on X, MasterYi on Discord, #540: the earlier once-only reopen ran on macOS from the GUI process only, so Windows, Linux, a GUI-less magpie and the switch back stayed greyed). It ends only app-servers on magpie's Codex home (`codexAppHomeIs`: the process's `CODEX_HOME`, else `HOME/.codex`, read by `proc.EnvOf`; Windows can't tell and counts every one), only once no Codex request is in flight through the gateway nor ended in the last 10s (`Server.CodexBusy`) and no session under the Codex home has a turn started and not ended (`codexTurnOpen`), and with a clean exit (`proc.End`: SIGTERM, `TerminateProcess` with code 0), since the app shows any other exit as a crash. The app starts another app-server at once and keeps its window, threads and drafts (tried in the real app in a sandbox `CODEX_HOME`, both ways). An app-server that outlives three ends, or may not be ended, leaves the row saying to quit and reopen the app (`CodexAppStuck`). Until the reset the app's ChatGPT side is off (cloud tasks, its usage meter, Log out); the Agents row says so with the reset's time (`appOut` in `/api/state`, `CodexOutUntil`), and it all comes back at the reset. While the active account is held or a window is at 90% or more, its usage is read every minute rather than every five (`codexLookEvery`). `TestCodexAppServerRestartedEachWay`, `TestCodexAppServerRestartedOnDisconnect`, `TestCodexAppRouteFollowsConnectAndDisconnect`, `TestCodexAppRouteFollowsTheCatalog`, `TestCodexAppServerUnknown`, `TestCodexAppServerStuck`, `TestCodexAppServersOnHome`, `TestCodexTurnOpen`, `TestCodexBusy`, `codex-app-out.test.cjs`. - Moving a field from one of magpie's models to another (the agent's own picker) is not drift. Moving it off magpie is. - Claude Desktop applying a configLibrary profile other than magpie's is not drift when that profile is a gateway profile for this magpie's gateway (`desktopAppliedGateway` in [`claudedesktop.go`](../../internal/agent/claudedesktop.go)): Desktop's "Import configuration" adds a file exported on another computer, magpie's profile there with the user's connectors (`managedMcpServers`), as a new entry under a random id (aa86222 on Discord). magpie keeps it applied on Reconnect and through Sync, and writes in it only `inferenceGatewayApiKey` (with a missing auth scheme) when the gateway would refuse its key (`desktopKeyApplied`; magpie's own keys count as taken, `desktopKeyTaken`). A profile for another gateway, CC Switch's among them, is still drift, and Reconnect applies magpie's. The first switch-on still starts magpie's profile from an applied one (#2035). `TestClaudeDesktopImportedProfileIsOnMagpie`. - A field that follows another while empty (`Follows`: Claude Code's tiers and subagents on its main model) is read by `Drift` as on that field's model. The main model moved, in Claude Code's own `/model`, onto the model magpie had set a tier to is not drift (#1050). The tier keeps that model as its own through the move and the next one (`tier_own` in the stash), whatever it would follow on the new main model: fable, which follows no model that is no Fable, and haiku, which follows a Claude model on its Haiku, read as following and lost their model on the next move (#2257). diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index b161f8ef5..e58fc93a0 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -45,7 +45,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | 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 reads CLIProxyAPI's files and Sub2API's export, whose Claude account says its email as Anthropic does, `email_address`, in `credentials` or `extra`, and keeps its `scope`, `account_uuid` and `org_uuid` as Claude Code's scopes, `accountUuid` and `organizationUuid` (#1975); a file with no email is refused, as Claude Code's own `.credentials.json` is. 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, or for Claude organization (`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). For Codex, *Only switch Codex's sign-in* (`SwitchOnly`, `SetSwitchOnly`) keeps magpie's `openai_base_url` failover out of Codex's config, so the switch is all magpie does (#1907); an unreadable providers.json reads as switch-only, so the failover is not written on a guess. | [`codex_switch.go`](../../internal/provider/codex_switch.go) | | Claude Code's proxy | Claude Code on its own subscription asks Anthropic itself, through the proxy its env names. While any Claude account has a proxy of its own (`AccountProxies`), the `env` of Claude Code's `settings.json` names the proxy of the account it is signed in to (#1807): `HTTPS_PROXY` and `HTTP_PROXY` set to that account's own, else the subscription's `Proxy` (`ProxyOfLogin`), and `NO_PROXY` to loopback; none for `direct` or a SOCKS proxy, which Claude Code can't use. It is written on every switch (`switchLogin`, the user's or `SwitchWhenSpent`), when the Claude subscription is saved, and at the gateway's look every `loginSwitchEvery` (a sign-in made in Claude Code itself). Claude Code reads its env at start, so only sessions started after the switch take it. A proxy key the user set (in either case) is theirs: magpie then writes none and takes out none of theirs. What magpie wrote is kept in `claude-proxy-env.json`, and a key is magpie's only while it holds that value. A `settings.json` that doesn't parse is left as it is. Its log lines name the proxy through `netproxy.Redact`, without its user and password (#1886); the env gets it whole. | [`claude_proxy_env.go`](../../internal/provider/claude_proxy_env.go) | -| Routing groups | User-made groups from the Routing view, and auto-found groups of the same model across providers (derived, never stored). The same model is the same id as vendors agree on it (`sameModel`): lowercase, without a vendor's prefix, a version's dot as `-`, a run of spaces, `_` and `-` as one `-` (a relay listing its display name as the id, `GPT-6 Sol`, joins `gpt-6-sol`, Chill on Discord: `TestSameModelDisplayNameAsID`), and without a YYYYMMDD or Ark YYMMDD snapshot date. Every word still counts (`gpt-6`, `gpt-6-mini` and `gpt-6-sol` stay apart), as do a `:variant`, a four-digit release and OpenAI's dashed date (`gpt-4o-2024-08-06`, a pinned snapshot whose group id agents may already name). A provider kept "Only through routing groups" joins them the same way. Members are `provider/model[:effort]`. A group can nest another (`group/`); `SaveGroup` refuses loops. `Match` takes a glob or `re:` pattern (#766), both matched in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter). A found group follows the providers magpie has: one removed leaves it, while one switched off stays in it (`foundGroups`, `heldOffEntries`; one without a key, such as a plugin not signed in, finds no group), skipped by `membersIn` and said as switched off on the Routing page, so switching one of two providers off for a while doesn't take the group away from the agents, rules and groups set to it; it is back in its place once on again (#2671: `TestFoundGroupStaysWithAProviderOff`, `TestFoundGroupWithAProviderOff`, `TestReseatKeepsAFoundGroupWithAProviderOff`, `TestFoundGroupMemberOfASwitchedOffProvider`). 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) | +| Routing groups | User-made groups from the Routing view, and auto-found groups of the same model across providers (derived, never stored). The same model is the same id as vendors agree on it (`sameModel`): lowercase, without a vendor's prefix, a version's dot as `-`, a run of spaces, `_` and `-` as one `-` (a relay listing its display name as the id, `GPT-6 Sol`, joins `gpt-6-sol`, Chill on Discord: `TestSameModelDisplayNameAsID`), and without a YYYYMMDD or Ark YYMMDD snapshot date. Every word still counts (`gpt-6`, `gpt-6-mini` and `gpt-6-sol` stay apart), as do a `:variant`, a four-digit release and OpenAI's dashed date (`gpt-4o-2024-08-06`, a pinned snapshot whose group id agents may already name). A provider kept "Only through routing groups" joins them the same way. Members are `provider/model[:effort]`. A group can nest another (`group/`); `SaveGroup` refuses loops. A group given another id (`agent.RenameGroup`: the Routing page, `magpie groups rename`, the TUI) moves every agent field on `group/` to `group/`, spelled as the agent spells it, through the same `renameRefs` a provider's rename uses, then `SyncCatalog`; before, the agents stayed on a group magpie no longer had (lucis0116 on X, `TestRenameGroupMovesTheAgentsOnIt`). A provider's or group's display name needs no move: `store` and `SaveGroup` drop the catalog, and `SyncCatalog` writes the new labels into every agent's list. `Match` takes a glob or `re:` pattern (#766), both matched in any case (`compilePattern`; `(?-i)` inside a `re:` makes case matter). A found group follows the providers magpie has: one removed leaves it, while one switched off stays in it (`foundGroups`, `heldOffEntries`; one without a key, such as a plugin not signed in, finds no group), skipped by `membersIn` and said as switched off on the Routing page, so switching one of two providers off for a while doesn't take the group away from the agents, rules and groups set to it; it is back in its place once on again (#2671: `TestFoundGroupStaysWithAProviderOff`, `TestFoundGroupWithAProviderOff`, `TestReseatKeepsAFoundGroupWithAProviderOff`, `TestFoundGroupMemberOfASwitchedOffProvider`). 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, each window with its whole-window estimate (`Holds`/`HoldsWhy`, `usage.WithWindowHolds`, which `quotaReport` reaches through the `ReckonHolds` hook since package provider can't import usage, #2333). 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. A Claude account's windows Claude Code told as it answered (`NoteClaudeLimits`, kept in `claudeUsage` with their own `heardSeq`, which drops the account's `LoginUsage` reading) stand on its card over any reading started before them (`withHeardClaude`, #2206), so a magpie only requests reach still tells them. 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 `/~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=/~keys&user=`). 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`). A remote that holds the key to a budget, models or accounts answers its cards 403 `gateway_key_held` (#1981, `errKeyHeld`): the cards kept from before are dropped and only the key's own card shows. Its owner can let the key be told the cards of what it may use (#2216, `magpie gateway-key quotas on`); the remote then answers those, and 403 as before when that is none. A remote's cards are kept by provider and key (`remoteCardsID`), so a changed key never shows what the old one was told, and a read is kept only over one asked before it (`keepRemoteCards`). 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) | | A remote magpie's prices | A local magpie asks a remote magpie's `/v1/models` with `X-Magpie-Prices` (`PricesHeader`, sent by `listHeaders`). The remote answers each model's `magpie_price`: what its own Usage page counts the model at (`EntryPriceIn`: the price its user set, else its provider's list price at its price rate; a routing group only when every member costs the same). It tells it only to a request from its own computer or one let in with a gateway key (`local` or `sharedWith`); a list that didn't ask gets no `magpie_price` (a remote request without a valid key never reaches the list: `lanGuard` refuses it); every list told to those callers also carries the same price as OpenRouter's `pricing`, for agents ([gateway routing](gateway-routing.md)). The local keeps the price with the fetched list (`catalog.Model.Price`; a value that isn't a price, or has a negative part, is dropped, the model kept) and uses it as that provider's list price (`ListPrice` → `remotePrice`). A price the local user set (`provider/model`, `provider/*`, `*/model`) still comes first, and the local provider's own price rate still applies on top. A remote from before this sends no field and the models stay priced as before; an older local sends no header and is sent nothing new. The model editor says the greyed price is the other magpie's (`remoteList`). | [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`models.go`](../../internal/provider/models.go), [`gateway.go`](../../internal/gateway/gateway.go) (`models`), [`live.go`](../../internal/catalog/live.go) | | A remote magpie's service tiers | A remote magpie's `/v1/models` gives each model the `service_tiers` its own Codex is offered on it (`codexTiers` → `codexcat.ServiceTiers`, from the same `CodexCatalog` and `codexcat.Entries` as its `/v1/codex/models`: Fast on a ChatGPT account's GPT model, the tiers of Codex's own entry on a relay's, none on a model it offers none). The local keeps the ids (`catalog.Model.Tiers` → `Entry.Tiers`), `codexListed` hands them on for the remote's models, and `codexcat.Entries` offers them to the local Codex with Codex's own names (`namedTiers`). The gateway sends the tier Codex asks for to a remote magpie as it was asked (`Request.OwnTier`, as for a provider added by its address; dropped and not sent again if refused), and the remote serves it as its own Codex's turn (#1234). A remote from before this sends no tiers, and its models are offered none, as before. The list gives every client the tiers, not only a magpie asking with `X-Magpie-Drawers`: Cindy shows its Fast switch on a model whose `service_tiers` hold `priority` (#1914, `TestModelsListTiersForEveryClient`). | [`codexcat.go`](../../internal/codexcat/codexcat.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`gateway.go`](../../internal/gateway/gateway.go), [`live.go`](../../internal/catalog/live.go) | diff --git a/internal/agent/agents.go b/internal/agent/agents.go index 4684214ee..3685a3cc1 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -72,6 +72,15 @@ func codexAppRoute() (route string, out, known bool) { } t, _ := edit.GetTOMLTable(a.Path, "model_providers."+magpieID) b.WriteString("magpie.base_url=" + t["base_url"] + "\n") + // and the list in that catalog, which the app-server also reads only + // as it starts: a provider or group renamed, or a model added, left + // the app on the names and models it started with (lucis0116 on X) + if c, _ := edit.GetTOMLTop(a.Path, "model_catalog_json"); c != "" { + if !filepath.IsAbs(c) { + c = filepath.Join(filepath.Dir(a.Path), c) + } + b.WriteString("catalog=" + codexCatalogTag(c) + "\n") + } if out { b.WriteString("out\n") } diff --git a/internal/agent/codex_app_route.go b/internal/agent/codex_app_route.go new file mode 100644 index 000000000..d830ea2e7 --- /dev/null +++ b/internal/agent/codex_app_route.go @@ -0,0 +1,45 @@ +package agent + +import ( + "crypto/sha256" + "encoding/hex" + "os" + "sync" + "time" +) + +// codexCatalogTag stands for what the catalog file at path holds now, for +// codexAppRoute: a hash of its bytes, "" when it can't be read. The route +// is looked at every few seconds (provider.KeepCodexAppOnItsProvider) and +// the catalog holds each model's instructions, a few MB with many models, +// so the file is read again only when its size or time changed. A rewrite +// to the same bytes (a Connect writes it again) is the same tag, and +// restarts nothing. +func codexCatalogTag(path string) string { + st, err := os.Stat(path) + if err != nil { + return "" + } + c := &codexCatalogSeen + c.Lock() + defer c.Unlock() + if c.path == path && c.size == st.Size() && c.mod.Equal(st.ModTime()) { + return c.tag + } + b, err := os.ReadFile(path) + if err != nil { + return "" + } + sum := sha256.Sum256(b) + c.path, c.size, c.mod, c.tag = path, st.Size(), st.ModTime(), hex.EncodeToString(sum[:12]) + return c.tag +} + +// codexCatalogSeen is the last catalog codexCatalogTag read. +var codexCatalogSeen struct { + sync.Mutex + path string + size int64 + mod time.Time + tag string +} diff --git a/internal/agent/rename.go b/internal/agent/rename.go index ce96f40c4..453300ae8 100644 --- a/internal/agent/rename.go +++ b/internal/agent/rename.go @@ -14,58 +14,14 @@ import ( func RenameProvider(from, to string) ([]string, error) { from = strings.ToLower(strings.TrimSpace(from)) to = strings.ToLower(strings.TrimSpace(to)) - type move struct { - a *Agent - key, val string - } - // what the agents are on is read before: the picker's options name - // the provider by the id it has - var moves []move - if from != to { - for _, a := range Detected() { - vals := a.Values() - for _, f := range a.Fields { - v := vals[f.Key] - if v == "" { - continue - } - // the agent's suffix after the model (SplitSuffix) stays; a - // list of models is the user's own, its names moved by - // RenameRefs where the agent has one - model, suffix, one := a.split(v) - if !one { - continue - } - nv := "" - if f.Options != nil { - for _, o := range f.Options(vals) { - if o.Value == model && strings.HasPrefix(o.Ref, from+"/") { - now := to + "/" + strings.TrimPrefix(o.Ref, from+"/") - nv = strings.Replace(model, o.Ref, now, 1) + suffix - break - } - } - } - if nv == "" && strings.HasPrefix(v, magpieID+"/"+from+"/") { - nv = magpieID + "/" + to + "/" + strings.TrimPrefix(v, magpieID+"/"+from+"/") - } - if nv != "" && nv != v { - moves = append(moves, move{a, f.Key, nv}) - } - } - } - } - if err := provider.Rename(from, to); err != nil { - return nil, err - } - var moved []string - for _, m := range moves { - if err := m.a.Apply(m.key, m.val); err != nil { - return moved, err - } - if len(moved) == 0 || moved[len(moved)-1] != m.a.Name { - moved = append(moved, m.a.Name) + moved, err := renameRefs(func(ref string) (string, bool) { + if rest, ok := strings.CutPrefix(ref, from+"/"); ok && from != to { + return to + "/" + rest, true } + return "", false + }, func() error { return provider.Rename(from, to) }) + if err != nil { + return moved, err } if from != to { for _, a := range Detected() { @@ -85,6 +41,97 @@ func RenameProvider(from, to string) ([]string, error) { return moved, nil } +// RenameGroup gives a routing group another id (provider.RenameGroup) and +// moves the agents on it to group/, as RenameProvider does a +// provider's: left on group/, each agent named a group magpie no +// longer has, and the user had to pick the group again in every agent +// (lucis0116 on X). It answers the agents it moved. +func RenameGroup(from, to string) ([]string, error) { + from = strings.ToLower(strings.TrimSpace(from)) + to = strings.ToLower(strings.TrimSpace(to)) + old, now := provider.GroupPrefix+from, provider.GroupPrefix+to + moved, err := renameRefs(func(ref string) (string, bool) { + if ref == old && from != to { + return now, true + } + return "", false + }, func() error { return provider.RenameGroup(from, to) }) + if err != nil { + return moved, err + } + SyncCatalog() + return moved, nil +} + +// renameRefs runs rename and then moves every field of a detected agent +// that was on a model whose ref renamed maps, to that model's new ref, +// spelled as the agent spells it. What the agents are on is read before +// rename: the pickers' options name the model by the ref it has then. +func renameRefs(renamed func(ref string) (string, bool), rename func() error) ([]string, error) { + type move struct { + a *Agent + key, val string + } + var moves []move + for _, a := range Detected() { + vals := a.Values() + for _, f := range a.Fields { + v := vals[f.Key] + if v == "" { + continue + } + // the agent's suffix after the model (SplitSuffix) stays; a + // list of models is the user's own, its names moved by + // RenameRefs where the agent has one + model, suffix, one := a.split(v) + if !one { + continue + } + nv := "" + if f.Options != nil { + for _, o := range f.Options(vals) { + if o.Value != model { + continue + } + if now, ok := renamed(o.Ref); ok { + nv = strings.Replace(model, o.Ref, now, 1) + suffix + break + } + } + } + if ref, ok := strings.CutPrefix(v, magpieID+"/"); nv == "" && ok { + // the agent's value names magpie's model outright + // (magpie/), with its suffix after it + for _, r := range []string{ref, strings.TrimPrefix(model, magpieID+"/")} { + if !strings.HasPrefix(ref, r) { + continue + } + if now, ok := renamed(r); ok { + nv = magpieID + "/" + now + strings.TrimPrefix(ref, r) + break + } + } + } + if nv != "" && nv != v { + moves = append(moves, move{a, f.Key, nv}) + } + } + } + if err := rename(); err != nil { + return nil, err + } + var moved []string + for _, m := range moves { + if err := m.a.Apply(m.key, m.val); err != nil { + return moved, err + } + if len(moved) == 0 || moved[len(moved)-1] != m.a.Name { + moved = append(moved, m.a.Name) + } + } + return moved, nil +} + // MoveOffAccountIDs moves each of the user's providers saved on a // subscription's id (provider.OnAccountIDs) to a free one, the agents on it // with it, so the subscription is listed once signed in: a "WorkBuddy" key diff --git a/internal/agent/rename_group_test.go b/internal/agent/rename_group_test.go new file mode 100644 index 000000000..64e772a9b --- /dev/null +++ b/internal/agent/rename_group_test.go @@ -0,0 +1,113 @@ +package agent + +import ( + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/provider" +) + +// A routing group given another id takes the agents on it along, as a +// provider's rename does: Codex, Claude Code (its model and tiers), +// OpenCode and Pi were left on group/, a group magpie no longer had, +// and the user had to pick it again in each (lucis0116 on X). +func TestRenameGroupMovesTheAgentsOnIt(t *testing.T) { + home := syncHome(t) + if err := provider.SaveGroup(provider.Group{ID: "smart", Name: "Smart", Members: []string{"relay/glm-4.6"}}); err != nil { + t.Fatal(err) + } + codexCfg := filepath.Join(home, ".codex", "config.toml") + codexCat := filepath.Join(home, ".codex", "magpie-models.json") + writeFile(t, codexCfg, "model = \"group/smart\"\nmodel_provider = \"magpie\"\nmodel_catalog_json = '"+codexCat+"'\n") + writeFile(t, codexCat, `{"models":[]}`) + piModels := filepath.Join(home, ".pi", "agent", "models.json") + piSettings := filepath.Join(home, ".pi", "agent", "settings.json") + writeFile(t, piModels, `{"providers":{"magpie":{"name":"magpie","models":[]}}}`) + writeFile(t, piSettings, `{"defaultProvider":"magpie","defaultModel":"group/smart"}`) + oc := filepath.Join(home, ".config", "opencode", "opencode.json") + writeFile(t, oc, `{"model":"magpie/group/smart"}`) + claudeCfg := filepath.Join(home, ".claude", "settings.json") + writeFile(t, claudeCfg, `{}`) + cc, err := Find("claude") + if err != nil { + t.Fatal(err) + } + if err := cc.Apply("model", "group/smart"); err != nil { + t.Fatal(err) + } + SyncCatalog() + + moved, err := RenameGroup("smart", "clever") + if err != nil { + t.Fatal(err) + } + for _, name := range []string{"Codex", "Claude Code", "OpenCode", "Pi"} { + if !slices.Contains(moved, name) { + t.Errorf("%s not said moved: %v", name, moved) + } + } + if v, _ := edit.GetTOMLTop(codexCfg, "model"); v != "group/clever" { + t.Errorf("codex model = %q", v) + } + if v, _ := edit.GetJSON(piSettings, "defaultModel"); v != "group/clever" { + t.Errorf("pi defaultModel = %v", v) + } + if v, _ := edit.GetJSON(oc, "model"); v != "magpie/group/clever" { + t.Errorf("opencode model = %v", v) + } + claude := readFile(claudeCfg) + if strings.Contains(claude, "group/smart") || !strings.Contains(claude, `"model": "group/clever"`) && !strings.Contains(claude, `"model":"group/clever"`) { + t.Errorf("claude settings still on the old id:\n%s", claude) + } + for _, f := range []string{codexCat, piModels, oc} { + if s := readFile(f); strings.Contains(s, "group/smart") || !strings.Contains(s, "group/clever") { + t.Errorf("%s lists the old id:\n%s", f, s) + } + } +} + +// The Codex app's app-server reads its model catalog only as it starts, +// so the route it is restarted on (codex_app_server.go) follows what the +// catalog holds: a provider's name changed in magpie reached the file, and +// the app kept showing the old one (lucis0116 on X). The same bytes +// written again are no change. +func TestCodexAppRouteFollowsTheCatalog(t *testing.T) { + home := syncHome(t) + codexCat := filepath.Join(home, ".codex", "magpie-models.json") + writeFile(t, filepath.Join(home, ".codex", "config.toml"), "model = \"relay/glm-4.6\"\nmodel_provider = \"magpie\"\nmodel_catalog_json = '"+codexCat+"'\n") + writeFile(t, codexCat, `{"models":[]}`) + SyncCatalog() + route := func() string { + t.Helper() + r, _, known := codexAppRoute() + if !known { + t.Fatal("route not known") + } + return r + } + before := route() + if !strings.Contains(readFile(codexCat), "GLM-4.6 · Relay") { + t.Fatalf("catalog:\n%s", readFile(codexCat)) + } + if err := provider.Save(provider.Provider{ID: "relay", Name: "Renamed", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"glm-4.6"}}); err != nil { + t.Fatal(err) + } + SyncCatalog() + if !strings.Contains(readFile(codexCat), "GLM-4.6 · Renamed") { + t.Fatalf("catalog not rewritten:\n%s", readFile(codexCat)) + } + renamed := route() + if renamed == before { + t.Fatal("a provider renamed left the Codex app's route as it was: its app-server keeps the old names") + } + // written again as it is (a Connect does): no restart for that + if err := writeOwnList(codexCat, []byte(readFile(codexCat))); err != nil { + t.Fatal(err) + } + if route() != renamed { + t.Error("the same catalog written again changed the route") + } +} diff --git a/internal/cli/groups_cli.go b/internal/cli/groups_cli.go index b2863cf8c..3503c04ad 100644 --- a/internal/cli/groups_cli.go +++ b/internal/cli/groups_cli.go @@ -807,10 +807,13 @@ func setGroup(ref string, pairs []string) (provider.Group, error) { return g, err } if to != from { - if err := provider.RenameGroup(from, to); err != nil { + moved, err := agent.RenameGroup(from, to) + if err != nil { return g, err } - fmt.Println(amber.Render("!"), "agents set to "+provider.GroupPrefix+from+" need "+provider.GroupPrefix+to+" now") + for _, a := range moved { + fmt.Println(green.Render("✓"), a+" is on "+provider.GroupPrefix+to+" now") + } } return findGroup(to) } diff --git a/internal/gui/groups.go b/internal/gui/groups.go index 0ff7a7b33..cb2e6f9b5 100644 --- a/internal/gui/groups.go +++ b/internal/gui/groups.go @@ -418,7 +418,8 @@ func groupRoutes(mux *http.ServeMux) { } in.ID = body.From if err = provider.SaveGroup(in); err == nil { - err = provider.RenameGroup(body.From, to) + // the agents on group/ move to group/ + _, err = agent.RenameGroup(body.From, to) } case "delete": if len(body.IDs) > 0 { diff --git a/internal/tui/routing.go b/internal/tui/routing.go index c31fdbf52..169b4cdf2 100644 --- a/internal/tui/routing.go +++ b/internal/tui/routing.go @@ -493,7 +493,7 @@ func (m model) updateGroup(msg tea.KeyMsg) (tea.Model, tea.Cmd) { hint: "agents pick it as group/: those on it, and the groups that have it in them, follow", onEnter: func(to string) tea.Cmd { return func() tea.Msg { - if err := provider.RenameGroup(g.ID, to); err != nil { + if _, err := agent.RenameGroup(g.ID, to); err != nil { return flashMsg{text: err.Error()} } return renamedMsg{from: g.ID, to: strings.ToLower(to)}