Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
agentplug: connect's models carry /v1/models' native_endpoints and pricing
yetone0b72ccbeff9d
diff --git a/docs/reference.md b/docs/reference.mdindex d73813c16..69453a95a 100644--- a/docs/reference.md+++ b/docs/reference.md@@ -1049,6 +1049,21 @@ export function connect({ gateway, model, models }) {It is then on the Agents page like magpie's own: picking one of magpie'smodels writes the model and what `connect` returns, and its own model orDisconnect puts every key back as it was. It runs in moejs like middleware.+`connect` gets `gateway` (`url`, `v1`, `key`), `model` and `models` (each+`id`, `name`, `context`, `output`, `images`, `efforts`), and `agent`+(`id`, `config`). Each model also has what `/v1/models` says of it, by the+same names: `native_endpoints`, the gateway paths a request for it goes on+untranslated, and `pricing`, USD a token as decimal strings, so an agent+can ask a model on the API that passes straight through and show what a+call costs. Each is left out when it isn't known (a routing group has no+`native_endpoints`, an unpriced model no `pricing`), never empty or 0:++```json+{ "id": "deepseek/pro", "name": "pro · DeepSeek", "context": 0, "output": 0, "images": false, "efforts": [],+ "native_endpoints": ["/v1/chat/completions"],+ "pricing": { "prompt": "0.0000003", "completion": "0.0000012", "input_cache_read": "0.00000003" } }+```+An id magpie's own agents use is refused. In the market an agent's entry has`"kind": "agent"` (`@magpie-community/agent-<name>`). The full reference ison the site's Plugins page, under Agent plugins.diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.mdindex 992aa7eb2..7d482d488 100644--- a/docs/subsystems/agent-wiring.md+++ b/docs/subsystems/agent-wiring.md@@ -25,7 +25,7 @@ something else shows up as drift.| Named omp profiles | omp keeps a profile's settings under `~/.omp/profiles/<name>` (or under `PI_CONFIG_DIR`), each with its own `config.yml` and `models.yml`. Every such profile is an agent of its own — `omp#<name>` on Windows, `omp#<name>@wsl:<distro>` in a distro — so each can be connected, drifted and disconnected on its own. They share omp's model lists (`ListsFor`), and the default `omp` row is the folder `ompDir`/`ompIn` already pick, so an `OMP_PROFILE` that row is already pointed at is not listed twice. A name omp refuses is not a row: `default`, a trailing dot, or a Windows reserved device name (`aux`, `nul`, `com1`, `lpt9.x`, `con.work`), on every platform (`ompProfileOK`). A distro's profile names come from its probe and are kept in `wsl.json`; a stopped distro is never started to list them, its profile rows showing what was last seen (`asleep`). | [`omp.go`](../../internal/agent/omp.go), [`wsl.go`](../../internal/agent/wsl.go) || WSL twins | On Windows each running distro is probed once, without starting a stopped one. The `wslKinds` agents found there become agents of their own, `<id>@wsl:<distro>`, edited through `\\wsl.localhost\<distro>`. A kind is found by its folder under the distro's home or by its command there (not one on a Windows drive). Where another tool shares one of them, the kind leaves it out: Gemini CLI is found by its command alone, because Antigravity keeps `~/.gemini` too. Goose is found by its folder alone, because a `goose` command can be pressly's migration tool. Reasonix also needs the version its command gives (`accept`), because the old npm client is named `reasonix` too. The gateway address and key follow the distro's networking: mirrored or NAT (`place`, `keyAt`). `ListsFor` keeps a twin's model picks under the Windows twin's id (#927). | [`wsl.go`](../../internal/agent/wsl.go), [`gatewaykey.go`](../../internal/agent/gatewaykey.go) || Settings tuned from use | Usage › Context's "Tuned for you" advises, per agent, the settings that would have spent the fewest tokens on the user's own calls of the range, and puts one in on a click. Package `tune` replays the calls `sessions.Calls` reads from the agents' session files under each candidate value (`Compact`, `CacheTTL`); `tuneOf` picks the agents and models (Claude Code per model, Codex pooled). `TuneRead`, `TuneApply` and `TuneUndo` know where each setting lives: Claude Code's `modelSettings.<model>.autoCompactWindow` (where its `/autocompact` saves), `promptCacheTtl` and `subagentPromptCacheTtl` in `~/.claude/settings.json`; Codex's top-level `model_auto_compact_token_limit`. The advice is weighed by tokens alone: it is labelled "Fewest tokens", and a compaction window it would change says it doesn't measure how well the agent keeps the task after a compaction, and that a lower window compacts more often (#1854, `context-tune.test.cjs`). A compaction row's "Other window…" opens the app menu with every value of the curve, each with its estimated extra tokens over the fewest and about how many compactions it would have made (`Point.compacts`, from the same replay), and puts the one picked in like Use (#1860). An agent whose files time its compactions also has their wait weighed (HirotaNagai on X): Claude Code's `compact_boundary` line says `compactMetadata.durationMs`, which `sessions` puts on the first call after it, and Codex compacts by a call of its own (the record a `compacted` line names, in rollouts since 2026-09), whose time is the compaction's (`Call.Compact`; an older rollout's compaction has no call and stays untimed). With 3 or more timed for a model (`minTimed`), `Facts.took` is their median seconds, each window says its wait (`Point.wait`, its compactions × `took`), and the row says what a compaction took, the wait at the advice against the window now, and the cheaper window the advice passed over for waiting longer (`Compaction.cheapest`, `wait_cheapest`) when it saves 3% or more; the advice is labelled "Tokens + wait", its caveat says tokens and waiting only, and the picker says each window's wait with "Fewest tokens" on the cheapest (`context-tune.test.cjs`). An agent or model with fewer timed reads and is advised as before. | [`internal/tune`](../../internal/tune/tune.go), [`tune.go`](../../internal/agent/tune.go), [`internal/gui/tune.go`](../../internal/gui/tune.go) |-| Agents a plugin adds | A plugin's `magpie.agent` module (or a `*.agent.js` file) says where an agent magpie has no setup of its own keeps its model (`config`, `format`, `model`, `prefix`), and its `connect` returns the other keys to write. One with no `model` is connect only (#2374): its one field is `provider`, magpie or nothing, as an app whose one setting is magpie as its provider; `connect` is called without a model, must return keys, and is called again on a catalog change (`Sync`); `ListsModels` is set, so its list is the models picked for it. `agentplug` compiles each in moejs (via `jsmod`, as gateway middleware is), reloads it when plugins.json or the file changes, and keeps why one didn't load. `plugged` makes each an `Agent` with `Plugin` set, listed after magpie's own; an id one of magpie's own agents has is refused (`PluginErrors`). | [`agentplug.go`](../../internal/agentplug/agentplug.go), [`plugged.go`](../../internal/agent/plugged.go) |+| Agents a plugin adds | A plugin's `magpie.agent` module (or a `*.agent.js` file) says where an agent magpie has no setup of its own keeps its model (`config`, `format`, `model`, `prefix`), and its `connect` returns the other keys to write. One with no `model` is connect only (#2374): its one field is `provider`, magpie or nothing, as an app whose one setting is magpie as its provider; `connect` is called without a model, must return keys, and is called again on a catalog change (`Sync`); `ListsModels` is set, so its list is the models picked for it. `agentplug` compiles each in moejs (via `jsmod`, as gateway middleware is), reloads it when plugins.json or the file changes, and keeps why one didn't load. `plugged` makes each an `Agent` with `Plugin` set, listed after magpie's own; an id one of magpie's own agents has is refused (`PluginErrors`). `connect` is given each model as `magpieModels` builds it, with `/v1/models`' `native_endpoints` (`provider.NativeEndpoints`, carried as `catalog.Model.Endpoints`) and `pricing` (`catalog.OpenRouterPricing` of the same `EntryPricer` price), each left out when not known ([`plugged_connect_facts_test.go`](../../internal/agent/plugged_connect_facts_test.go)). | [`agentplug.go`](../../internal/agentplug/agentplug.go), [`plugged.go`](../../internal/agent/plugged.go) || Environment-only agents | Agents that read the gateway only from the environment get a `Launch` command. Cursor Private Inference instead gets user-level variables (`cursorLocalOn`, `KeepCursorLocalEnv`), and magpie writes none of Cursor's own files. It is found by its product.json in the apps folders, in the folder Windows' list of installed programs names (`cursorLocalInstalls`, any folder picked in its installer), or as its Linux AppImage (`Cursor_Private_Inference-…AppImage`) in the folders downloads are kept in (#1254). Its effort field is kept in magpie (`provider.AgentEffort`) and asked by the gateway, its levels those of the models it lists (`cursorLocalEfforts`, #1003). | [`cursorlocal.go`](../../internal/agent/cursorlocal.go) || Claude Science | Its daemon (`claude-science`) reads the API's address only from its environment's `ANTHROPIC_BASE_URL` and has no setting for it. Connect restarts the daemon with that variable set to the gateway (`scienceOn`: `stop`, then `serve --detached --no-browser` on the port `status` said it was on) and notes the daemon in `claude-science.json` (url, pid, port); Disconnect restarts it without the variable, one in magpie's own environment taken out too. No variable is set for the user and no file of the app's is written. Setting it again while magpie's daemon runs on this gateway does nothing (`Pick` sets the field after `connect`). `KeepClaudeScience` starts it again on the gateway, on its port, when it isn't running (a restart of the computer), each minute while magpie serves; it never stops one running. `Check` reads the daemon's `operon.lock`, not `status` (seconds for a 130 MB Bun program), and calls a daemon with another pid drift: the app's window, opened while none ran, starts its own without the variable. It is found in the Mac app's bundle (`Claude Science.app/Contents/Resources/bin`), `%LOCALAPPDATA%\Programs\ClaudeScience` on Windows, `~/.local/bin`, else on PATH. The app still needs its own Claude sign-in; the gateway never passes it on (see gateway-routing). | [`claudescience.go`](../../internal/agent/claudescience.go), [`science.go`](../../internal/gateway/science.go) |diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex f2878c507..c32788c83 100644--- a/docs/subsystems/gateway-routing.md+++ b/docs/subsystems/gateway-routing.md@@ -209,7 +209,7 @@ recorded as a prediction failure (`noPrediction`).- A tool call's arguments reach the client as the vendor writes them, translated too (echo_ts on Discord: Codex on Copilot about 10x slower, an apply_patch shown only once whole). The Responses decoder hands each `function_call_arguments.delta` and `custom_tool_call_input.delta` on as a `KToolArgs` delta (`argsDelta`), holding back only the one that would make the JSON whole until `.done`, which `endCall` checks against the final arguments; the Responses encoder streams a custom tool's input as `custom_tool_call_input.delta` (`customStream` in [`custom_tool.go`](../../internal/gateway/custom_tool.go)) before its `.done`. A Copilot account's Responses request is relayed with a `web_search` tool in it (`searchesItself`; checked on a real account 2026-10-17), and Copilot is never picked to search for another provider's model (`searchRank`). It is translated instead when a tool marks a parameter `"encrypted": true` (`asksSealing`, MultiAgentV2's `spawn_agent`): Copilot seals such an argument and can't read its own seal on the subagent's turn. `TestCallArgsStreamWhenTranslated`, `TestCustomInputStreams`, `TestResponsesCallArgsStream`, `TestCopilotRelayedUnlessAskedToSeal`, `TestCopilotUltraSubagentWithWebSearch`.- A relayed Responses stream gives each output item the one id its `response.output_item.added` gave it, in every event after that carries an `item_id` or an `item`, and in the `output` of `response.completed`, `response.incomplete` or `response.failed` (`idTidy` in [`itemids.go`](../../internal/gateway/itemids.go), applied in `passthrough` before `phaseTidy`). GitHub Copilot's `/responses` gives an item another id in every event (checked 2026-10-19 on a real account, gpt-5.5 with web_search), and Codex starts an item by the added's id and ends one by the done's, so a commentary message was shown twice and a web search never ended (echo_ts on Discord, `TestCopilotItemKeepsItsID`). An upstream whose ids agree goes through byte for byte (`TestItemIDsThatAgreeGoAsTheyCame`); a translated reply's ids are magpie's own.- A model's reply limit is published within the window beside it (#1438, `provider.OutputWithin`, `Entry.PublishedOutput`): `/v1/models`' `max_output_tokens` (`modelObject`), Cursor Private Inference's `capabilities.max_output_tokens` (`cursorLocalModel`), Muse Code's `limit.output` (`museModels`), the GUI's model and group rows (`providerInfo`, `providersState`), `magpie model output`, and every agent's file (`agent.maxTokens`, #338). The window and the output can come from different sources: Grok's backend lists grok-4.7's 256000 window, and models.dev fills its 500000 output (`catalog.Decorate` and `Provider.replyLimit` fill an output only where the vendor gives none). An unknown window or output is published as it is. The catalog keeps the unclamped `Entry.Output`, and a group's member is still asked for no more than that (`outputLimit`, `withMaxOutput`), so a request isn't lowered by the clamp. A limit the user set stays in their settings as they set it (`TestModelListsKeepOutputWithinTheWindow`). Outside a group, only a Max output the user set for the model (`Entry.OutputSet`) lowers a request (`userOutput`): Claude Code asks a claude-* model for its own full limit (128000 on Opus 5.5) and is told no figure of magpie's for it (`claudeOutput`), and a key whose quota is held per request as max_tokens times the price turned every turn away (YaCo on Discord, `TestUserMaxOutputLowersAPlainProvidersRequest`). A vendor's or models.dev's figure doesn't lower it, since it may be stale.-- `/v1/models` and `/v1/models/{id}` give each model magpie knows a price of its `pricing` in OpenRouter's shape, USD a token as decimal strings: `prompt` and `completion` always (a price set at 0 included), `input_cache_read` and `input_cache_write` only when that part has a price (`openRouterPricing`, `perToken` in [`gateway.go`](../../internal/gateway/gateway.go); cleary5779 on Discord, an agent showing what a call costs). The price is the one the Usage page counts the model at (`provider.EntryPricer`, as `EntryPriceIn`: the user's own, else the provider's list price or its maker's at its price rate; a subscription's model at its list price; a group only when every member costs the same), the base price only (no `Tiers`, no 1-hour write). A model no price is known for has no `pricing` key, never a 0. It is told to the callers `magpie_price` is (`local` or `sharedWith`), whether they ask or not. The list reads the settings, groups and providers once (`EntryPricer`), and `catalog.PricedBy` and `AtEndpoint` look a model up in indexes built once a catalog load (`priceIndexOf`, `endpoints`), not by walking every models.dev model a look-up: a 755-model list went from about 38ms to 18ms with pricing on, against about 10ms without, at load 65 (`TestModelsListPricing`, `TestPerToken`). Claude Desktop's, Claude Science's, Muse Code's, Codex's and Ollama's lists, the decision, image and video models carry no `pricing`: their clients read a shape of their own, and an image's price isn't a token's.+- `/v1/models` and `/v1/models/{id}` give each model magpie knows a price of its `pricing` in OpenRouter's shape, USD a token as decimal strings: `prompt` and `completion` always (a price set at 0 included), `input_cache_read` and `input_cache_write` only when that part has a price (`catalog.OpenRouterPricing`, `catalog.PerToken` in [`openrouter.go`](../../internal/catalog/openrouter.go), which an agent plugin's `connect` is given too; cleary5779 on Discord, an agent showing what a call costs). The price is the one the Usage page counts the model at (`provider.EntryPricer`, as `EntryPriceIn`: the user's own, else the provider's list price or its maker's at its price rate; a subscription's model at its list price; a group only when every member costs the same), the base price only (no `Tiers`, no 1-hour write). A model no price is known for has no `pricing` key, never a 0. It is told to the callers `magpie_price` is (`local` or `sharedWith`), whether they ask or not. The list reads the settings, groups and providers once (`EntryPricer`), and `catalog.PricedBy` and `AtEndpoint` look a model up in indexes built once a catalog load (`priceIndexOf`, `endpoints`), not by walking every models.dev model a look-up: a 755-model list went from about 38ms to 18ms with pricing on, against about 10ms without, at load 65 (`TestModelsListPricing`, `TestPerToken`). Claude Desktop's, Claude Science's, Muse Code's, Codex's and Ollama's lists, the decision, image and video models carry no `pricing`: their clients read a shape of their own, and an image's price isn't a token's.- A request that names no reply limit, translated to Anthropic's Messages API, which needs `max_tokens` (`forwardTranslated`), is sent the model's published limit (`askedOutput` in [`maxoutput.go`](../../internal/gateway/maxoutput.go)): the user's Max output, else the vendor's list or models.dev, within the window. `anthropicBody`'s `defaultMaxTokens` (16384) is left only for a model whose limit isn't known. Every Codex turn on a Claude went at 16384 before, and a long thinking and tool turn ran out of it: `stop_reason: max_tokens` reaches a Responses client as `incomplete_details.reason: "max_output_tokens"` (#1792, tensornull). A limit the client names goes as it is. The thinking budget fits under the filled limit as under one the client named (`TestAnthropicMaxTokensIsTheModels`).- A restart to update on a Mac or Linux hands the listening socket to thenew version ([GUI shell](gui-shell.md#a-restart-to-update-hands-the-gateway-over),diff --git a/internal/agent/plugged.go b/internal/agent/plugged.goindex b5223ac31..0b1fed9f2 100644--- a/internal/agent/plugged.go+++ b/internal/agent/plugged.go@@ -20,6 +20,7 @@ import ("github.com/tidwall/gjson""github.com/tidwall/jsonc""github.com/yetone/magpie/internal/agentplug"+ "github.com/yetone/magpie/internal/catalog""github.com/yetone/magpie/internal/edit""github.com/yetone/magpie/internal/gateway""github.com/yetone/magpie/internal/plugin"@@ -271,6 +272,16 @@ func plugged(home string, p *agentplug.Agent) *Agent {if j["efforts"] == nil {j["efforts"] = []string{}}+ // what /v1/models says of it too, by the same names, for an+ // agent built on the gateway (cleary5779 on Discord): the APIs+ // a request for it goes on untranslated, and what a token+ // costs; each left out when not known, never empty or 0+ if len(m.Endpoints) > 0 {+ j["native_endpoints"] = m.Endpoints+ }+ if m.Price != nil {+ j["pricing"] = catalog.OpenRouterPricing(*m.Price)+ }if m.ID == ref {model = j}diff --git a/internal/agent/plugged_connect_facts_test.go b/internal/agent/plugged_connect_facts_test.gonew file mode 100644index 000000000..a1616ef37--- /dev/null+++ b/internal/agent/plugged_connect_facts_test.go@@ -0,0 +1,98 @@+package agent++import (+ "encoding/json"+ "os"+ "path/filepath"+ "testing"++ "github.com/yetone/magpie/internal/catalog"+ "github.com/yetone/magpie/internal/provider"+)++// An agent plugin's connect is told, of each model in models and of+// model, what /v1/models says of it by the same names: native_endpoints,+// the APIs a request goes on untranslated, and pricing, OpenRouter's USD+// a token (cleary5779 on Discord, a self-built agent picking the API that+// passes straight through and showing what a call costs). A model with no+// known price has no pricing at all, never a 0.+func TestPluggedConnectSeesEndpointsAndPricing(t *testing.T) {+ home := pluggedHome(t, `+export const agent = { id: "facts", name: "Facts", config: "~/.facts.json", model: "model" };+export function connect({ gateway, model, models }) {+ return { "seen": JSON.stringify({ model, models }) };+}+`)+ if err := provider.SetModelPrice("deepseek/pro", &catalog.Price{Input: 0.3, Output: 1.2, CacheRead: 0.03}); err != nil {+ t.Fatal(err)+ }+ a, err := Find("facts")+ if err != nil {+ t.Fatal(err)+ }+ if err := a.Field("model").Set("magpie/deepseek/pro"); err != nil {+ t.Fatal(err)+ }+ b, err := os.ReadFile(filepath.Join(home, ".facts.json"))+ if err != nil {+ t.Fatal(err)+ }+ var file struct{ Seen string }+ if err := json.Unmarshal(b, &file); err != nil {+ t.Fatalf("%v:\n%s", err, b)+ }+ type entry struct {+ ID string `json:"id"`+ Native []string `json:"native_endpoints"`+ Pricing map[string]string `json:"pricing"`+ HasPrice bool `json:"-"`+ HasNative bool `json:"-"`+ }+ var seen struct {+ Model map[string]json.RawMessage `json:"model"`+ Models []map[string]json.RawMessage `json:"models"`+ }+ if err := json.Unmarshal([]byte(file.Seen), &seen); err != nil {+ t.Fatalf("%v:\n%s", err, file.Seen)+ }+ read := func(raw map[string]json.RawMessage) entry {+ var e entry+ b, _ := json.Marshal(raw)+ json.Unmarshal(b, &e)+ _, e.HasPrice = raw["pricing"]+ _, e.HasNative = raw["native_endpoints"]+ return e+ }+ byID := map[string]entry{}+ for _, m := range seen.Models {+ e := read(m)+ byID[e.ID] = e+ }+ pro, flash, model := byID["deepseek/pro"], byID["deepseek/flash"], read(seen.Model)+ want := map[string]string{"prompt": "0.0000003", "completion": "0.0000012", "input_cache_read": "0.00000003"}+ for name, e := range map[string]entry{"models' pro": pro, "model": model} {+ if len(e.Native) != 1 || e.Native[0] != "/v1/chat/completions" {+ t.Errorf("%s native_endpoints = %v, want [/v1/chat/completions]:\n%s", name, e.Native, file.Seen)+ }+ if len(e.Pricing) != len(want) {+ t.Errorf("%s pricing = %v, want %v", name, e.Pricing, want)+ }+ for k, v := range want {+ if e.Pricing[k] != v {+ t.Errorf("%s pricing[%s] = %q, want %q", name, k, e.Pricing[k], v)+ }+ }+ }+ if flash.ID == "" || !flash.HasNative {+ t.Errorf("flash missing or without native_endpoints:\n%s", file.Seen)+ }+ if flash.HasPrice {+ t.Errorf("unpriced flash has pricing %v, want none", flash.Pricing)+ }+ // what connect was told before stays as it was+ for _, k := range []string{"id", "name", "context", "output", "images", "efforts"} {+ if _, ok := seen.Model[k]; !ok {+ t.Errorf("model lost %q:\n%s", k, file.Seen)+ }+ }+}diff --git a/internal/agent/route.go b/internal/agent/route.goindex 7d9234e8e..30f283348 100644--- a/internal/agent/route.go+++ b/internal/agent/route.go@@ -242,6 +242,9 @@ func magpieModels(agent string) []catalog.Model {// lists offer them: Fast in the Codex CLI magpie writes// magpie-models.json for (#1530)provider.CodexTiers(&m, e, members)+ // the gateway paths it goes on untranslated, as /v1/models says+ // them: what an agent plugin's connect is told (cleary5779)+ m.Endpoints = provider.NativeEndpoints(e)// Codex's /fast on a ChatGPT account's own GPT model, which// OpenCode has no command for and takes as variants (#2379); a// group is sent fast as the group says, as a fast pick isdiff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.goindex 93f883f04..56db532c9 100644--- a/internal/catalog/catalog.go+++ b/internal/catalog/catalog.go@@ -38,6 +38,11 @@ type Model struct {// APIs, when the vendor says, are the APIs the model is served on// ("chat", "responses", "anthropic"); empty is not known.APIs []string `json:",omitempty"`+ // Endpoints, in magpie's own models for an agent, are the gateway+ // paths a request for it is relayed on as it is+ // (provider.NativeEndpoints, /v1/models' native_endpoints); none for a+ // group or a model translated anyway.+ Endpoints []string `json:"-"`// Images is set on a model that takes images as input.Images bool `json:",omitempty"`// ImageInput is the source's explicit answer; nil means it did not say.diff --git a/internal/catalog/openrouter.go b/internal/catalog/openrouter.gonew file mode 100644index 000000000..65b223051--- /dev/null+++ b/internal/catalog/openrouter.go@@ -0,0 +1,45 @@+package catalog++import (+ "strconv"+ "strings"+)++// OpenRouterPricing is a price as OpenRouter's model list writes it+// (gateway /v1/models' and an agent plugin's connect's "pricing"), the+// shape agents and SDKs built on that list read: USD a token, as decimal+// strings. prompt and completion are always there, a price set at 0+// included, since the price is known; a cache read or write only when it+// has a price, as a part a list leaves at 0 is one it doesn't give. The+// base price only: a model billed more above a prompt size (Tiers) tells+// what it costs below it, and the 1-hour cache write has no field there.+func OpenRouterPricing(pr Price) map[string]string {+ out := map[string]string{"prompt": PerToken(pr.Input), "completion": PerToken(pr.Output)}+ if pr.CacheRead > 0 {+ out["input_cache_read"] = PerToken(pr.CacheRead)+ }+ if pr.CacheWrite > 0 {+ out["input_cache_write"] = PerToken(pr.CacheWrite)+ }+ return out+}++// PerToken is a price of USD a million tokens as USD a token, written as+// a decimal: the decimal point moved, not the float divided, so $0.3 is+// "0.0000003" and not 2.9999999999999997e-07.+func PerToken(perMillion float64) string {+ s := strconv.FormatFloat(max(perMillion, 0), 'f', -1, 64)+ whole, frac, _ := strings.Cut(s, ".")+ if len(whole) < 7 {+ whole = strings.Repeat("0", 7-len(whole)) + whole+ }+ cut := len(whole) - 6+ whole, frac = strings.TrimLeft(whole[:cut], "0"), strings.TrimRight(whole[cut:]+frac, "0")+ if whole == "" {+ whole = "0"+ }+ if frac == "" {+ return whole+ }+ return whole + "." + frac+}diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.goindex d52cdf510..b920924c4 100644--- a/internal/gateway/gateway.go+++ b/internal/gateway/gateway.go@@ -936,7 +936,7 @@ func modelObject(e provider.Entry) map[string]any {// the APIs a request for the model goes on as it is, so it sends each// one on an API of these rather than having it translated twice, and// whether it takes images- if native := nativeEndpoints(e); len(native) > 0 {+ if native := provider.NativeEndpoints(e); len(native) > 0 {m["native_endpoints"] = native}// what it takes and gives: every kind its source listed, audio, video@@ -960,50 +960,12 @@ func pricedModelObject(r *http.Request, e provider.Entry) map[string]any {m := modelObject(e)if local(r) || sharedWith(r) {if pr, ok := provider.EntryPriceIn(settings.Load(), provider.GroupFinder(), e); ok {- m["pricing"] = openRouterPricing(pr)+ m["pricing"] = catalog.OpenRouterPricing(pr)}}return m}-// openRouterPricing is a price as OpenRouter's model list writes it, the-// shape agents and SDKs built on that list read: USD a token, as decimal-// strings. prompt and completion are always there, a price set at 0-// included, since the price is known; a cache read or write only when it-// has a price, as a part a list leaves at 0 is one it doesn't give. The-// base price only: a model billed more above a prompt size (Tiers) tells-// what it costs below it, and the 1-hour cache write has no field there.-func openRouterPricing(pr catalog.Price) map[string]string {- out := map[string]string{"prompt": perToken(pr.Input), "completion": perToken(pr.Output)}- if pr.CacheRead > 0 {- out["input_cache_read"] = perToken(pr.CacheRead)- }- if pr.CacheWrite > 0 {- out["input_cache_write"] = perToken(pr.CacheWrite)- }- return out-}--// perToken is a price of USD a million tokens as USD a token, written as-// a decimal: the decimal point moved, not the float divided, so $0.3 is-// "0.0000003" and not 2.9999999999999997e-07.-func perToken(perMillion float64) string {- s := strconv.FormatFloat(max(perMillion, 0), 'f', -1, 64)- whole, frac, _ := strings.Cut(s, ".")- if len(whole) < 7 {- whole = strings.Repeat("0", 7-len(whole)) + whole- }- cut := len(whole) - 6- whole, frac = strings.TrimLeft(whole[:cut], "0"), strings.TrimRight(whole[cut:]+frac, "0")- if whole == "" {- whole = "0"- }- if frac == "" {- return whole- }- return whole + "." + frac-}-// cursorLocalModel adds what Cursor Private Inference reads of a model// (#299): api_types, the APIs it may ask it on — those the model is relayed// on as it is, so a Claude served on Anthropic Messages is asked there and@@ -1021,7 +983,7 @@ func perToken(perMillion float64) string {func cursorLocalModel(m map[string]any, e provider.Entry) {names := map[string]string{"/v1/chat/completions": "chat_completions", "/v1/responses": "responses", "/v1/messages": "anthropic_messages"}types := []string{}- for _, p := range nativeEndpoints(e) {+ for _, p := range provider.NativeEndpoints(e) {types = append(types, names[p])}if len(types) == 0 {@@ -1051,26 +1013,6 @@ func cursorLocalModel(m map[string]any, e provider.Entry) {m["capabilities"] = c}-// nativeEndpoints are the paths a request for the model is relayed on to-// its provider as it is: the APIs the provider serves it on. None for a-// routing group, whose members may speak any, or a model every request-// to is translated anyway (a subscription served through its agent's own-// API).-func nativeEndpoints(e provider.Entry) []string {- p := e.Provider- if e.Group != "" || p.Native(e.Model) == "" {- return nil- }- apis := p.APIs(e.Model)- var out []string- for _, pr := range p.Speaks() {- if slices.Contains(provider.Protocols, pr) && (apis == nil || slices.Contains(apis, pr)) {- out = append(out, map[provider.Protocol]string{provider.Chat: "/v1/chat/completions", provider.Responses: "/v1/responses", provider.Anthropic: "/v1/messages"}[pr])- }- }- return out-}-// drawerObjects are the image models magpie draws with, as another magpie// asks for them in its list (provider.DrawersHeader): "kind": "image",// which an agent's list never has, so it takes none for a model to chat@@ -1193,7 +1135,7 @@ func (s *Server) models(w http.ResponseWriter, r *http.Request) {}if told {if pr, ok := priceOf(e); ok {- m["pricing"] = openRouterPricing(pr)+ m["pricing"] = catalog.OpenRouterPricing(pr)if prices {m["magpie_price"] = pr}diff --git a/internal/gateway/models_pricing_test.go b/internal/gateway/models_pricing_test.goindex 869d6fc54..b8e2db05c 100644--- a/internal/gateway/models_pricing_test.go+++ b/internal/gateway/models_pricing_test.go@@ -94,12 +94,12 @@ func TestModelsListPricing(t *testing.T) {func TestPerToken(t *testing.T) {for in, want := range map[float64]string{0: "0", 3: "0.000003", 0.3: "0.0000003", 3.75: "0.00000375",15: "0.000015", 1234567: "1.234567", 12345678.9: "12.3456789", 0.075: "0.000000075"} {- if got := perToken(in); got != want {- t.Errorf("perToken(%v) = %s, want %s", in, got, want)+ if got := catalog.PerToken(in); got != want {+ t.Errorf("PerToken(%v) = %s, want %s", in, got, want)}}// a user's free price is known: both parts there, at 0- got, _ := json.Marshal(openRouterPricing(catalog.Price{}))+ got, _ := json.Marshal(catalog.OpenRouterPricing(catalog.Price{}))if string(got) != `{"completion":"0","prompt":"0"}` {t.Errorf("a free model's pricing: %s", got)}diff --git a/internal/gateway/opencode_wire_test.go b/internal/gateway/opencode_wire_test.goindex 3c646a560..50637a86c 100644--- a/internal/gateway/opencode_wire_test.go+++ b/internal/gateway/opencode_wire_test.go@@ -134,7 +134,7 @@ func TestOtherRelayKeepsItsOneAPI(t *testing.T) {if apis := p.APIs("gpt-6-luna"); apis != nil {t.Errorf("relay gpt-6-luna APIs %v, want none named", apis)}- if got := nativeEndpoints(provider.Entry{Provider: *p, Model: "gpt-6-luna", ID: "relay/gpt-6-luna"}); len(got) != 1 || got[0] != "/v1/chat/completions" {+ if got := provider.NativeEndpoints(provider.Entry{Provider: *p, Model: "gpt-6-luna", ID: "relay/gpt-6-luna"}); len(got) != 1 || got[0] != "/v1/chat/completions" {t.Errorf("relay native_endpoints %v", got)}}diff --git a/internal/provider/native_endpoints.go b/internal/provider/native_endpoints.gonew file mode 100644index 000000000..b9570527b--- /dev/null+++ b/internal/provider/native_endpoints.go@@ -0,0 +1,24 @@+package provider++import "slices"++// NativeEndpoints are the paths a request for the model is relayed on to+// its provider as it is (/v1/models' and an agent plugin's connect's+// "native_endpoints"): the APIs the provider serves it on. None for a+// routing group, whose members may speak any, or a model every request+// to is translated anyway (a subscription served through its agent's own+// API).+func NativeEndpoints(e Entry) []string {+ p := e.Provider+ if e.Group != "" || p.Native(e.Model) == "" {+ return nil+ }+ apis := p.APIs(e.Model)+ var out []string+ for _, pr := range p.Speaks() {+ if slices.Contains(Protocols, pr) && (apis == nil || slices.Contains(apis, pr)) {+ out = append(out, map[Protocol]string{Chat: "/v1/chat/completions", Responses: "/v1/responses", Anthropic: "/v1/messages"}[pr])+ }+ }+ return out+}diff --git a/site/public/docs/ja/plugins.html b/site/public/docs/ja/plugins.htmlindex ed6799ce5..f706dc5be 100644--- a/site/public/docs/ja/plugins.html+++ b/site/public/docs/ja/plugins.html@@ -788,7 +788,7 @@ claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/to<tr><td><code>library</code></td><td><span class="ui">ライブラリ</span>が渡すものをエージェントがどこで読むか:<code>instructions</code>(毎回の会話の前に読む Markdown ファイル)、<code>mcp</code>(MCP サーバーのファイル)とその書き方を表す <code>mcpFormat</code>(どのエージェントのファイルと同じ形か:<code>alma</code>, <code>antigravity</code>, <code>claude</code>, <code>cline</code>, <code>codex</code>, <code>commandcode</code>, <code>copilot</code>, <code>crush</code>, <code>cursor</code>, <code>devin</code>, <code>gemini</code>, <code>goose</code>, <code>grok</code>, <code>hermes</code>, <code>kimi</code>, <code>omp</code>, <code>opencode</code>, <code>zed</code>。<code>claude</code> は <code>{"mcpServers": {…}}</code>)、<code>skills</code>(<code>SKILL.md</code> のフォルダを置くフォルダ)。どれも省略でき、<code>~</code> と <code>$VAR</code> は展開されます:<code>library: { instructions: "~/.toy/AGENTS.md", mcp: "~/.toy/mcp.json", mcpFormat: "claude", skills: "~/.toy/skills" }</code>。書かなければライブラリからは何も渡されず、渡そうとするとプラグインが書くべきキーを示して断られます。</td></tr></table></div><h3>connect</h3>- <p><code>connect(input)</code> はモデルの横に書き込む他のキーを、キーのパスと値で返します。<code>async</code> でも構いません。受け取るのは <code>gateway</code>(<code>url</code>、<code>/v1</code> で終わる URL の <code>v1</code>、エージェント専用のキー <code>key</code>。リクエストはその id で数えられます)、<code>model</code>(<code>id</code>、<code>name</code>、<code>context</code>、<code>output</code>、<code>images</code>、<code>efforts</code>)、<code>models</code>(magpie がエージェントに出すすべてのモデル、同じ形)、<code>agent</code>(<code>id</code>、<code>config</code>)です。<code>connect</code> がないプラグインはモデルだけを書きます。magpie のモデルが変わると <code>connect</code> がもう一度呼ばれるので、書いたモデル一覧は最新のまま保たれます。</p>+ <p><code>connect(input)</code> はモデルの横に書き込む他のキーを、キーのパスと値で返します。<code>async</code> でも構いません。受け取るのは <code>gateway</code>(<code>url</code>、<code>/v1</code> で終わる URL の <code>v1</code>、エージェント専用のキー <code>key</code>。リクエストはその id で数えられます)、<code>model</code>(<code>id</code>、<code>name</code>、<code>context</code>、<code>output</code>、<code>images</code>、<code>efforts</code>、そして <code>/v1/models</code> と同じ名前の <code>native_endpoints</code>(リクエストが変換されずにそのまま通るゲートウェイのパス、例えば <code>["/v1/chat/completions"]</code>)と <code>pricing</code>(1 トークンあたりの USD、10 進の文字列:<code>prompt</code>、<code>completion</code>、<code>input_cache_read</code>、<code>input_cache_write</code>。分からないものは含まれず、空や 0 にはなりません))、<code>models</code>(magpie がエージェントに出すすべてのモデル、同じ形)、<code>agent</code>(<code>id</code>、<code>config</code>)です。<code>connect</code> がないプラグインはモデルだけを書きます。magpie のモデルが変わると <code>connect</code> がもう一度呼ばれるので、書いたモデル一覧は最新のまま保たれます。</p><h3>magpie がすること</h3><ul><li><b>書き込み。</b>各キーをその場で書き換え、ユーザーのコメントや他のキーは残します。最初に書く前に、各キーの元の値を型ごと(数値は数値のまま)取っておきます。</li>diff --git a/site/public/docs/plugins.html b/site/public/docs/plugins.htmlindex 814ec5f8a..4b6a47061 100644--- a/site/public/docs/plugins.html+++ b/site/public/docs/plugins.html@@ -788,7 +788,7 @@ claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/to<tr><td><code>library</code></td><td>Where the agent reads what the <span class="ui">Library</span> gives: <code>instructions</code> (a Markdown file it reads before every conversation), <code>mcp</code> (its MCP servers file) with <code>mcpFormat</code>, the agent whose file it is shaped like (<code>alma</code>, <code>antigravity</code>, <code>claude</code>, <code>cline</code>, <code>codex</code>, <code>commandcode</code>, <code>copilot</code>, <code>crush</code>, <code>cursor</code>, <code>devin</code>, <code>gemini</code>, <code>goose</code>, <code>grok</code>, <code>hermes</code>, <code>kimi</code>, <code>omp</code>, <code>opencode</code>, <code>zed</code>; <code>claude</code> is <code>{"mcpServers": {…}}</code>), and <code>skills</code> (a folder of <code>SKILL.md</code> folders). Each is optional, with <code>~</code> and <code>$VAR</code> expanded: <code>library: { instructions: "~/.toy/AGENTS.md", mcp: "~/.toy/mcp.json", mcpFormat: "claude", skills: "~/.toy/skills" }</code>. Without it the agent is given nothing from the Library, and giving it an item is refused, naming the key its plugin would set.</td></tr></table></div><h3>connect</h3>- <p><code>connect(input)</code> returns the other keys to write beside the model, by key path, each with its value; it may be <code>async</code>. It is given <code>gateway</code> (<code>url</code>, <code>v1</code> — the URL ending in <code>/v1</code> — and <code>key</code>, the agent’s own key, which counts its requests under its id), <code>model</code> (<code>id</code>, <code>name</code>, <code>context</code>, <code>output</code>, <code>images</code>, <code>efforts</code>), <code>models</code> (every model magpie offers the agent, the same way) and <code>agent</code> (<code>id</code>, <code>config</code>). A plugin without <code>connect</code> writes only the model. It is called again when magpie’s models change, so a list it writes stays current.</p>+ <p><code>connect(input)</code> returns the other keys to write beside the model, by key path, each with its value; it may be <code>async</code>. It is given <code>gateway</code> (<code>url</code>, <code>v1</code> — the URL ending in <code>/v1</code> — and <code>key</code>, the agent’s own key, which counts its requests under its id), <code>model</code> (<code>id</code>, <code>name</code>, <code>context</code>, <code>output</code>, <code>images</code>, <code>efforts</code>, and as <code>/v1/models</code> names them <code>native_endpoints</code>, the gateway paths a request for it goes on untranslated such as <code>["/v1/chat/completions"]</code>, and <code>pricing</code>, USD a token as decimal strings: <code>prompt</code>, <code>completion</code>, <code>input_cache_read</code>, <code>input_cache_write</code>; each left out when not known, never empty or 0), <code>models</code> (every model magpie offers the agent, the same way) and <code>agent</code> (<code>id</code>, <code>config</code>). A plugin without <code>connect</code> writes only the model. It is called again when magpie’s models change, so a list it writes stays current.</p><h3>What magpie does with it</h3><ul><li><b>Writing.</b> Each key is set in place, the user’s comments and other keys kept. Before the first write, what each key held is kept aside, typed (a number stays a number).</li>diff --git a/site/public/docs/zh/plugins.html b/site/public/docs/zh/plugins.htmlindex c1592ec11..54ae61cf0 100644--- a/site/public/docs/zh/plugins.html+++ b/site/public/docs/zh/plugins.html@@ -788,7 +788,7 @@ claude mcp add --transport http magpie-tools http://127.0.0.1:3425/mcp/magpie/to<tr><td><code>library</code></td><td>Agent 从哪里读<span class="ui">资源库</span>给它的东西:<code>instructions</code>(每次对话前读的 Markdown 文件)、<code>mcp</code>(它的 MCP 服务器文件)和 <code>mcpFormat</code>(这个文件的写法跟哪个 Agent 的一样:<code>alma</code>, <code>antigravity</code>, <code>claude</code>, <code>cline</code>, <code>codex</code>, <code>commandcode</code>, <code>copilot</code>, <code>crush</code>, <code>cursor</code>, <code>devin</code>, <code>gemini</code>, <code>goose</code>, <code>grok</code>, <code>hermes</code>, <code>kimi</code>, <code>omp</code>, <code>opencode</code>, <code>zed</code>;<code>claude</code> 即 <code>{"mcpServers": {…}}</code>),以及 <code>skills</code>(放 <code>SKILL.md</code> 文件夹的目录)。每项都可省略,<code>~</code> 和 <code>$VAR</code> 会展开:<code>library: { instructions: "~/.toy/AGENTS.md", mcp: "~/.toy/mcp.json", mcpFormat: "claude", skills: "~/.toy/skills" }</code>。不写的话,资源库不会给它任何东西,给它某一项时会被拒绝,并说明插件该写哪个键。</td></tr></table></div><h3>connect</h3>- <p><code>connect(input)</code> 返回要在模型旁边一起写入的其他键,按键路径给出各自的值;可以是 <code>async</code>。它拿到 <code>gateway</code>(<code>url</code>、<code>v1</code>——以 <code>/v1</code> 结尾的地址——和 <code>key</code>,即这个 Agent 自己的 key,请求会按它的 id 计入用量)、<code>model</code>(<code>id</code>、<code>name</code>、<code>context</code>、<code>output</code>、<code>images</code>、<code>efforts</code>)、<code>models</code>(magpie 给这个 Agent 的所有模型,格式相同)和 <code>agent</code>(<code>id</code>、<code>config</code>)。没有 <code>connect</code> 的插件只写模型。magpie 的模型有变化时会再调用一次 <code>connect</code>,它写的模型列表因此保持最新。</p>+ <p><code>connect(input)</code> 返回要在模型旁边一起写入的其他键,按键路径给出各自的值;可以是 <code>async</code>。它拿到 <code>gateway</code>(<code>url</code>、<code>v1</code>——以 <code>/v1</code> 结尾的地址——和 <code>key</code>,即这个 Agent 自己的 key,请求会按它的 id 计入用量)、<code>model</code>(<code>id</code>、<code>name</code>、<code>context</code>、<code>output</code>、<code>images</code>、<code>efforts</code>,以及与 <code>/v1/models</code> 同名的 <code>native_endpoints</code>——请求不经转换直接走的网关路径,如 <code>["/v1/chat/completions"]</code>——和 <code>pricing</code>——每 token 的美元价格,十进制字符串:<code>prompt</code>、<code>completion</code>、<code>input_cache_read</code>、<code>input_cache_write</code>;不知道的就不给,绝不是空或 0)、<code>models</code>(magpie 给这个 Agent 的所有模型,格式相同)和 <code>agent</code>(<code>id</code>、<code>config</code>)。没有 <code>connect</code> 的插件只写模型。magpie 的模型有变化时会再调用一次 <code>connect</code>,它写的模型列表因此保持最新。</p><h3>magpie 怎么用它</h3><ul><li><b>写入。</b>每个键原地修改,用户的注释和其他键都保留。第一次写之前,每个键原来的值会按原类型存起来(数字仍是数字)。</li>